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

Fri, 22 May 2020 16:21:31 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 22 May 2020 16:21:31 +0200
changeset 71
dca186d3911f
parent 70
821c4950b619
child 73
672b5003cafe
permissions
-rw-r--r--

adds breadcrumb menu

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

mercurial