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

Mon, 18 May 2020 21:06:38 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 18 May 2020 21:06:38 +0200
changeset 63
51aa5e267c7f
parent 58
8d3047f78190
child 70
821c4950b619
permissions
-rw-r--r--

adds utility function to find an entity by ID (reduces code duplication)

     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     private final List<MenuEntry> subMenu = new ArrayList<>();
    97     /**
    98      * Gives implementing modules access to the {@link ModuleManager}.
    99      *
   100      * @return the module manager
   101      */
   102     protected final ModuleManager getModuleManager() {
   103         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
   104     }
   107     /**
   108      * Creates a set of data access objects for the specified connection.
   109      *
   110      * @param connection the SQL connection
   111      * @return a set of data access objects
   112      */
   113     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
   114         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   115         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
   116             return new PGDataAccessObjects(connection);
   117         }
   118         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
   119     }
   121     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   122         try {
   123             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   124             final var paramTypes = method.getParameterTypes();
   125             final var paramValues = new Object[paramTypes.length];
   126             for (int i = 0; i < paramTypes.length; i++) {
   127                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   128                     paramValues[i] = req;
   129                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   130                     paramValues[i] = resp;
   131                 }
   132                 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
   133                     paramValues[i] = dao;
   134                 }
   135             }
   136             return (ResponseType) method.invoke(this, paramValues);
   137         } catch (ReflectiveOperationException | ClassCastException ex) {
   138             LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
   139             LOG.debug("Details: ", ex);
   140             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   141             return ResponseType.NONE;
   142         }
   143     }
   145     @Override
   146     public void init() throws ServletException {
   147         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   148                 .map(LightPITModule.ELProxy::new).orElse(null);
   150         if (moduleInfo != null) {
   151             scanForRequestMappings();
   152         }
   154         LOG.trace("{} initialized", getServletName());
   155     }
   157     private void scanForRequestMappings() {
   158         try {
   159             Method[] methods = getClass().getDeclaredMethods();
   160             for (Method method : methods) {
   161                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   162                 if (mapping.isPresent()) {
   163                     if (!Modifier.isPublic(method.getModifiers())) {
   164                         LOG.warn("{} is annotated with {} but is not public",
   165                                 method.getName(), RequestMapping.class.getSimpleName()
   166                         );
   167                         continue;
   168                     }
   169                     if (Modifier.isAbstract(method.getModifiers())) {
   170                         LOG.warn("{} is annotated with {} but is abstract",
   171                                 method.getName(), RequestMapping.class.getSimpleName()
   172                         );
   173                         continue;
   174                     }
   175                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   176                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   177                                 method.getName(), RequestMapping.class.getSimpleName()
   178                         );
   179                         continue;
   180                     }
   182                     boolean paramsInjectible = true;
   183                     for (var param : method.getParameterTypes()) {
   184                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   185                                 || HttpServletResponse.class.isAssignableFrom(param)
   186                                 || DataAccessObjects.class.isAssignableFrom(param);
   187                     }
   188                     if (paramsInjectible) {
   189                         String requestPath = "/" + mapping.get().requestPath();
   190                         if (!mapping.get().requestPath().isBlank() && !mapping.get().menuKey().isBlank()) {
   191                             requestPath += "/";
   192                         }
   194                         if (mappings
   195                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   196                                 .putIfAbsent(requestPath, method) != null) {
   197                             LOG.warn("{} {} has multiple mappings",
   198                                     mapping.get().method(),
   199                                     mapping.get().requestPath()
   200                             );
   201                         }
   203                         final var menuKey = mapping.get().menuKey();
   204                         if (!menuKey.isBlank()) {
   205                             subMenu.add(new MenuEntry(
   206                                     new ResourceKey(moduleInfo.getBundleBaseName(), menuKey),
   207                                     moduleInfo.getModulePath() + requestPath,
   208                                     mapping.get().menuSequence()));
   209                         }
   211                         LOG.debug("{} {} maps to {}::{}",
   212                                 mapping.get().method(),
   213                                 requestPath,
   214                                 getClass().getSimpleName(),
   215                                 method.getName()
   216                         );
   217                     } else {
   218                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   219                                 method.getName(), RequestMapping.class.getSimpleName()
   220                         );
   221                     }
   222                 }
   223             }
   224         } catch (SecurityException ex) {
   225             LOG.error("Scan for request mappings on declared methods failed.", ex);
   226         }
   227     }
   229     @Override
   230     public void destroy() {
   231         mappings.clear();
   232         LOG.trace("{} destroyed", getServletName());
   233     }
   235     /**
   236      * Sets the name of the dynamic fragment.
   237      * <p>
   238      * It is sufficient to specify the name without any extension. The extension
   239      * is added automatically if not specified.
   240      * <p>
   241      * The fragment must be located in the dynamic fragments folder.
   242      *
   243      * @param req          the servlet request object
   244      * @param fragmentName the name of the fragment
   245      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   246      */
   247     protected void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   248         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   249     }
   251     /**
   252      * @param req      the servlet request object
   253      * @param location the location where to redirect
   254      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   255      */
   256     protected void setRedirectLocation(HttpServletRequest req, String location) {
   257         if (location.startsWith("./")) {
   258             location = location.replaceFirst("\\./", Functions.baseHref(req));
   259         }
   260         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   261     }
   263     /**
   264      * Specifies the name of an additional stylesheet used by the module.
   265      * <p>
   266      * Setting an additional stylesheet is optional, but quite common for HTML
   267      * output.
   268      * <p>
   269      * It is sufficient to specify the name without any extension. The extension
   270      * is added automatically if not specified.
   271      *
   272      * @param req        the servlet request object
   273      * @param stylesheet the name of the stylesheet
   274      */
   275     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   276         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   277     }
   279     /**
   280      * Obtains a request parameter of the specified type.
   281      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   282      * The constructor of the specified type may throw an exception on conversion failures.
   283      *
   284      * @param req the servlet request object
   285      * @param clazz the class object of the expected type
   286      * @param name the name of the parameter
   287      * @param <T> the expected type
   288      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   289      */
   290     protected<T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   291         final String paramValue = req.getParameter(name);
   292         if (paramValue == null) return Optional.empty();
   293         if (clazz.equals(String.class)) return Optional.of((T)paramValue);
   294         try {
   295             final Constructor<T> ctor = clazz.getConstructor(String.class);
   296             return Optional.of(ctor.newInstance(paramValue));
   297         } catch (ReflectiveOperationException e) {
   298             throw new RuntimeException(e);
   299         }
   301     }
   303     /**
   304      * Tries to look up an entity with a key obtained from a request parameter.
   305      *
   306      * @param req the servlet request object
   307      * @param clazz the class representing the type of the request parameter
   308      * @param name the name of the request parameter
   309      * @param find the find function (typically a DAO function)
   310      * @param <T> the type of the request parameter
   311      * @param <R> the type of the looked up entity
   312      * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
   313      * @throws SQLException if the find function throws an exception
   314      */
   315     protected<T,R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
   316         final var param = getParameter(req, clazz, name);
   317         if (param.isPresent()) {
   318             return Optional.ofNullable(find.apply(param.get()));
   319         } else {
   320             return Optional.empty();
   321         }
   322     }
   324     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   325             throws IOException, ServletException {
   327         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   328         req.setAttribute(Constants.REQ_ATTR_SUB_MENU, subMenu);
   329         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   330     }
   332     private String sanitizeRequestPath(HttpServletRequest req) {
   333         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   334     }
   336     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   337         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   338     }
   340     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   341             throws ServletException, IOException {
   342         switch (type) {
   343             case NONE:
   344                 return;
   345             case HTML:
   346                 forwardToFullView(req, resp);
   347                 return;
   348             // TODO: implement remaining response types
   349             default:
   350                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   351         }
   352     }
   354     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   356         // choose the requested language as session language (if available) or fall back to english, otherwise
   357         HttpSession session = req.getSession();
   358         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   359             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   360             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   361             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   362             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   363             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   364         } else {
   365             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   366             resp.setLocale(sessionLocale);
   367             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   368         }
   370         // set some internal request attributes
   371         final String fullPath = Functions.fullPath(req);
   372         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   373         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   374         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   376         // if this is an error path, bypass the normal flow
   377         if (fullPath.startsWith("/error/")) {
   378             final var mapping = findMapping(method, req);
   379             if (mapping.isPresent()) {
   380                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   381             }
   382             return;
   383         }
   385         // obtain a connection and create the data access objects
   386         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   387         final var ds = db.getDataSource();
   388         if (ds == null) {
   389             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   390             return;
   391         }
   392         try (final var connection = ds.getConnection()) {
   393             final var dao = createDataAccessObjects(connection);
   394             try {
   395                 connection.setAutoCommit(false);
   396                 // call the handler, if available, or send an HTTP 404 error
   397                 final var mapping = findMapping(method, req);
   398                 if (mapping.isPresent()) {
   399                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   400                 } else {
   401                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   402                 }
   403                 connection.commit();
   404             } catch (SQLException ex) {
   405                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   406                 LOG.debug("Details: ", ex);
   407                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   408                 connection.rollback();
   409             }
   410         } catch (SQLException ex) {
   411             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   412             LOG.debug("Details: ", ex);
   413             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   414         }
   415     }
   417     @Override
   418     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   419             throws ServletException, IOException {
   420         doProcess(HttpMethod.GET, req, resp);
   421     }
   423     @Override
   424     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   425             throws ServletException, IOException {
   426         doProcess(HttpMethod.POST, req, resp);
   427     }
   428 }

mercurial