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

Sun, 17 May 2020 15:24:58 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 17 May 2020 15:24:58 +0200
changeset 57
1262b5433644
parent 54
77e01cda5a40
child 58
8d3047f78190
permissions
-rw-r--r--

fixes sub-menu entries not mapping correctly due to buggy handling of trailing slash

     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                         final String requestPath = "/" + mapping.get().requestPath()
   170                                 + (mapping.get().menuKey().isBlank() ? "" : "/");
   172                         if (mappings
   173                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   174                                 .putIfAbsent(requestPath, method) != null) {
   175                             LOG.warn("{} {} has multiple mappings",
   176                                     mapping.get().method(),
   177                                     mapping.get().requestPath()
   178                             );
   179                         }
   181                         final var menuKey = mapping.get().menuKey();
   182                         if (!menuKey.isBlank()) {
   183                             subMenu.add(new MenuEntry(
   184                                     new ResourceKey(moduleInfo.getBundleBaseName(), menuKey),
   185                                     moduleInfo.getModulePath() + requestPath,
   186                                     mapping.get().menuSequence()));
   187                         }
   189                         LOG.debug("{} {} maps to {}::{}",
   190                                 mapping.get().method(),
   191                                 requestPath,
   192                                 getClass().getSimpleName(),
   193                                 method.getName()
   194                         );
   195                     } else {
   196                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   197                                 method.getName(), RequestMapping.class.getSimpleName()
   198                         );
   199                     }
   200                 }
   201             }
   202         } catch (SecurityException ex) {
   203             LOG.error("Scan for request mappings on declared methods failed.", ex);
   204         }
   205     }
   207     @Override
   208     public void destroy() {
   209         mappings.clear();
   210         LOG.trace("{} destroyed", getServletName());
   211     }
   213     /**
   214      * Sets the name of the dynamic fragment.
   215      * <p>
   216      * It is sufficient to specify the name without any extension. The extension
   217      * is added automatically if not specified.
   218      * <p>
   219      * The fragment must be located in the dynamic fragments folder.
   220      *
   221      * @param req          the servlet request object
   222      * @param fragmentName the name of the fragment
   223      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   224      */
   225     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   226         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   227     }
   229     /**
   230      * @param req      the servlet request object
   231      * @param location the location where to redirect
   232      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   233      */
   234     public void setRedirectLocation(HttpServletRequest req, String location) {
   235         if (location.startsWith("./")) {
   236             location = location.replaceFirst("\\./", Functions.baseHref(req));
   237         }
   238         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   239     }
   241     /**
   242      * Specifies the name of an additional stylesheet used by the module.
   243      * <p>
   244      * Setting an additional stylesheet is optional, but quite common for HTML
   245      * output.
   246      * <p>
   247      * It is sufficient to specify the name without any extension. The extension
   248      * is added automatically if not specified.
   249      *
   250      * @param req        the servlet request object
   251      * @param stylesheet the name of the stylesheet
   252      */
   253     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   254         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   255     }
   257     /**
   258      * Obtains a request parameter of the specified type.
   259      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   260      * The constructor of the specified type may throw an exception on conversion failures.
   261      *
   262      * @param req the servlet request object
   263      * @param clazz the class object of the expected type
   264      * @param name the name of the parameter
   265      * @param <T> the expected type
   266      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   267      */
   268     public<T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   269         final String paramValue = req.getParameter(name);
   270         if (paramValue == null) return Optional.empty();
   271         if (clazz.equals(String.class)) return Optional.of((T)paramValue);
   272         try {
   273             final Constructor<T> ctor = clazz.getConstructor(String.class);
   274             return Optional.of(ctor.newInstance(paramValue));
   275         } catch (ReflectiveOperationException e) {
   276             throw new RuntimeException(e);
   277         }
   279     }
   281     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   282             throws IOException, ServletException {
   284         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   285         req.setAttribute(Constants.REQ_ATTR_SUB_MENU, subMenu);
   286         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   287     }
   289     private String sanitizeRequestPath(HttpServletRequest req) {
   290         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   291     }
   293     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   294         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   295     }
   297     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   298             throws ServletException, IOException {
   299         switch (type) {
   300             case NONE:
   301                 return;
   302             case HTML:
   303                 forwardToFullView(req, resp);
   304                 return;
   305             // TODO: implement remaining response types
   306             default:
   307                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   308         }
   309     }
   311     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   313         // choose the requested language as session language (if available) or fall back to english, otherwise
   314         HttpSession session = req.getSession();
   315         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   316             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   317             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   318             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   319             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   320             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   321         } else {
   322             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   323             resp.setLocale(sessionLocale);
   324             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   325         }
   327         // set some internal request attributes
   328         final String fullPath = Functions.fullPath(req);
   329         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   330         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   331         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   333         // if this is an error path, bypass the normal flow
   334         if (fullPath.startsWith("/error/")) {
   335             final var mapping = findMapping(method, req);
   336             if (mapping.isPresent()) {
   337                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   338             }
   339             return;
   340         }
   342         // obtain a connection and create the data access objects
   343         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   344         final var ds = db.getDataSource();
   345         if (ds == null) {
   346             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   347             return;
   348         }
   349         try (final var connection = ds.getConnection()) {
   350             final var dao = createDataAccessObjects(connection);
   351             try {
   352                 connection.setAutoCommit(false);
   353                 // call the handler, if available, or send an HTTP 404 error
   354                 final var mapping = findMapping(method, req);
   355                 if (mapping.isPresent()) {
   356                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   357                 } else {
   358                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   359                 }
   360                 connection.commit();
   361             } catch (SQLException ex) {
   362                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   363                 LOG.debug("Details: ", ex);
   364                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   365                 connection.rollback();
   366             }
   367         } catch (SQLException ex) {
   368             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   369             LOG.debug("Details: ", ex);
   370             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   371         }
   372     }
   374     @Override
   375     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   376             throws ServletException, IOException {
   377         doProcess(HttpMethod.GET, req, resp);
   378     }
   380     @Override
   381     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   382             throws ServletException, IOException {
   383         doProcess(HttpMethod.POST, req, resp);
   384     }
   385 }

mercurial