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

Sat, 31 Mar 2018 19:35:04 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 31 Mar 2018 19:35:04 +0200
changeset 20
bd1a76c91d5b
parent 18
a94b172c3a93
child 21
b213fef2539e
permissions
-rw-r--r--

module synchronization with database

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

mercurial