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

Thu, 19 Nov 2020 13:58:54 +0100

author
mike@uapl01.localdomain
date
Thu, 19 Nov 2020 13:58:54 +0100
changeset 159
86b5d8a1662f
parent 158
4f912cd42876
child 160
e2d09cf3fb96
permissions
-rw-r--r--

migrates DAO classes

     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.DaoProvider;
    32 import de.uapcore.lightpit.dao.postgres.PGDaoProvider;
    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.*;
    43 import java.sql.Connection;
    44 import java.sql.SQLException;
    45 import java.util.*;
    46 import java.util.function.Function;
    48 /**
    49  * A special implementation of a HTTPServlet which is focused on implementing
    50  * the necessary functionality for LightPIT pages.
    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 = jspPath("site");
    59     @FunctionalInterface
    60     protected interface SQLFindFunction<K, T> {
    61         T apply(K key) throws SQLException;
    63         default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
    64             Objects.requireNonNull(before);
    65             return (v) -> this.apply(before.apply(v));
    66         }
    68         default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
    69             Objects.requireNonNull(after);
    70             return (t) -> after.apply(this.apply(t));
    71         }
    73         static <K> Function<K, K> identity() {
    74             return (t) -> t;
    75         }
    76     }
    78     /**
    79      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    80      * <p>
    81      * Paths in this map must always start with a leading slash, although
    82      * the specification in the annotation must not start with a leading slash.
    83      * <p>
    84      * The reason for this is the different handling of empty paths in
    85      * {@link HttpServletRequest#getPathInfo()}.
    86      */
    87     private final Map<HttpMethod, Map<PathPattern, Method>> mappings = new HashMap<>();
    89     /**
    90      * Returns the name of the resource bundle associated with this servlet.
    91      *
    92      * @return the resource bundle base name
    93      */
    94     protected abstract String getResourceBundleName();
    97     /**
    98      * Creates a set of data access objects for the specified connection.
    99      *
   100      * @param connection the SQL connection
   101      * @return a set of data access objects
   102      */
   103     private DaoProvider createDataAccessObjects(Connection connection) throws SQLException {
   104         final var df = (DataSourceProvider) getServletContext().getAttribute(DataSourceProvider.Companion.getSC_ATTR_NAME());
   105         if (df.getDialect() == DataSourceProvider.Dialect.Postgres) {
   106             return new PGDaoProvider(connection);
   107         }
   108         throw new UnsupportedOperationException("Non-exhaustive if-else - this is a bug.");
   109     }
   111     private void invokeMapping(Map.Entry<PathPattern, Method> mapping, HttpServletRequest req, HttpServletResponse resp, DaoProvider dao) throws IOException {
   112         final var pathPattern = mapping.getKey();
   113         final var method = mapping.getValue();
   114         try {
   115             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   116             final var paramTypes = method.getParameterTypes();
   117             final var paramValues = new Object[paramTypes.length];
   118             for (int i = 0; i < paramTypes.length; i++) {
   119                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   120                     paramValues[i] = req;
   121                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   122                     paramValues[i] = resp;
   123                 }
   124                 if (paramTypes[i].isAssignableFrom(DaoProvider.class)) {
   125                     paramValues[i] = dao;
   126                 }
   127                 if (paramTypes[i].isAssignableFrom(PathParameters.class)) {
   128                     paramValues[i] = pathPattern.obtainPathParameters(sanitizeRequestPath(req));
   129                 }
   130             }
   131             method.invoke(this, paramValues);
   132         } catch (InvocationTargetException ex) {
   133             LOG.error("invocation of method {}::{} failed: {}",
   134                     method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
   135             LOG.debug("Details: ", ex.getTargetException());
   136             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
   137         } catch (ReflectiveOperationException | ClassCastException ex) {
   138             LOG.error("invocation of method {}::{} failed: {}",
   139                     method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
   140             LOG.debug("Details: ", ex);
   141             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
   142         }
   143     }
   145     @Override
   146     public void init() throws ServletException {
   147         scanForRequestMappings();
   149         LOG.trace("{} initialized", getServletName());
   150     }
   152     private void scanForRequestMappings() {
   153         try {
   154             Method[] methods = getClass().getDeclaredMethods();
   155             for (Method method : methods) {
   156                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   157                 if (mapping.isPresent()) {
   158                     if (mapping.get().requestPath().isBlank()) {
   159                         LOG.warn("{} is annotated with {} but request path is empty",
   160                                 method.getName(), RequestMapping.class.getSimpleName()
   161                         );
   162                         continue;
   163                     }
   165                     if (!Modifier.isPublic(method.getModifiers())) {
   166                         LOG.warn("{} is annotated with {} but is not public",
   167                                 method.getName(), RequestMapping.class.getSimpleName()
   168                         );
   169                         continue;
   170                     }
   171                     if (Modifier.isAbstract(method.getModifiers())) {
   172                         LOG.warn("{} is annotated with {} but is abstract",
   173                                 method.getName(), RequestMapping.class.getSimpleName()
   174                         );
   175                         continue;
   176                     }
   178                     boolean paramsInjectible = true;
   179                     for (var param : method.getParameterTypes()) {
   180                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   181                                 || HttpServletResponse.class.isAssignableFrom(param)
   182                                 || PathParameters.class.isAssignableFrom(param)
   183                                 || DaoProvider.class.isAssignableFrom(param);
   184                     }
   185                     if (paramsInjectible) {
   186                         try {
   187                             PathPattern pathPattern = new PathPattern(mapping.get().requestPath());
   189                             final var methodMappings = mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>());
   190                             final var currentMapping = methodMappings.putIfAbsent(pathPattern, method);
   191                             if (currentMapping != null) {
   192                                 LOG.warn("Cannot map {} {} to {} in class {} - this would override the mapping to {}",
   193                                         mapping.get().method(),
   194                                         mapping.get().requestPath(),
   195                                         method.getName(),
   196                                         getClass().getSimpleName(),
   197                                         currentMapping.getName()
   198                                 );
   199                             }
   201                             LOG.debug("{} {} maps to {}::{}",
   202                                     mapping.get().method(),
   203                                     mapping.get().requestPath(),
   204                                     getClass().getSimpleName(),
   205                                     method.getName()
   206                             );
   207                         } catch (IllegalArgumentException ex) {
   208                             LOG.warn("Request mapping for {} failed: path pattern '{}' is syntactically invalid",
   209                                     method.getName(), mapping.get().requestPath()
   210                             );
   211                         }
   212                     } else {
   213                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest, HttpServletResponse, PathParameters, and DataAccessObjects are allowed",
   214                                 method.getName(), RequestMapping.class.getSimpleName()
   215                         );
   216                     }
   217                 }
   218             }
   219         } catch (SecurityException ex) {
   220             LOG.error("Scan for request mappings on declared methods failed.", ex);
   221         }
   222     }
   224     @Override
   225     public void destroy() {
   226         mappings.clear();
   227         LOG.trace("{} destroyed", getServletName());
   228     }
   230     /**
   231      * Sets the name of the content page.
   232      * <p>
   233      * It is sufficient to specify the name without any extension. The extension
   234      * is added automatically if not specified.
   235      *
   236      * @param req      the servlet request object
   237      * @param pageName the name of the content page
   238      * @see Constants#REQ_ATTR_CONTENT_PAGE
   239      */
   240     protected void setContentPage(HttpServletRequest req, String pageName) {
   241         req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, jspPath(pageName));
   242     }
   244     /**
   245      * Sets the navigation menu.
   246      *
   247      * @param req     the servlet request object
   248      * @param jspName the name of the menu's jsp file
   249      * @see Constants#REQ_ATTR_NAVIGATION
   250      */
   251     protected void setNavigationMenu(HttpServletRequest req, String jspName) {
   252         req.setAttribute(Constants.REQ_ATTR_NAVIGATION, jspPath(jspName));
   253     }
   255     /**
   256      * @param req      the servlet request object
   257      * @param location the location where to redirect
   258      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   259      */
   260     protected void setRedirectLocation(HttpServletRequest req, String location) {
   261         if (location.startsWith("./")) {
   262             location = location.replaceFirst("\\./", baseHref(req));
   263         }
   264         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   265     }
   267     /**
   268      * Specifies the name of an additional stylesheet used by the module.
   269      * <p>
   270      * Setting an additional stylesheet is optional, but quite common for HTML
   271      * output.
   272      * <p>
   273      * It is sufficient to specify the name without any extension. The extension
   274      * is added automatically if not specified.
   275      *
   276      * @param req        the servlet request object
   277      * @param stylesheet the name of the stylesheet
   278      */
   279     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   280         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, enforceExt(stylesheet, ".css"));
   281     }
   283     /**
   284      * Sets the view model object.
   285      * The type must match the expected type in the JSP file.
   286      *
   287      * @param req       the servlet request object
   288      * @param viewModel the view model object
   289      */
   290     public void setViewModel(HttpServletRequest req, Object viewModel) {
   291         req.setAttribute(Constants.REQ_ATTR_VIEWMODEL, viewModel);
   292     }
   294     private <T> Optional<T> parseParameter(String paramValue, Class<T> clazz) {
   295         if (paramValue == null) return Optional.empty();
   296         if (clazz.equals(Boolean.class)) {
   297             if (paramValue.toLowerCase().equals("false") || paramValue.equals("0")) {
   298                 return Optional.of((T) Boolean.FALSE);
   299             } else {
   300                 return Optional.of((T) Boolean.TRUE);
   301             }
   302         }
   303         if (clazz.equals(String.class)) return Optional.of((T) paramValue);
   304         if (java.sql.Date.class.isAssignableFrom(clazz)) {
   305             try {
   306                 return Optional.of((T) java.sql.Date.valueOf(paramValue));
   307             } catch (IllegalArgumentException ex) {
   308                 return Optional.empty();
   309             }
   310         }
   311         try {
   312             final Constructor<T> ctor = clazz.getConstructor(String.class);
   313             return Optional.of(ctor.newInstance(paramValue));
   314         } catch (ReflectiveOperationException e) {
   315             // does not type check and is not convertible - treat as if the parameter was never set
   316             return Optional.empty();
   317         }
   318     }
   320     /**
   321      * Obtains a request parameter of the specified type.
   322      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   323      * The constructor of the specified type may throw an exception on conversion failures.
   324      *
   325      * @param req   the servlet request object
   326      * @param clazz the class object of the expected type
   327      * @param name  the name of the parameter
   328      * @param <T>   the expected type
   329      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   330      */
   331     protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   332         if (clazz.isArray()) {
   333             final String[] paramValues = req.getParameterValues(name);
   334             int len = paramValues == null ? 0 : paramValues.length;
   335             final var array = (T) Array.newInstance(clazz.getComponentType(), len);
   336             for (int i = 0; i < len; i++) {
   337                 try {
   338                     final Constructor<?> ctor = clazz.getComponentType().getConstructor(String.class);
   339                     Array.set(array, i, ctor.newInstance(paramValues[i]));
   340                 } catch (ReflectiveOperationException e) {
   341                     throw new RuntimeException(e);
   342                 }
   343             }
   344             return Optional.of(array);
   345         } else {
   346             return parseParameter(req.getParameter(name), clazz);
   347         }
   348     }
   350     /**
   351      * Tries to look up an entity with a key obtained from a request parameter.
   352      *
   353      * @param req   the servlet request object
   354      * @param clazz the class representing the type of the request parameter
   355      * @param name  the name of the request parameter
   356      * @param find  the find function (typically a DAO function)
   357      * @param <T>   the type of the request parameter
   358      * @param <R>   the type of the looked up entity
   359      * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
   360      * @throws SQLException if the find function throws an exception
   361      */
   362     protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
   363         final var param = getParameter(req, clazz, name);
   364         if (param.isPresent()) {
   365             return Optional.ofNullable(find.apply(param.get()));
   366         } else {
   367             return Optional.empty();
   368         }
   369     }
   371     private String sanitizeRequestPath(HttpServletRequest req) {
   372         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   373     }
   375     private Optional<Map.Entry<PathPattern, Method>> findMapping(HttpMethod method, HttpServletRequest req) {
   376         return Optional.ofNullable(mappings.get(method)).flatMap(rm ->
   377                 rm.entrySet().stream().filter(
   378                         kv -> kv.getKey().matches(sanitizeRequestPath(req))
   379                 ).findAny()
   380         );
   381     }
   383     protected void renderSite(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   384         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   385     }
   387     protected Optional<String[]> availableLanguages() {
   388         return Optional.ofNullable(getServletContext().getInitParameter(Constants.CTX_ATTR_LANGUAGES)).map((x) -> x.split("\\s*,\\s*"));
   389     }
   391     private static String baseHref(HttpServletRequest req) {
   392         return String.format("%s://%s:%d%s/",
   393                 req.getScheme(),
   394                 req.getServerName(),
   395                 req.getServerPort(),
   396                 req.getContextPath());
   397     }
   399     private static String enforceExt(String filename, String ext) {
   400         return filename.endsWith(ext) ? filename : filename + ext;
   401     }
   403     private static String jspPath(String filename) {
   404         return enforceExt(Constants.JSP_PATH_PREFIX + filename, ".jsp");
   405     }
   407     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   409         // choose the requested language as session language (if available) or fall back to english, otherwise
   410         HttpSession session = req.getSession();
   411         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   412             Optional<List<String>> availableLanguages = availableLanguages().map(Arrays::asList);
   413             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   414             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   415             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   416             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   417         } else {
   418             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   419             resp.setLocale(sessionLocale);
   420             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   421         }
   423         // set some internal request attributes
   424         final String fullPath = req.getServletPath() + Optional.ofNullable(req.getPathInfo()).orElse("");
   425         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, baseHref(req));
   426         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   427         req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
   429         // if this is an error path, bypass the normal flow
   430         if (fullPath.startsWith("/error/")) {
   431             final var mapping = findMapping(method, req);
   432             if (mapping.isPresent()) {
   433                 invokeMapping(mapping.get(), req, resp, null);
   434             }
   435             return;
   436         }
   438         // obtain a connection and create the data access objects
   439         final var db = (DataSourceProvider) req.getServletContext().getAttribute(DataSourceProvider.Companion.getSC_ATTR_NAME());
   440         final var ds = db.getDataSource();
   441         if (ds == null) {
   442             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   443             return;
   444         }
   445         try (final var connection = ds.getConnection()) {
   446             final var dao = createDataAccessObjects(connection);
   447             try {
   448                 connection.setAutoCommit(false);
   449                 // call the handler, if available, or send an HTTP 404 error
   450                 final var mapping = findMapping(method, req);
   451                 if (mapping.isPresent()) {
   452                     invokeMapping(mapping.get(), req, resp, dao);
   453                 } else {
   454                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   455                 }
   456                 connection.commit();
   457             } catch (SQLException ex) {
   458                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   459                 LOG.debug("Details: ", ex);
   460                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   461                 connection.rollback();
   462             }
   463         } catch (SQLException ex) {
   464             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   465             LOG.debug("Details: ", ex);
   466             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   467         }
   468     }
   470     @Override
   471     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   472             throws ServletException, IOException {
   473         doProcess(HttpMethod.GET, req, resp);
   474     }
   476     @Override
   477     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   478             throws ServletException, IOException {
   479         doProcess(HttpMethod.POST, req, resp);
   480     }
   481 }

mercurial