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

Sat, 09 May 2020 15:19:21 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 09 May 2020 15:19:21 +0200
changeset 33
fd8c40ff78c3
parent 29
27a0fdd7bca7
child 34
824d4042c857
permissions
-rw-r--r--

fixes several warnings

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

mercurial