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

Sun, 17 May 2020 16:00:13 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 17 May 2020 16:00:13 +0200
changeset 58
8d3047f78190
parent 57
1262b5433644
child 63
51aa5e267c7f
permissions
-rw-r--r--

fixes duplicated trailing slash if index path has a menu entry

     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.*;
    49 /**
    50  * A special implementation of a HTTPServlet which is focused on implementing
    51  * the necessary functionality for {@link LightPITModule}s.
    52  */
    53 public abstract class AbstractLightPITServlet extends HttpServlet {
    55     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
    57     private static final String SITE_JSP = Functions.jspPath("site");
    59     /**
    60      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    61      */
    62     private LightPITModule.ELProxy moduleInfo = null;
    64     /**
    65      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    66      * <p>
    67      * Paths in this map must always start with a leading slash, although
    68      * the specification in the annotation must not start with a leading slash.
    69      * <p>
    70      * The reason for this is the different handling of empty paths in
    71      * {@link HttpServletRequest#getPathInfo()}.
    72      */
    73     private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
    75     private final List<MenuEntry> subMenu = new ArrayList<>();
    77     /**
    78      * Gives implementing modules access to the {@link ModuleManager}.
    79      *
    80      * @return the module manager
    81      */
    82     protected final ModuleManager getModuleManager() {
    83         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
    84     }
    87     /**
    88      * Creates a set of data access objects for the specified connection.
    89      *
    90      * @param connection the SQL connection
    91      * @return a set of data access objects
    92      */
    93     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
    94         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
    95         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
    96             return new PGDataAccessObjects(connection);
    97         }
    98         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
    99     }
   101     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   102         try {
   103             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   104             final var paramTypes = method.getParameterTypes();
   105             final var paramValues = new Object[paramTypes.length];
   106             for (int i = 0; i < paramTypes.length; i++) {
   107                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   108                     paramValues[i] = req;
   109                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   110                     paramValues[i] = resp;
   111                 }
   112                 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
   113                     paramValues[i] = dao;
   114                 }
   115             }
   116             return (ResponseType) method.invoke(this, paramValues);
   117         } catch (ReflectiveOperationException | ClassCastException ex) {
   118             LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
   119             LOG.debug("Details: ", ex);
   120             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   121             return ResponseType.NONE;
   122         }
   123     }
   125     @Override
   126     public void init() throws ServletException {
   127         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   128                 .map(LightPITModule.ELProxy::new).orElse(null);
   130         if (moduleInfo != null) {
   131             scanForRequestMappings();
   132         }
   134         LOG.trace("{} initialized", getServletName());
   135     }
   137     private void scanForRequestMappings() {
   138         try {
   139             Method[] methods = getClass().getDeclaredMethods();
   140             for (Method method : methods) {
   141                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   142                 if (mapping.isPresent()) {
   143                     if (!Modifier.isPublic(method.getModifiers())) {
   144                         LOG.warn("{} is annotated with {} but is not public",
   145                                 method.getName(), RequestMapping.class.getSimpleName()
   146                         );
   147                         continue;
   148                     }
   149                     if (Modifier.isAbstract(method.getModifiers())) {
   150                         LOG.warn("{} is annotated with {} but is abstract",
   151                                 method.getName(), RequestMapping.class.getSimpleName()
   152                         );
   153                         continue;
   154                     }
   155                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   156                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   157                                 method.getName(), RequestMapping.class.getSimpleName()
   158                         );
   159                         continue;
   160                     }
   162                     boolean paramsInjectible = true;
   163                     for (var param : method.getParameterTypes()) {
   164                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   165                                 || HttpServletResponse.class.isAssignableFrom(param)
   166                                 || DataAccessObjects.class.isAssignableFrom(param);
   167                     }
   168                     if (paramsInjectible) {
   169                         String requestPath = "/" + mapping.get().requestPath();
   170                         if (!mapping.get().requestPath().isBlank() && !mapping.get().menuKey().isBlank()) {
   171                             requestPath += "/";
   172                         }
   174                         if (mappings
   175                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   176                                 .putIfAbsent(requestPath, method) != null) {
   177                             LOG.warn("{} {} has multiple mappings",
   178                                     mapping.get().method(),
   179                                     mapping.get().requestPath()
   180                             );
   181                         }
   183                         final var menuKey = mapping.get().menuKey();
   184                         if (!menuKey.isBlank()) {
   185                             subMenu.add(new MenuEntry(
   186                                     new ResourceKey(moduleInfo.getBundleBaseName(), menuKey),
   187                                     moduleInfo.getModulePath() + requestPath,
   188                                     mapping.get().menuSequence()));
   189                         }
   191                         LOG.debug("{} {} maps to {}::{}",
   192                                 mapping.get().method(),
   193                                 requestPath,
   194                                 getClass().getSimpleName(),
   195                                 method.getName()
   196                         );
   197                     } else {
   198                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   199                                 method.getName(), RequestMapping.class.getSimpleName()
   200                         );
   201                     }
   202                 }
   203             }
   204         } catch (SecurityException ex) {
   205             LOG.error("Scan for request mappings on declared methods failed.", ex);
   206         }
   207     }
   209     @Override
   210     public void destroy() {
   211         mappings.clear();
   212         LOG.trace("{} destroyed", getServletName());
   213     }
   215     /**
   216      * Sets the name of the dynamic fragment.
   217      * <p>
   218      * It is sufficient to specify the name without any extension. The extension
   219      * is added automatically if not specified.
   220      * <p>
   221      * The fragment must be located in the dynamic fragments folder.
   222      *
   223      * @param req          the servlet request object
   224      * @param fragmentName the name of the fragment
   225      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   226      */
   227     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   228         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   229     }
   231     /**
   232      * @param req      the servlet request object
   233      * @param location the location where to redirect
   234      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   235      */
   236     public void setRedirectLocation(HttpServletRequest req, String location) {
   237         if (location.startsWith("./")) {
   238             location = location.replaceFirst("\\./", Functions.baseHref(req));
   239         }
   240         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   241     }
   243     /**
   244      * Specifies the name of an additional stylesheet used by the module.
   245      * <p>
   246      * Setting an additional stylesheet is optional, but quite common for HTML
   247      * output.
   248      * <p>
   249      * It is sufficient to specify the name without any extension. The extension
   250      * is added automatically if not specified.
   251      *
   252      * @param req        the servlet request object
   253      * @param stylesheet the name of the stylesheet
   254      */
   255     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   256         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   257     }
   259     /**
   260      * Obtains a request parameter of the specified type.
   261      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   262      * The constructor of the specified type may throw an exception on conversion failures.
   263      *
   264      * @param req the servlet request object
   265      * @param clazz the class object of the expected type
   266      * @param name the name of the parameter
   267      * @param <T> the expected type
   268      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   269      */
   270     public<T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   271         final String paramValue = req.getParameter(name);
   272         if (paramValue == null) return Optional.empty();
   273         if (clazz.equals(String.class)) return Optional.of((T)paramValue);
   274         try {
   275             final Constructor<T> ctor = clazz.getConstructor(String.class);
   276             return Optional.of(ctor.newInstance(paramValue));
   277         } catch (ReflectiveOperationException e) {
   278             throw new RuntimeException(e);
   279         }
   281     }
   283     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   284             throws IOException, ServletException {
   286         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   287         req.setAttribute(Constants.REQ_ATTR_SUB_MENU, subMenu);
   288         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   289     }
   291     private String sanitizeRequestPath(HttpServletRequest req) {
   292         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   293     }
   295     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   296         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   297     }
   299     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   300             throws ServletException, IOException {
   301         switch (type) {
   302             case NONE:
   303                 return;
   304             case HTML:
   305                 forwardToFullView(req, resp);
   306                 return;
   307             // TODO: implement remaining response types
   308             default:
   309                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   310         }
   311     }
   313     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   315         // choose the requested language as session language (if available) or fall back to english, otherwise
   316         HttpSession session = req.getSession();
   317         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   318             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   319             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   320             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   321             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   322             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   323         } else {
   324             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   325             resp.setLocale(sessionLocale);
   326             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   327         }
   329         // set some internal request attributes
   330         final String fullPath = Functions.fullPath(req);
   331         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   332         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   333         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   335         // if this is an error path, bypass the normal flow
   336         if (fullPath.startsWith("/error/")) {
   337             final var mapping = findMapping(method, req);
   338             if (mapping.isPresent()) {
   339                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   340             }
   341             return;
   342         }
   344         // obtain a connection and create the data access objects
   345         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   346         final var ds = db.getDataSource();
   347         if (ds == null) {
   348             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   349             return;
   350         }
   351         try (final var connection = ds.getConnection()) {
   352             final var dao = createDataAccessObjects(connection);
   353             try {
   354                 connection.setAutoCommit(false);
   355                 // call the handler, if available, or send an HTTP 404 error
   356                 final var mapping = findMapping(method, req);
   357                 if (mapping.isPresent()) {
   358                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   359                 } else {
   360                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   361                 }
   362                 connection.commit();
   363             } catch (SQLException ex) {
   364                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   365                 LOG.debug("Details: ", ex);
   366                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   367                 connection.rollback();
   368             }
   369         } catch (SQLException ex) {
   370             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   371             LOG.debug("Details: ", ex);
   372             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   373         }
   374     }
   376     @Override
   377     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   378             throws ServletException, IOException {
   379         doProcess(HttpMethod.GET, req, resp);
   380     }
   382     @Override
   383     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   384             throws ServletException, IOException {
   385         doProcess(HttpMethod.POST, req, resp);
   386     }
   387 }

mercurial