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

Mon, 11 May 2020 19:09:06 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 11 May 2020 19:09:06 +0200
changeset 38
cf85ef18f231
parent 36
0f4f8f255c32
child 39
e722861558bb
permissions
-rw-r--r--

adds DAO for Project entity and save/update methods

     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.Method;
    43 import java.lang.reflect.Modifier;
    44 import java.sql.Connection;
    45 import java.sql.SQLException;
    46 import java.util.*;
    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      * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
    60      */
    61     private LightPITModule.ELProxy moduleInfo = null;
    64     @FunctionalInterface
    65     private interface HandlerMethod {
    66         ResponseType apply(HttpServletRequest request, HttpServletResponse response, DataAccessObjects dao) throws IOException, SQLException;
    67     }
    69     /**
    70      * Invocation mapping gathered from the {@link RequestMapping} annotations.
    71      * <p>
    72      * Paths in this map must always start with a leading slash, although
    73      * the specification in the annotation must not start with a leading slash.
    74      * <p>
    75      * The reason for this is the different handling of empty paths in
    76      * {@link HttpServletRequest#getPathInfo()}.
    77      */
    78     private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
    80     /**
    81      * Gives implementing modules access to the {@link ModuleManager}.
    82      *
    83      * @return the module manager
    84      */
    85     protected final ModuleManager getModuleManager() {
    86         return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
    87     }
    90     /**
    91      * Creates a set of data access objects for the specified connection.
    92      *
    93      * @param connection the SQL connection
    94      * @return a set of data access objects
    95      */
    96     private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
    97         final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
    98         switch (df.getSQLDialect()) {
    99             case Postgres:
   100                 return new PGDataAccessObjects(connection);
   101             default:
   102                 throw new AssertionError("Non-exhaustive switch - this is a bug.");
   103         }
   104     }
   106     private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
   107         try {
   108             LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
   109             return (ResponseType) method.invoke(this, req, resp, dao);
   110         } catch (ReflectiveOperationException | ClassCastException ex) {
   111             LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
   112             LOG.debug("Details: ", ex);
   113             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
   114             return ResponseType.NONE;
   115         }
   116     }
   118     @Override
   119     public void init() throws ServletException {
   120         moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
   121                 .map(LightPITModule.ELProxy::new).orElse(null);
   123         if (moduleInfo != null) {
   124             scanForRequestMappings();
   125         }
   127         LOG.trace("{} initialized", getServletName());
   128     }
   130     private void scanForRequestMappings() {
   131         try {
   132             Method[] methods = getClass().getDeclaredMethods();
   133             for (Method method : methods) {
   134                 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
   135                 if (mapping.isPresent()) {
   136                     if (!Modifier.isPublic(method.getModifiers())) {
   137                         LOG.warn("{} is annotated with {} but is not public",
   138                                 method.getName(), RequestMapping.class.getSimpleName()
   139                         );
   140                         continue;
   141                     }
   142                     if (Modifier.isAbstract(method.getModifiers())) {
   143                         LOG.warn("{} is annotated with {} but is abstract",
   144                                 method.getName(), RequestMapping.class.getSimpleName()
   145                         );
   146                         continue;
   147                     }
   148                     if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
   149                         LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
   150                                 method.getName(), RequestMapping.class.getSimpleName()
   151                         );
   152                         continue;
   153                     }
   155                     Class<?>[] params = method.getParameterTypes();
   156                     if (params.length == 3
   157                             && HttpServletRequest.class.isAssignableFrom(params[0])
   158                             && HttpServletResponse.class.isAssignableFrom(params[1])
   159                             && DataAccessObjects.class.isAssignableFrom(params[2])) {
   161                         final String requestPath = "/" + mapping.get().requestPath();
   163                         if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
   164                                 putIfAbsent(requestPath,
   165                                         (req, resp, dao) -> invokeMapping(method, req, resp, dao)) != null) {
   166                             LOG.warn("{} {} has multiple mappings",
   167                                     mapping.get().method(),
   168                                     mapping.get().requestPath()
   169                             );
   170                         }
   172                         LOG.debug("{} {} maps to {}::{}",
   173                                 mapping.get().method(),
   174                                 requestPath,
   175                                 getClass().getSimpleName(),
   176                                 method.getName()
   177                         );
   178                     } else {
   179                         LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
   180                                 method.getName(), RequestMapping.class.getSimpleName()
   181                         );
   182                     }
   183                 }
   184             }
   185         } catch (SecurityException ex) {
   186             LOG.error("Scan for request mappings on declared methods failed.", ex);
   187         }
   188     }
   190     @Override
   191     public void destroy() {
   192         mappings.clear();
   193         LOG.trace("{} destroyed", getServletName());
   194     }
   196     /**
   197      * Sets the name of the dynamic fragment.
   198      * <p>
   199      * It is sufficient to specify the name without any extension. The extension
   200      * is added automatically if not specified.
   201      * <p>
   202      * The fragment must be located in the dynamic fragments folder.
   203      *
   204      * @param req          the servlet request object
   205      * @param fragmentName the name of the fragment
   206      * @see Constants#DYN_FRAGMENT_PATH_PREFIX
   207      */
   208     public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
   209         req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
   210     }
   212     /**
   213      * Specifies the name of an additional stylesheet used by the module.
   214      * <p>
   215      * Setting an additional stylesheet is optional, but quite common for HTML
   216      * output.
   217      * <p>
   218      * It is sufficient to specify the name without any extension. The extension
   219      * is added automatically if not specified.
   220      *
   221      * @param req        the servlet request object
   222      * @param stylesheet the name of the stylesheet
   223      */
   224     public void setStylesheet(HttpServletRequest req, String stylesheet) {
   225         req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
   226     }
   228     private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
   229             throws IOException, ServletException {
   231         req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
   232         req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
   233     }
   235     private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
   236         return Optional.ofNullable(mappings.get(method)).map(
   237                 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
   238         );
   239     }
   241     private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
   242             throws ServletException, IOException {
   243         switch (type) {
   244             case NONE:
   245                 return;
   246             case HTML_FULL:
   247                 forwardToFullView(req, resp);
   248                 return;
   249             // TODO: implement remaining response types
   250             default:
   251                 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
   252         }
   253     }
   255     private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   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("Setting 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(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
   276         // obtain a connection and create the data access objects
   277         final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
   278         try (final var connection = db.getDataSource().getConnection()) {
   279             final var dao = createDataAccessObjects(connection);
   280             // call the handler, if available, or send an HTTP 404 error
   281             final var mapping = findMapping(method, req);
   282             if (mapping.isPresent()) {
   283                 forwardAsSpecified(mapping.get().apply(req, resp, dao), req, resp);
   284             } else {
   285                 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
   286             }
   287         } catch (SQLException ex) {
   288             LOG.error("Database exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
   289             LOG.debug("Details: ", ex);
   290             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code:" + ex.getErrorCode());
   291         }
   292     }
   294     @Override
   295     protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
   296             throws ServletException, IOException {
   297         doProcess(HttpMethod.GET, req, resp);
   298     }
   300     @Override
   301     protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
   302             throws ServletException, IOException {
   303         doProcess(HttpMethod.POST, req, resp);
   304     }
   305 }

mercurial