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

Sun, 10 May 2020 10:11:37 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 10 May 2020 10:11:37 +0200
changeset 36
0f4f8f255c32
parent 34
824d4042c857
child 38
cf85ef18f231
permissions
-rw-r--r--

removes features that are not (and probably will not) used anyway

     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 org.slf4j.Logger;
    32 import org.slf4j.LoggerFactory;
    34 import javax.servlet.ServletException;
    35 import javax.servlet.http.HttpServlet;
    36 import javax.servlet.http.HttpServletRequest;
    37 import javax.servlet.http.HttpServletResponse;
    38 import javax.servlet.http.HttpSession;
    39 import java.io.IOException;
    40 import java.lang.reflect.Method;
    41 import java.lang.reflect.Modifier;
    42 import java.util.*;
    44 /**
    45  * A special implementation of a HTTPServlet which is focused on implementing
    46  * the necessary functionality for {@link LightPITModule}s.
    47  */
    48 public abstract class AbstractLightPITServlet extends HttpServlet {
    50     private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
    52     private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
    54     /**
    55      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    56      */
    57     private LightPITModule.ELProxy moduleInfo = null;
    60     @FunctionalInterface
    61     private interface HandlerMethod {
    62         ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException;
    63     }
    65     /**
    66      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    67      * <p>
    68      * Paths in this map must always start with a leading slash, although
    69      * the specification in the annotation must not start with a leading slash.
    70      * <p>
    71      * The reason for this is the different handling of empty paths in
    72      * {@link HttpServletRequest#getPathInfo()}.
    73      */
    74     private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
    76     /**
    77      * Gives implementing modules access to the {@link ModuleManager}.
    78      *
    79      * @return the module manager
    80      */
    81     protected final ModuleManager getModuleManager() {
    82         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
    83     }
    85     /**
    86      * Gives implementing modules access to the {@link DatabaseFacade}.
    87      *
    88      * @return the database facade
    89      */
    90     protected final DatabaseFacade getDatabaseFacade() {
    91         return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
    92     }
    94     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    95         try {
    96             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
    97             return (ResponseType) method.invoke(this, req, resp);
    98         } catch (ReflectiveOperationException | ClassCastException ex) {
    99             LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
   100             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   101             return ResponseType.NONE;
   102         }
   103     }
   105     @Override
   106     public void init() throws ServletException {
   107         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   108                 .map(LightPITModule.ELProxy::new).orElse(null);
   110         if (moduleInfo != null) {
   111             scanForRequestMappings();
   112         }
   114         LOG.trace("{} initialized", getServletName());
   115     }
   117     private void scanForRequestMappings() {
   118         try {
   119             Method[] methods = getClass().getDeclaredMethods();
   120             for (Method method : methods) {
   121                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   122                 if (mapping.isPresent()) {
   123                     if (!Modifier.isPublic(method.getModifiers())) {
   124                         LOG.warn("{} is annotated with {} but is not public",
   125                                 method.getName(), RequestMapping.class.getSimpleName()
   126                         );
   127                         continue;
   128                     }
   129                     if (Modifier.isAbstract(method.getModifiers())) {
   130                         LOG.warn("{} is annotated with {} but is abstract",
   131                                 method.getName(), RequestMapping.class.getSimpleName()
   132                         );
   133                         continue;
   134                     }
   135                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   136                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   137                                 method.getName(), RequestMapping.class.getSimpleName()
   138                         );
   139                         continue;
   140                     }
   142                     Class<?>[] params = method.getParameterTypes();
   143                     if (params.length == 2
   144                             && HttpServletRequest.class.isAssignableFrom(params[0])
   145                             && HttpServletResponse.class.isAssignableFrom(params[1])) {
   147                         final String requestPath = "/" + mapping.get().requestPath();
   149                         if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
   150                                 putIfAbsent(requestPath,
   151                                         (req, resp) -> invokeMapping(method, req, resp)) != null) {
   152                             LOG.warn("{} {} has multiple mappings",
   153                                     mapping.get().method(),
   154                                     mapping.get().requestPath()
   155                             );
   156                         }
   158                         LOG.debug("{} {} maps to {}::{}",
   159                                 mapping.get().method(),
   160                                 requestPath,
   161                                 getClass().getSimpleName(),
   162                                 method.getName()
   163                         );
   164                     } else {
   165                         LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
   166                                 method.getName(), RequestMapping.class.getSimpleName()
   167                         );
   168                     }
   169                 }
   170             }
   171         } catch (SecurityException ex) {
   172             LOG.error("Scan for request mappings on declared methods failed.", ex);
   173         }
   174     }
   176     @Override
   177     public void destroy() {
   178         mappings.clear();
   179         LOG.trace("{} destroyed", getServletName());
   180     }
   182     /**
   183      * Sets the name of the dynamic fragment.
   184      * <p>
   185      * It is sufficient to specify the name without any extension. The extension
   186      * is added automatically if not specified.
   187      * <p>
   188      * The fragment must be located in the dynamic fragments folder.
   189      *
   190      * @param req          the servlet request object
   191      * @param fragmentName the name of the fragment
   192      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   193      */
   194     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   195         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   196     }
   198     /**
   199      * Specifies the name of an additional stylesheet used by the module.
   200      * <p>
   201      * Setting an additional stylesheet is optional, but quite common for HTML
   202      * output.
   203      * <p>
   204      * It is sufficient to specify the name without any extension. The extension
   205      * is added automatically if not specified.
   206      *
   207      * @param req        the servlet request object
   208      * @param stylesheet the name of the stylesheet
   209      */
   210     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   211         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   212     }
   214     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   215             throws IOException, ServletException {
   217         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   218         req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
   219     }
   221     private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
   222         return Optional.ofNullable(mappings.get(method)).map(
   223                 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
   224         );
   225     }
   227     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   228             throws ServletException, IOException {
   229         switch (type) {
   230             case NONE:
   231                 return;
   232             case HTML_FULL:
   233                 forwardToFullView(req, resp);
   234                 return;
   235             // TODO: implement remaining response types
   236             default:
   237                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   238         }
   239     }
   241     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
   242             throws ServletException, IOException {
   244         // choose the requested language as session language (if available) or fall back to english, otherwise
   245         HttpSession session = req.getSession();
   246         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   247             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   248             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   249             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   250             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   251             LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   252         } else {
   253             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   254             resp.setLocale(sessionLocale);
   255             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   256         }
   258         // set some internal request attributes
   259         req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
   260         req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
   261         Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   264         // call the handler, if available, or send an HTTP 404 error
   265         Optional<HandlerMethod> mapping = findMapping(method, req);
   266         if (mapping.isPresent()) {
   267             forwardAsSpecified(mapping.get().apply(req, resp), req, resp);
   268         } else {
   269             resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   270         }
   271     }
   273     @Override
   274     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   275             throws ServletException, IOException {
   276         doProcess(HttpMethod.GET, req, resp);
   277     }
   279     @Override
   280     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   281             throws ServletException, IOException {
   282         doProcess(HttpMethod.POST, req, resp);
   283     }
   284 }

mercurial