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

Sun, 24 May 2020 15:30:43 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 24 May 2020 15:30:43 +0200
changeset 80
27a25f32048e
parent 79
f64255a88d66
child 83
24a3596b8f98
permissions
-rw-r--r--

adds project overview page

     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 LightPIT pages.
    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");
    62     @FunctionalInterface
    63     protected interface SQLFindFunction<K, T> {
    64         T apply(K key) throws SQLException;
    66         default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
    67             Objects.requireNonNull(before);
    68             return (v) -> this.apply(before.apply(v));
    69         }
    71         default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
    72             Objects.requireNonNull(after);
    73             return (t) -> after.apply(this.apply(t));
    74         }
    76         static <K> Function<K, K> identity() {
    77             return (t) -> t;
    78         }
    79     }
    81     /**
    82      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    83      * <p>
    84      * Paths in this map must always start with a leading slash, although
    85      * the specification in the annotation must not start with a leading slash.
    86      * <p>
    87      * The reason for this is the different handling of empty paths in
    88      * {@link HttpServletRequest#getPathInfo()}.
    89      */
    90     private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
    92     /**
    93      * Returns the name of the resource bundle associated with this servlet.
    94      * @return the resource bundle base name
    95      */
    96     protected abstract String getResourceBundleName();
    99     /**
   100      * Creates a set of data access objects for the specified connection.
   101      *
   102      * @param connection the SQL connection
   103      * @return a set of data access objects
   104      */
   105     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
   106         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   107         if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
   108             return new PGDataAccessObjects(connection);
   109         }
   110         throw new AssertionError("Non-exhaustive if-else - this is a bug.");
   111     }
   113     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   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(DataAccessObjects.class)) {
   125                     paramValues[i] = dao;
   126                 }
   127             }
   128             return (ResponseType) method.invoke(this, paramValues);
   129         } catch (InvocationTargetException ex) {
   130             LOG.error("invocation of method {}::{} failed: {}",
   131                     method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
   132             LOG.debug("Details: ", ex.getTargetException());
   133             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
   134             return ResponseType.NONE;
   135         } catch (ReflectiveOperationException | ClassCastException ex) {
   136             LOG.error("invocation of method {}::{} failed: {}",
   137                     method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
   138             LOG.debug("Details: ", ex);
   139             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
   140             return ResponseType.NONE;
   141         }
   142     }
   144     @Override
   145     public void init() throws ServletException {
   146         scanForRequestMappings();
   148         LOG.trace("{} initialized", getServletName());
   149     }
   151     private void scanForRequestMappings() {
   152         try {
   153             Method[] methods = getClass().getDeclaredMethods();
   154             for (Method method : methods) {
   155                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   156                 if (mapping.isPresent()) {
   157                     if (!Modifier.isPublic(method.getModifiers())) {
   158                         LOG.warn("{} is annotated with {} but is not public",
   159                                 method.getName(), RequestMapping.class.getSimpleName()
   160                         );
   161                         continue;
   162                     }
   163                     if (Modifier.isAbstract(method.getModifiers())) {
   164                         LOG.warn("{} is annotated with {} but is abstract",
   165                                 method.getName(), RequestMapping.class.getSimpleName()
   166                         );
   167                         continue;
   168                     }
   169                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   170                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   171                                 method.getName(), RequestMapping.class.getSimpleName()
   172                         );
   173                         continue;
   174                     }
   176                     boolean paramsInjectible = true;
   177                     for (var param : method.getParameterTypes()) {
   178                         paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
   179                                 || HttpServletResponse.class.isAssignableFrom(param)
   180                                 || DataAccessObjects.class.isAssignableFrom(param);
   181                     }
   182                     if (paramsInjectible) {
   183                         String requestPath = "/" + mapping.get().requestPath();
   185                         if (mappings
   186                                 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
   187                                 .putIfAbsent(requestPath, method) != null) {
   188                             LOG.warn("{} {} has multiple mappings",
   189                                     mapping.get().method(),
   190                                     mapping.get().requestPath()
   191                             );
   192                         }
   194                         LOG.debug("{} {} maps to {}::{}",
   195                                 mapping.get().method(),
   196                                 requestPath,
   197                                 getClass().getSimpleName(),
   198                                 method.getName()
   199                         );
   200                     } else {
   201                         LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
   202                                 method.getName(), RequestMapping.class.getSimpleName()
   203                         );
   204                     }
   205                 }
   206             }
   207         } catch (SecurityException ex) {
   208             LOG.error("Scan for request mappings on declared methods failed.", ex);
   209         }
   210     }
   212     @Override
   213     public void destroy() {
   214         mappings.clear();
   215         LOG.trace("{} destroyed", getServletName());
   216     }
   218     /**
   219      * Sets the name of the content page.
   220      * <p>
   221      * It is sufficient to specify the name without any extension. The extension
   222      * is added automatically if not specified.
   223      *
   224      * @param req      the servlet request object
   225      * @param pageName the name of the content page
   226      * @see Constants#REQ_ATTR_CONTENT_PAGE
   227      */
   228     protected void setContentPage(HttpServletRequest req, String pageName) {
   229         req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
   230     }
   232     /**
   233      * Sets the breadcrumbs menu.
   234      *
   235      * @param req         the servlet request object
   236      * @param breadcrumbs the menu entries for the breadcrumbs menu
   237      * @see Constants#REQ_ATTR_BREADCRUMBS
   238      */
   239     protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
   240         req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
   241     }
   243     /**
   244      * @param req      the servlet request object
   245      * @param location the location where to redirect
   246      * @see Constants#REQ_ATTR_REDIRECT_LOCATION
   247      */
   248     protected void setRedirectLocation(HttpServletRequest req, String location) {
   249         if (location.startsWith("./")) {
   250             location = location.replaceFirst("\\./", Functions.baseHref(req));
   251         }
   252         req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
   253     }
   255     /**
   256      * Specifies the name of an additional stylesheet used by the module.
   257      * <p>
   258      * Setting an additional stylesheet is optional, but quite common for HTML
   259      * output.
   260      * <p>
   261      * It is sufficient to specify the name without any extension. The extension
   262      * is added automatically if not specified.
   263      *
   264      * @param req        the servlet request object
   265      * @param stylesheet the name of the stylesheet
   266      */
   267     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   268         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   269     }
   271     /**
   272      * Obtains a request parameter of the specified type.
   273      * The specified type must have a single-argument constructor accepting a string to perform conversion.
   274      * The constructor of the specified type may throw an exception on conversion failures.
   275      *
   276      * @param req   the servlet request object
   277      * @param clazz the class object of the expected type
   278      * @param name  the name of the parameter
   279      * @param <T>   the expected type
   280      * @return the parameter value or an empty optional, if no parameter with the specified name was found
   281      */
   282     protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
   283         final String paramValue = req.getParameter(name);
   284         if (paramValue == null) return Optional.empty();
   285         if (clazz.equals(Boolean.class)) {
   286             if (paramValue.toLowerCase().equals("false") || paramValue.equals("0")) {
   287                 return Optional.of((T)Boolean.FALSE);
   288             } else {
   289                 return Optional.of((T)Boolean.TRUE);
   290             }
   291         }
   292         if (clazz.equals(String.class)) return Optional.of((T) paramValue);
   293         if (java.sql.Date.class.isAssignableFrom(clazz)) {
   294             try {
   295                 return Optional.of((T)java.sql.Date.valueOf(paramValue));
   296             } catch (IllegalArgumentException ex) {
   297                 return Optional.empty();
   298             }
   299         }
   300         try {
   301             final Constructor<T> ctor = clazz.getConstructor(String.class);
   302             return Optional.of(ctor.newInstance(paramValue));
   303         } catch (ReflectiveOperationException e) {
   304             throw new RuntimeException(e);
   305         }
   307     }
   309     /**
   310      * Tries to look up an entity with a key obtained from a request parameter.
   311      *
   312      * @param req   the servlet request object
   313      * @param clazz the class representing the type of the request parameter
   314      * @param name  the name of the request parameter
   315      * @param find  the find function (typically a DAO function)
   316      * @param <T>   the type of the request parameter
   317      * @param <R>   the type of the looked up entity
   318      * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
   319      * @throws SQLException if the find function throws an exception
   320      */
   321     protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
   322         final var param = getParameter(req, clazz, name);
   323         if (param.isPresent()) {
   324             return Optional.ofNullable(find.apply(param.get()));
   325         } else {
   326             return Optional.empty();
   327         }
   328     }
   330     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   331             throws IOException, ServletException {
   333         final String lightpitBundle = "localization.lightpit";
   334         final var mainMenu = List.of(
   335                 new MenuEntry(new ResourceKey(lightpitBundle, "menu.projects"), "projects/"),
   336                 new MenuEntry(new ResourceKey(lightpitBundle, "menu.users"), "teams/"),
   337                 new MenuEntry(new ResourceKey(lightpitBundle, "menu.languages"), "language/")
   338         );
   339         for (var entry : mainMenu) {
   340             if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
   341                 entry.setActive(true);
   342             }
   343         }
   344         req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
   345         req.getRequestDispatcher(SITE_JSP).forward(req, resp);
   346     }
   348     private String sanitizeRequestPath(HttpServletRequest req) {
   349         return Optional.ofNullable(req.getPathInfo()).orElse("/");
   350     }
   352     private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
   353         return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
   354     }
   356     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   357             throws ServletException, IOException {
   358         switch (type) {
   359             case NONE:
   360                 return;
   361             case HTML:
   362                 forwardToFullView(req, resp);
   363                 return;
   364             // TODO: implement remaining response types
   365             default:
   366                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   367         }
   368     }
   370     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   372         // choose the requested language as session language (if available) or fall back to english, otherwise
   373         HttpSession session = req.getSession();
   374         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   375             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   376             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   377             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   378             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   379             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   380         } else {
   381             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   382             resp.setLocale(sessionLocale);
   383             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   384         }
   386         // set some internal request attributes
   387         final String fullPath = Functions.fullPath(req);
   388         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
   389         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
   390         req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
   392         // if this is an error path, bypass the normal flow
   393         if (fullPath.startsWith("/error/")) {
   394             final var mapping = findMapping(method, req);
   395             if (mapping.isPresent()) {
   396                 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
   397             }
   398             return;
   399         }
   401         // obtain a connection and create the data access objects
   402         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   403         final var ds = db.getDataSource();
   404         if (ds == null) {
   405             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
   406             return;
   407         }
   408         try (final var connection = ds.getConnection()) {
   409             final var dao = createDataAccessObjects(connection);
   410             try {
   411                 connection.setAutoCommit(false);
   412                 // call the handler, if available, or send an HTTP 404 error
   413                 final var mapping = findMapping(method, req);
   414                 if (mapping.isPresent()) {
   415                     forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
   416                 } else {
   417                     resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   418                 }
   419                 connection.commit();
   420             } catch (SQLException ex) {
   421                 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   422                 LOG.debug("Details: ", ex);
   423                 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
   424                 connection.rollback();
   425             }
   426         } catch (SQLException ex) {
   427             LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   428             LOG.debug("Details: ", ex);
   429             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
   430         }
   431     }
   433     @Override
   434     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   435             throws ServletException, IOException {
   436         doProcess(HttpMethod.GET, req, resp);
   437     }
   439     @Override
   440     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   441             throws ServletException, IOException {
   442         doProcess(HttpMethod.POST, req, resp);
   443     }
   444 }

mercurial