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

Fri, 22 May 2020 17:26:27 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 22 May 2020 17:26:27 +0200
changeset 74
91d1fc2a3a14
parent 73
672b5003cafe
child 75
33b6843fdf8a
permissions
-rw-r--r--

removes that dynamic_fragment bullshit

     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.InvocationTargetException;
    44 import java.lang.reflect.Method;
    45 import java.lang.reflect.Modifier;
    46 import java.sql.Connection;
    47 import java.sql.SQLException;
    48 import java.util.*;
    49 import java.util.function.Function;
    51 /**
    52  * A special implementation of a HTTPServlet which is focused on implementing
    53  * the necessary functionality for {@link LightPITModule}s.
    54  */
    55 public abstract class AbstractLightPITServlet extends HttpServlet {
    57     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
    59     private static final String SITE_JSP = Functions.jspPath("site");
    61     /**
    62      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    63      */
    64     private LightPITModule.ELProxy moduleInfo = null;
    66     @FunctionalInterface
    67     protected interface SQLFindFunction<K, T> {
    68         T apply(K key) throws SQLException;
    70         default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
    71             Objects.requireNonNull(before);
    72             return (v) -> this.apply(before.apply(v));
    73         }
    75         default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
    76             Objects.requireNonNull(after);
    77             return (t) -> after.apply(this.apply(t));
    78         }
    80         static <K> Function<K, K> identity() {
    81             return (t) -> t;
    82         }
    83     }
    85     /**
    86      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    87      * <p>
    88      * Paths in this map must always start with a leading slash, although
    89      * the specification in the annotation must not start with a leading slash.
    90      * <p>
    91      * The reason for this is the different handling of empty paths in
    92      * {@link HttpServletRequest#getPathInfo()}.
    93      */
    94     private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
    96     /**
    97      * Gives implementing modules access to the {@link ModuleManager}.
    98      *
    99      * @return the module manager
   100      */
   101     protected final ModuleManager getModuleManager() {
   102         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
   103     }
   106     /**
   107      * Creates a set of data access objects for the specified connection.
   108      *
   109      * @param connection the SQL connection
   110      * @return a set of data access objects
   111      */
   112     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
   113         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   114         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
   115             return new PGDataAccessObjects(connection);
   116         }
   117         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
   118     }
   120     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   121         try {
   122             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   123             final var paramTypes = method.getParameterTypes();
   124             final var paramValues = new Object[paramTypes.length];
   125             for (int i = 0; i < paramTypes.length; i++) {
   126                 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
   127                     paramValues[i] = req;
   128                 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
   129                     paramValues[i] = resp;
   130                 }
   131                 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
   132                     paramValues[i] = dao;
   133                 }
   134             }
   135             return (ResponseType) method.invoke(this, paramValues);
   136         } catch (InvocationTargetException ex) {
   137             LOG.error("invocation of method {}::{} failed: {}",
   138                     method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
   139             LOG.debug("Details: ", ex.getTargetException());
   140             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
   141             return ResponseType.NONE;
   142         } catch (ReflectiveOperationException | ClassCastException ex) {
   143             LOG.error("invocation of method {}::{} failed: {}",
   144                     method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
   145             LOG.debug("Details: ", ex);
   146             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
   147             return ResponseType.NONE;
   148         }
   149     }
   151     @Override
   152     public void init() throws ServletException {
   153         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   154                 .map(LightPITModule.ELProxy::new).orElse(null);
   156         if (moduleInfo != null) {
   157             scanForRequestMappings();
   158         }
   160         LOG.trace("{} initialized", getServletName());
   161     }
   163     private void scanForRequestMappings() {
   164         try {
   165             Method[] methods = getClass().getDeclaredMethods();
   166             for (Method method : methods) {
   167                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   168                 if (mapping.isPresent()) {
   169                     if (!Modifier.isPublic(method.getModifiers())) {
   170                         LOG.warn("{} is annotated with {} but is not public",
   171                                 method.getName(), RequestMapping.class.getSimpleName()
   172                         );
   173                         continue;
   174                     }
   175                     if (Modifier.isAbstract(method.getModifiers())) {
   176                         LOG.warn("{} is annotated with {} but is abstract",
   177                                 method.getName(), RequestMapping.class.getSimpleName()
   178                         );
   179                         continue;
   180                     }
   181                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   182                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   183                                 method.getName(), RequestMapping.class.getSimpleName()
   184                         );
   185                         continue;
   186                     }
   188                     boolean paramsInjectible = true;
   189                     for (var param : method.getParameterTypes()) {
   190                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   191                                 || HttpServletResponse.class.isAssignableFrom(param)
   192                                 || DataAccessObjects.class.isAssignableFrom(param);
   193                     }
   194                     if (paramsInjectible) {
   195                         String requestPath = "/" + mapping.get().requestPath();
   197                         if (mappings
   198                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   199                                 .putIfAbsent(requestPath, method) != null) {
   200                             LOG.warn("{} {} has multiple mappings",
   201                                     mapping.get().method(),
   202                                     mapping.get().requestPath()
   203                             );
   204                         }
   206                         LOG.debug("{} {} maps to {}::{}",
   207                                 mapping.get().method(),
   208                                 requestPath,
   209                                 getClass().getSimpleName(),
   210                                 method.getName()
   211                         );
   212                     } else {
   213                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, 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, Functions.jspPath(pageName));
   242     }
   244     /**
   245      * Sets the breadcrumbs menu.
   246      *
   247      * @param req         the servlet request object
   248      * @param breadcrumbs the menu entries for the breadcrumbs menu
   249      * @see Constants#REQ_ATTR_BREADCRUMBS
   250      */
   251     protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
   252         req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
   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("\\./", Functions.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, Functions.enforceExt(stylesheet, ".css"));
   281     }
   283     /**
   284      * Obtains a request parameter of the specified type.
   285      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   286      * The constructor of the specified type may throw an exception on conversion failures.
   287      *
   288      * @param req   the servlet request object
   289      * @param clazz the class object of the expected type
   290      * @param name  the name of the parameter
   291      * @param <T>   the expected type
   292      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   293      */
   294     protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   295         final String paramValue = req.getParameter(name);
   296         if (paramValue == null) return Optional.empty();
   297         if (clazz.equals(String.class)) return Optional.of((T) paramValue);
   298         try {
   299             final Constructor<T> ctor = clazz.getConstructor(String.class);
   300             return Optional.of(ctor.newInstance(paramValue));
   301         } catch (ReflectiveOperationException e) {
   302             throw new RuntimeException(e);
   303         }
   305     }
   307     /**
   308      * Tries to look up an entity with a key obtained from a request parameter.
   309      *
   310      * @param req   the servlet request object
   311      * @param clazz the class representing the type of the request parameter
   312      * @param name  the name of the request parameter
   313      * @param find  the find function (typically a DAO function)
   314      * @param <T>   the type of the request parameter
   315      * @param <R>   the type of the looked up entity
   316      * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
   317      * @throws SQLException if the find function throws an exception
   318      */
   319     protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
   320         final var param = getParameter(req, clazz, name);
   321         if (param.isPresent()) {
   322             return Optional.ofNullable(find.apply(param.get()));
   323         } else {
   324             return Optional.empty();
   325         }
   326     }
   328     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   329             throws IOException, ServletException {
   331         final var mainMenu = new ArrayList<MenuEntry>(getModuleManager().getMainMenu());
   332         for (var entry : mainMenu) {
   333             if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
   334                 entry.setActive(true);
   335             }
   336         }
   337         req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
   338         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   339     }
   341     private String sanitizeRequestPath(HttpServletRequest req) {
   342         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   343     }
   345     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   346         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   347     }
   349     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   350             throws ServletException, IOException {
   351         switch (type) {
   352             case NONE:
   353                 return;
   354             case HTML:
   355                 forwardToFullView(req, resp);
   356                 return;
   357             // TODO: implement remaining response types
   358             default:
   359                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   360         }
   361     }
   363     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   365         // choose the requested language as session language (if available) or fall back to english, otherwise
   366         HttpSession session = req.getSession();
   367         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   368             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   369             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   370             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   371             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   372             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   373         } else {
   374             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   375             resp.setLocale(sessionLocale);
   376             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   377         }
   379         // set some internal request attributes
   380         final String fullPath = Functions.fullPath(req);
   381         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   382         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   383         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   385         // if this is an error path, bypass the normal flow
   386         if (fullPath.startsWith("/error/")) {
   387             final var mapping = findMapping(method, req);
   388             if (mapping.isPresent()) {
   389                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   390             }
   391             return;
   392         }
   394         // obtain a connection and create the data access objects
   395         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   396         final var ds = db.getDataSource();
   397         if (ds == null) {
   398             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   399             return;
   400         }
   401         try (final var connection = ds.getConnection()) {
   402             final var dao = createDataAccessObjects(connection);
   403             try {
   404                 connection.setAutoCommit(false);
   405                 // call the handler, if available, or send an HTTP 404 error
   406                 final var mapping = findMapping(method, req);
   407                 if (mapping.isPresent()) {
   408                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   409                 } else {
   410                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   411                 }
   412                 connection.commit();
   413             } catch (SQLException ex) {
   414                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   415                 LOG.debug("Details: ", ex);
   416                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   417                 connection.rollback();
   418             }
   419         } catch (SQLException ex) {
   420             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   421             LOG.debug("Details: ", ex);
   422             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   423         }
   424     }
   426     @Override
   427     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   428             throws ServletException, IOException {
   429         doProcess(HttpMethod.GET, req, resp);
   430     }
   432     @Override
   433     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   434             throws ServletException, IOException {
   435         doProcess(HttpMethod.POST, req, resp);
   436     }
   437 }

mercurial