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

Wed, 13 May 2020 18:45:28 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 13 May 2020 18:45:28 +0200
changeset 43
9abf0bf44c7b
parent 42
f962ff9dd44e
child 45
cc7f082c5ef3
permissions
-rw-r--r--

renames some crappy constants

     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.Method;
    43 import java.lang.reflect.Modifier;
    44 import java.sql.Connection;
    45 import java.sql.SQLException;
    46 import java.util.*;
    48 /**
    49  * A special implementation of a HTTPServlet which is focused on implementing
    50  * the necessary functionality for {@link LightPITModule}s.
    51  */
    52 public abstract class AbstractLightPITServlet extends HttpServlet {
    54     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
    56     private static final String SITE_JSP = Functions.jspPath("site");
    58     /**
    59      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    60      */
    61     private LightPITModule.ELProxy moduleInfo = null;
    63     /**
    64      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    65      * <p>
    66      * Paths in this map must always start with a leading slash, although
    67      * the specification in the annotation must not start with a leading slash.
    68      * <p>
    69      * The reason for this is the different handling of empty paths in
    70      * {@link HttpServletRequest#getPathInfo()}.
    71      */
    72     private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
    74     /**
    75      * Gives implementing modules access to the {@link ModuleManager}.
    76      *
    77      * @return the module manager
    78      */
    79     protected final ModuleManager getModuleManager() {
    80         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
    81     }
    84     /**
    85      * Creates a set of data access objects for the specified connection.
    86      *
    87      * @param connection the SQL connection
    88      * @return a set of data access objects
    89      */
    90     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
    91         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
    92         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
    93             return new PGDataAccessObjects(connection);
    94         }
    95         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
    96     }
    98     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
    99         try {
   100             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   101             final var paramTypes = method.getParameterTypes();
   102             final var paramValues = new Object[paramTypes.length];
   103             for (int i = 0; i < paramTypes.length; i++) {
   104                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   105                     paramValues[i] = req;
   106                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   107                     paramValues[i] = resp;
   108                 }
   109                 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
   110                     paramValues[i] = dao;
   111                 }
   112             }
   113             return (ResponseType) method.invoke(this, paramValues);
   114         } catch (ReflectiveOperationException | ClassCastException ex) {
   115             LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
   116             LOG.debug("Details: ", ex);
   117             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   118             return ResponseType.NONE;
   119         }
   120     }
   122     @Override
   123     public void init() throws ServletException {
   124         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   125                 .map(LightPITModule.ELProxy::new).orElse(null);
   127         if (moduleInfo != null) {
   128             scanForRequestMappings();
   129         }
   131         LOG.trace("{} initialized", getServletName());
   132     }
   134     private void scanForRequestMappings() {
   135         try {
   136             Method[] methods = getClass().getDeclaredMethods();
   137             for (Method method : methods) {
   138                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   139                 if (mapping.isPresent()) {
   140                     if (!Modifier.isPublic(method.getModifiers())) {
   141                         LOG.warn("{} is annotated with {} but is not public",
   142                                 method.getName(), RequestMapping.class.getSimpleName()
   143                         );
   144                         continue;
   145                     }
   146                     if (Modifier.isAbstract(method.getModifiers())) {
   147                         LOG.warn("{} is annotated with {} but is abstract",
   148                                 method.getName(), RequestMapping.class.getSimpleName()
   149                         );
   150                         continue;
   151                     }
   152                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   153                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   154                                 method.getName(), RequestMapping.class.getSimpleName()
   155                         );
   156                         continue;
   157                     }
   159                     boolean paramsInjectible = true;
   160                     for (var param : method.getParameterTypes()) {
   161                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   162                                 || HttpServletResponse.class.isAssignableFrom(param)
   163                                 || DataAccessObjects.class.isAssignableFrom(param);
   164                     }
   165                     if (paramsInjectible) {
   166                         final String requestPath = "/" + mapping.get().requestPath();
   168                         if (mappings
   169                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   170                                 .putIfAbsent(requestPath, method) != null) {
   171                             LOG.warn("{} {} has multiple mappings",
   172                                     mapping.get().method(),
   173                                     mapping.get().requestPath()
   174                             );
   175                         }
   177                         LOG.debug("{} {} maps to {}::{}",
   178                                 mapping.get().method(),
   179                                 requestPath,
   180                                 getClass().getSimpleName(),
   181                                 method.getName()
   182                         );
   183                     } else {
   184                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   185                                 method.getName(), RequestMapping.class.getSimpleName()
   186                         );
   187                     }
   188                 }
   189             }
   190         } catch (SecurityException ex) {
   191             LOG.error("Scan for request mappings on declared methods failed.", ex);
   192         }
   193     }
   195     @Override
   196     public void destroy() {
   197         mappings.clear();
   198         LOG.trace("{} destroyed", getServletName());
   199     }
   201     /**
   202      * Sets the name of the dynamic fragment.
   203      * <p>
   204      * It is sufficient to specify the name without any extension. The extension
   205      * is added automatically if not specified.
   206      * <p>
   207      * The fragment must be located in the dynamic fragments folder.
   208      *
   209      * @param req          the servlet request object
   210      * @param fragmentName the name of the fragment
   211      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   212      */
   213     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   214         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   215     }
   217     /**
   218      * Specifies the name of an additional stylesheet used by the module.
   219      * <p>
   220      * Setting an additional stylesheet is optional, but quite common for HTML
   221      * output.
   222      * <p>
   223      * It is sufficient to specify the name without any extension. The extension
   224      * is added automatically if not specified.
   225      *
   226      * @param req        the servlet request object
   227      * @param stylesheet the name of the stylesheet
   228      */
   229     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   230         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   231     }
   233     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   234             throws IOException, ServletException {
   236         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   237         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   238     }
   240     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   241         return Optional.ofNullable(mappings.get(method))
   242                 .map(rm -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
   243                 );
   244     }
   246     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   247             throws ServletException, IOException {
   248         switch (type) {
   249             case NONE:
   250                 return;
   251             case HTML:
   252                 forwardToFullView(req, resp);
   253                 return;
   254             // TODO: implement remaining response types
   255             default:
   256                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   257         }
   258     }
   260     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   262         // choose the requested language as session language (if available) or fall back to english, otherwise
   263         HttpSession session = req.getSession();
   264         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   265             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   266             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   267             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   268             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   269             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   270         } else {
   271             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   272             resp.setLocale(sessionLocale);
   273             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   274         }
   276         // set some internal request attributes
   277         req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
   278         req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
   279         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   281         // obtain a connection and create the data access objects
   282         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   283         try (final var connection = db.getDataSource().getConnection()) {
   284             final var dao = createDataAccessObjects(connection);
   285             try {
   286                 connection.setAutoCommit(false);
   287                 // call the handler, if available, or send an HTTP 404 error
   288                 final var mapping = findMapping(method, req);
   289                 if (mapping.isPresent()) {
   290                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   291                 } else {
   292                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   293                 }
   294                 connection.commit();
   295             } catch (SQLException ex) {
   296                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   297                 LOG.debug("Details: ", ex);
   298                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code:" + ex.getErrorCode());
   299                 connection.rollback();
   300             }
   301         } catch (SQLException ex) {
   302             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   303             LOG.debug("Details: ", ex);
   304             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code:" + ex.getErrorCode());
   305         }
   306     }
   308     @Override
   309     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   310             throws ServletException, IOException {
   311         doProcess(HttpMethod.GET, req, resp);
   312     }
   314     @Override
   315     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   316             throws ServletException, IOException {
   317         doProcess(HttpMethod.POST, req, resp);
   318     }
   319 }

mercurial