src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java

Tue, 19 May 2020 19:34:57 +0200

author
Mike Becker <universe@uap-core.de>
date
Tue, 19 May 2020 19:34:57 +0200
changeset 70
821c4950b619
parent 63
51aa5e267c7f
child 71
dca186d3911f
permissions
-rw-r--r--

removes the sub menu and removes the home module
fixes the queries in the PGIssueDao
adds placeholder for a breadcrumb menu

     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2018 Mike Becker. All rights reserved.
     5  *
     6  * Redistribution and use in source and binary forms, with or without
     7  * modification, are permitted provided that the following conditions are met:
     8  *
     9  *   1. Redistributions of source code must retain the above copyright
    10  *      notice, this list of conditions and the following disclaimer.
    11  *
    12  *   2. Redistributions in binary form must reproduce the above copyright
    13  *      notice, this list of conditions and the following disclaimer in the
    14  *      documentation and/or other materials provided with the distribution.
    15  *
    16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    26  * POSSIBILITY OF SUCH DAMAGE.
    27  *
    28  */
    29 package de.uapcore.lightpit;
    31 import de.uapcore.lightpit.dao.DataAccessObjects;
    32 import de.uapcore.lightpit.dao.postgres.PGDataAccessObjects;
    33 import org.slf4j.Logger;
    34 import org.slf4j.LoggerFactory;
    36 import javax.servlet.ServletException;
    37 import javax.servlet.http.HttpServlet;
    38 import javax.servlet.http.HttpServletRequest;
    39 import javax.servlet.http.HttpServletResponse;
    40 import javax.servlet.http.HttpSession;
    41 import java.io.IOException;
    42 import java.lang.reflect.Constructor;
    43 import java.lang.reflect.Method;
    44 import java.lang.reflect.Modifier;
    45 import java.sql.Connection;
    46 import java.sql.SQLException;
    47 import java.util.*;
    48 import java.util.function.Function;
    50 /**
    51  * A special implementation of a HTTPServlet which is focused on implementing
    52  * the necessary functionality for {@link LightPITModule}s.
    53  */
    54 public abstract class AbstractLightPITServlet extends HttpServlet {
    56     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
    58     private static final String SITE_JSP = Functions.jspPath("site");
    60     /**
    61      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    62      */
    63     private LightPITModule.ELProxy moduleInfo = null;
    65     @FunctionalInterface
    66     protected interface SQLFindFunction<K, T> {
    67         T apply(K key) throws SQLException;
    69         default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
    70             Objects.requireNonNull(before);
    71             return (v) -> this.apply(before.apply(v));
    72         }
    74         default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
    75             Objects.requireNonNull(after);
    76             return (t) -> after.apply(this.apply(t));
    77         }
    79         static <K> Function<K, K> identity() {
    80             return (t) -> t;
    81         }
    82     }
    84     /**
    85      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    86      * <p>
    87      * Paths in this map must always start with a leading slash, although
    88      * the specification in the annotation must not start with a leading slash.
    89      * <p>
    90      * The reason for this is the different handling of empty paths in
    91      * {@link HttpServletRequest#getPathInfo()}.
    92      */
    93     private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
    95     /**
    96      * Gives implementing modules access to the {@link ModuleManager}.
    97      *
    98      * @return the module manager
    99      */
   100     protected final ModuleManager getModuleManager() {
   101         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
   102     }
   105     /**
   106      * Creates a set of data access objects for the specified connection.
   107      *
   108      * @param connection the SQL connection
   109      * @return a set of data access objects
   110      */
   111     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
   112         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   113         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
   114             return new PGDataAccessObjects(connection);
   115         }
   116         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
   117     }
   119     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   120         try {
   121             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   122             final var paramTypes = method.getParameterTypes();
   123             final var paramValues = new Object[paramTypes.length];
   124             for (int i = 0; i < paramTypes.length; i++) {
   125                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   126                     paramValues[i] = req;
   127                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   128                     paramValues[i] = resp;
   129                 }
   130                 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
   131                     paramValues[i] = dao;
   132                 }
   133             }
   134             return (ResponseType) method.invoke(this, paramValues);
   135         } catch (ReflectiveOperationException | ClassCastException ex) {
   136             LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
   137             LOG.debug("Details: ", ex);
   138             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   139             return ResponseType.NONE;
   140         }
   141     }
   143     @Override
   144     public void init() throws ServletException {
   145         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   146                 .map(LightPITModule.ELProxy::new).orElse(null);
   148         if (moduleInfo != null) {
   149             scanForRequestMappings();
   150         }
   152         LOG.trace("{} initialized", getServletName());
   153     }
   155     private void scanForRequestMappings() {
   156         try {
   157             Method[] methods = getClass().getDeclaredMethods();
   158             for (Method method : methods) {
   159                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   160                 if (mapping.isPresent()) {
   161                     if (!Modifier.isPublic(method.getModifiers())) {
   162                         LOG.warn("{} is annotated with {} but is not public",
   163                                 method.getName(), RequestMapping.class.getSimpleName()
   164                         );
   165                         continue;
   166                     }
   167                     if (Modifier.isAbstract(method.getModifiers())) {
   168                         LOG.warn("{} is annotated with {} but is abstract",
   169                                 method.getName(), RequestMapping.class.getSimpleName()
   170                         );
   171                         continue;
   172                     }
   173                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   174                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   175                                 method.getName(), RequestMapping.class.getSimpleName()
   176                         );
   177                         continue;
   178                     }
   180                     boolean paramsInjectible = true;
   181                     for (var param : method.getParameterTypes()) {
   182                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   183                                 || HttpServletResponse.class.isAssignableFrom(param)
   184                                 || DataAccessObjects.class.isAssignableFrom(param);
   185                     }
   186                     if (paramsInjectible) {
   187                         String requestPath = "/" + mapping.get().requestPath();
   189                         if (mappings
   190                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   191                                 .putIfAbsent(requestPath, method) != null) {
   192                             LOG.warn("{} {} has multiple mappings",
   193                                     mapping.get().method(),
   194                                     mapping.get().requestPath()
   195                             );
   196                         }
   198                         LOG.debug("{} {} maps to {}::{}",
   199                                 mapping.get().method(),
   200                                 requestPath,
   201                                 getClass().getSimpleName(),
   202                                 method.getName()
   203                         );
   204                     } else {
   205                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   206                                 method.getName(), RequestMapping.class.getSimpleName()
   207                         );
   208                     }
   209                 }
   210             }
   211         } catch (SecurityException ex) {
   212             LOG.error("Scan for request mappings on declared methods failed.", ex);
   213         }
   214     }
   216     @Override
   217     public void destroy() {
   218         mappings.clear();
   219         LOG.trace("{} destroyed", getServletName());
   220     }
   222     /**
   223      * Sets the name of the dynamic fragment.
   224      * <p>
   225      * It is sufficient to specify the name without any extension. The extension
   226      * is added automatically if not specified.
   227      * <p>
   228      * The fragment must be located in the dynamic fragments folder.
   229      *
   230      * @param req          the servlet request object
   231      * @param fragmentName the name of the fragment
   232      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   233      */
   234     protected void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   235         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   236     }
   238     /**
   239      * @param req      the servlet request object
   240      * @param location the location where to redirect
   241      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   242      */
   243     protected void setRedirectLocation(HttpServletRequest req, String location) {
   244         if (location.startsWith("./")) {
   245             location = location.replaceFirst("\\./", Functions.baseHref(req));
   246         }
   247         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   248     }
   250     /**
   251      * Specifies the name of an additional stylesheet used by the module.
   252      * <p>
   253      * Setting an additional stylesheet is optional, but quite common for HTML
   254      * output.
   255      * <p>
   256      * It is sufficient to specify the name without any extension. The extension
   257      * is added automatically if not specified.
   258      *
   259      * @param req        the servlet request object
   260      * @param stylesheet the name of the stylesheet
   261      */
   262     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   263         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   264     }
   266     /**
   267      * Obtains a request parameter of the specified type.
   268      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   269      * The constructor of the specified type may throw an exception on conversion failures.
   270      *
   271      * @param req the servlet request object
   272      * @param clazz the class object of the expected type
   273      * @param name the name of the parameter
   274      * @param <T> the expected type
   275      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   276      */
   277     protected<T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   278         final String paramValue = req.getParameter(name);
   279         if (paramValue == null) return Optional.empty();
   280         if (clazz.equals(String.class)) return Optional.of((T)paramValue);
   281         try {
   282             final Constructor<T> ctor = clazz.getConstructor(String.class);
   283             return Optional.of(ctor.newInstance(paramValue));
   284         } catch (ReflectiveOperationException e) {
   285             throw new RuntimeException(e);
   286         }
   288     }
   290     /**
   291      * Tries to look up an entity with a key obtained from a request parameter.
   292      *
   293      * @param req the servlet request object
   294      * @param clazz the class representing the type of the request parameter
   295      * @param name the name of the request parameter
   296      * @param find the find function (typically a DAO function)
   297      * @param <T> the type of the request parameter
   298      * @param <R> the type of the looked up entity
   299      * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
   300      * @throws SQLException if the find function throws an exception
   301      */
   302     protected<T,R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
   303         final var param = getParameter(req, clazz, name);
   304         if (param.isPresent()) {
   305             return Optional.ofNullable(find.apply(param.get()));
   306         } else {
   307             return Optional.empty();
   308         }
   309     }
   311     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   312             throws IOException, ServletException {
   314         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   315         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   316     }
   318     private String sanitizeRequestPath(HttpServletRequest req) {
   319         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   320     }
   322     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   323         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   324     }
   326     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   327             throws ServletException, IOException {
   328         switch (type) {
   329             case NONE:
   330                 return;
   331             case HTML:
   332                 forwardToFullView(req, resp);
   333                 return;
   334             // TODO: implement remaining response types
   335             default:
   336                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   337         }
   338     }
   340     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   342         // choose the requested language as session language (if available) or fall back to english, otherwise
   343         HttpSession session = req.getSession();
   344         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   345             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   346             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   347             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   348             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   349             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   350         } else {
   351             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   352             resp.setLocale(sessionLocale);
   353             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   354         }
   356         // set some internal request attributes
   357         final String fullPath = Functions.fullPath(req);
   358         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   359         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   360         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   362         // if this is an error path, bypass the normal flow
   363         if (fullPath.startsWith("/error/")) {
   364             final var mapping = findMapping(method, req);
   365             if (mapping.isPresent()) {
   366                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   367             }
   368             return;
   369         }
   371         // obtain a connection and create the data access objects
   372         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   373         final var ds = db.getDataSource();
   374         if (ds == null) {
   375             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   376             return;
   377         }
   378         try (final var connection = ds.getConnection()) {
   379             final var dao = createDataAccessObjects(connection);
   380             try {
   381                 connection.setAutoCommit(false);
   382                 // call the handler, if available, or send an HTTP 404 error
   383                 final var mapping = findMapping(method, req);
   384                 if (mapping.isPresent()) {
   385                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   386                 } else {
   387                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   388                 }
   389                 connection.commit();
   390             } catch (SQLException ex) {
   391                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   392                 LOG.debug("Details: ", ex);
   393                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   394                 connection.rollback();
   395             }
   396         } catch (SQLException ex) {
   397             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   398             LOG.debug("Details: ", ex);
   399             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   400         }
   401     }
   403     @Override
   404     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   405             throws ServletException, IOException {
   406         doProcess(HttpMethod.GET, req, resp);
   407     }
   409     @Override
   410     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   411             throws ServletException, IOException {
   412         doProcess(HttpMethod.POST, req, resp);
   413     }
   414 }

mercurial