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

Tue, 26 Dec 2017 19:45:31 +0100

author
Mike Becker <universe@uap-core.de>
date
Tue, 26 Dec 2017 19:45:31 +0100
changeset 15
bb594abac796
parent 14
2b270c714678
child 17
d1036b776eee
permissions
-rw-r--r--

language selector completed

     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     private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
    79     /**
    80      * Gives implementing modules access to the {@link ModuleManager}.
    81      * @return the module manager
    82      */
    83     protected final ModuleManager getModuleManager() {
    84         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
    85     }
    87     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp)
    88             throws IOException, ServletException {
    89         try {
    90             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
    91             return (ResponseType) method.invoke(this, req, resp);
    92         } catch (ReflectiveOperationException | ClassCastException ex) {
    93             LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
    94             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    95             return ResponseType.NONE;
    96         }
    97     }
    99     @Override
   100     public void init() throws ServletException {
   101         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class));
   102         moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert);
   104         if (moduleInfo.isPresent()) {
   105             scanForRequestMappings();
   106         }
   108         LOG.trace("{} initialized", getServletName());
   109     }
   111     private void scanForRequestMappings() {
   112         try {
   113             Method[] methods = getClass().getDeclaredMethods();
   114             for (Method method : methods) {
   115                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   116                 if (mapping.isPresent()) {
   117                     if (!Modifier.isPublic(method.getModifiers())) {
   118                         LOG.warn("{} is annotated with {} but is not public",
   119                                 method.getName(), RequestMapping.class.getSimpleName()
   120                         );
   121                         continue;
   122                     }
   123                     if (Modifier.isAbstract(method.getModifiers())) {
   124                         LOG.warn("{} is annotated with {} but is abstract",
   125                                 method.getName(), RequestMapping.class.getSimpleName()
   126                         );
   127                         continue;
   128                     }
   129                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   130                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   131                                 method.getName(), RequestMapping.class.getSimpleName()
   132                         );
   133                         continue;
   134                     }
   136                     Class<?>[] params = method.getParameterTypes();
   137                     if (params.length == 2
   138                             && HttpServletRequest.class.isAssignableFrom(params[0])
   139                             && HttpServletResponse.class.isAssignableFrom(params[1])) {
   141                         if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
   142                                 putIfAbsent(mapping.get().requestPath(),
   143                                         (req, resp) -> invokeMapping(method, req, resp)) != null) {
   144                             LOG.warn("{} {} has multiple mappings",
   145                                     mapping.get().method(),
   146                                     mapping.get().requestPath()
   147                             );
   148                         }
   150                         LOG.info("{} {} maps to {}",
   151                                 mapping.get().method(),
   152                                 mapping.get().requestPath(),
   153                                 method.getName()
   154                         );
   155                     } else {
   156                         LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
   157                                 method.getName(), RequestMapping.class.getSimpleName()
   158                         );
   159                     }
   160                 }
   161             }
   162         } catch (SecurityException ex) {
   163             LOG.error("Scan for request mappings on declared methods failed.", ex);
   164         }
   165     }
   167     @Override
   168     public void destroy() {
   169         mappings.clear();
   170         LOG.trace("{} destroyed", getServletName());
   171     }
   173     /**
   174      * Sets the name of the dynamic fragment.
   175      * 
   176      * It is sufficient to specify the name without any extension. The extension
   177      * is added automatically if not specified.
   178      * 
   179      * The fragment must be located in the dynamic fragments folder.
   180      * 
   181      * @param req the servlet request object
   182      * @param fragmentName the name of the fragment
   183      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   184      */
   185     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   186         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   187     }
   189     /**
   190      * Specifies the name of an additional stylesheet used by the module.
   191      * 
   192      * Setting an additional stylesheet is optional, but quite common for HTML
   193      * output.
   194      * 
   195      * It is sufficient to specify the name without any extension. The extension
   196      * is added automatically if not specified.
   197      * 
   198      * @param req the servlet request object
   199      * @param stylesheet the name of the stylesheet
   200      */
   201     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   202         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   203     }
   205     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   206             throws IOException, ServletException {
   208         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   209         req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
   210     }
   212     private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
   213         return Optional.ofNullable(mappings.get(method)).map(
   214                 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse(""))
   215         );
   216     }
   218     private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   219             throws ServletException, IOException {
   220         switch (type) {
   221             case NONE: return;
   222             case HTML_FULL:
   223                 forwardToFullView(req, resp);
   224                 return;
   225             // TODO: implement remaining response types
   226             default:
   227                 // this code should be unreachable
   228                 LOG.error("ResponseType switch is not exhaustive - this is a bug!");
   229                 throw new UnsupportedOperationException();
   230         }
   231     }
   233     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
   234             throws ServletException, IOException {
   236         HttpSession session = req.getSession();
   238         // choose the requested language as session language (if available) or fall back to english, otherwise
   239         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   240             Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
   241             Optional<Locale> reqLocale = Optional.of(req.getLocale());
   242             Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
   243             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
   244             LOG.debug("Settng language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
   245         } else {
   246             Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
   247             resp.setLocale(sessionLocale);
   248             LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
   249         }
   251         req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
   252         req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
   253         moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   255         Optional<HandlerMethod> mapping = findMapping(method, req);
   256         if (mapping.isPresent()) {
   257             forwardAsSepcified(mapping.get().apply(req, resp), req, resp);
   258         } else {
   259             resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   260         }
   261     }
   263     @Override
   264     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   265             throws ServletException, IOException {
   266         doProcess(HttpMethod.GET, req, resp);
   267     }
   269     @Override
   270     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   271             throws ServletException, IOException {
   272         doProcess(HttpMethod.POST, req, resp);
   273     }
   274 }

mercurial