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

Sat, 09 May 2020 17:01:29 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 09 May 2020 17:01:29 +0200
changeset 34
824d4042c857
parent 33
fd8c40ff78c3
child 36
0f4f8f255c32
permissions
-rw-r--r--

cleanup and simplification of database access layer

universe@7 1 /*
universe@7 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
universe@34 3 *
universe@24 4 * Copyright 2018 Mike Becker. All rights reserved.
universe@34 5 *
universe@7 6 * Redistribution and use in source and binary forms, with or without
universe@7 7 * modification, are permitted provided that the following conditions are met:
universe@7 8 *
universe@7 9 * 1. Redistributions of source code must retain the above copyright
universe@7 10 * notice, this list of conditions and the following disclaimer.
universe@7 11 *
universe@7 12 * 2. Redistributions in binary form must reproduce the above copyright
universe@7 13 * notice, this list of conditions and the following disclaimer in the
universe@7 14 * documentation and/or other materials provided with the distribution.
universe@7 15 *
universe@7 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@7 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@7 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
universe@7 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
universe@7 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
universe@7 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
universe@7 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
universe@7 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
universe@7 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
universe@7 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
universe@7 26 * POSSIBILITY OF SUCH DAMAGE.
universe@34 27 *
universe@7 28 */
universe@7 29 package de.uapcore.lightpit;
universe@7 30
universe@33 31 import org.slf4j.Logger;
universe@33 32 import org.slf4j.LoggerFactory;
universe@33 33
universe@7 34 import javax.servlet.ServletException;
universe@7 35 import javax.servlet.http.HttpServlet;
universe@7 36 import javax.servlet.http.HttpServletRequest;
universe@7 37 import javax.servlet.http.HttpServletResponse;
universe@13 38 import javax.servlet.http.HttpSession;
universe@33 39 import java.io.IOException;
universe@33 40 import java.lang.reflect.Method;
universe@33 41 import java.lang.reflect.Modifier;
universe@33 42 import java.util.*;
universe@7 43
universe@7 44 /**
universe@7 45 * A special implementation of a HTTPServlet which is focused on implementing
universe@7 46 * the necessary functionality for {@link LightPITModule}s.
universe@7 47 */
universe@9 48 public abstract class AbstractLightPITServlet extends HttpServlet {
universe@34 49
universe@10 50 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@34 51
universe@13 52 private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
universe@33 53
universe@11 54 /**
universe@11 55 * Store a reference to the annotation for quicker access.
universe@11 56 */
universe@33 57 private LightPITModule moduleInfo = null;
universe@10 58
universe@11 59 /**
universe@11 60 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
universe@11 61 */
universe@33 62 private LightPITModule.ELProxy moduleInfoELProxy = null;
universe@33 63
universe@33 64
universe@12 65 @FunctionalInterface
universe@33 66 private interface HandlerMethod {
universe@33 67 ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException;
universe@12 68 }
universe@34 69
universe@10 70 /**
universe@11 71 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@34 72 * <p>
universe@18 73 * Paths in this map must always start with a leading slash, although
universe@18 74 * the specification in the annotation must not start with a leading slash.
universe@34 75 * <p>
universe@34 76 * The reason for this is the different handling of empty paths in
universe@18 77 * {@link HttpServletRequest#getPathInfo()}.
universe@11 78 */
universe@12 79 private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
universe@11 80
universe@11 81 /**
universe@10 82 * Gives implementing modules access to the {@link ModuleManager}.
universe@33 83 *
universe@10 84 * @return the module manager
universe@10 85 */
universe@10 86 protected final ModuleManager getModuleManager() {
universe@10 87 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
universe@10 88 }
universe@33 89
universe@34 90 /**
universe@34 91 * Returns the annotated module information.
universe@34 92 *
universe@34 93 * @return the module annotation
universe@34 94 */
universe@33 95 public final LightPITModule getModuleInfo() {
universe@33 96 return moduleInfo;
universe@33 97 }
universe@33 98
universe@17 99 /**
universe@17 100 * Gives implementing modules access to the {@link DatabaseFacade}.
universe@33 101 *
universe@17 102 * @return the database facade
universe@17 103 */
universe@17 104 protected final DatabaseFacade getDatabaseFacade() {
universe@17 105 return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@17 106 }
universe@33 107
universe@33 108 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException {
universe@11 109 try {
universe@14 110 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
universe@12 111 return (ResponseType) method.invoke(this, req, resp);
universe@12 112 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@11 113 LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
universe@12 114 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
universe@12 115 return ResponseType.NONE;
universe@11 116 }
universe@11 117 }
universe@11 118
universe@11 119 @Override
universe@11 120 public void init() throws ServletException {
universe@33 121 moduleInfo = this.getClass().getAnnotation(LightPITModule.class);
universe@33 122 moduleInfoELProxy = moduleInfo == null ? null : LightPITModule.ELProxy.convert(moduleInfo);
universe@33 123
universe@33 124 if (moduleInfo != null) {
universe@12 125 scanForRequestMappings();
universe@12 126 }
universe@33 127
universe@12 128 LOG.trace("{} initialized", getServletName());
universe@12 129 }
universe@12 130
universe@12 131 private void scanForRequestMappings() {
universe@12 132 try {
universe@11 133 Method[] methods = getClass().getDeclaredMethods();
universe@11 134 for (Method method : methods) {
universe@11 135 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 136 if (mapping.isPresent()) {
universe@11 137 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 138 LOG.warn("{} is annotated with {} but is not public",
universe@11 139 method.getName(), RequestMapping.class.getSimpleName()
universe@11 140 );
universe@11 141 continue;
universe@11 142 }
universe@11 143 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 144 LOG.warn("{} is annotated with {} but is abstract",
universe@11 145 method.getName(), RequestMapping.class.getSimpleName()
universe@11 146 );
universe@11 147 continue;
universe@11 148 }
universe@12 149 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 150 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 151 method.getName(), RequestMapping.class.getSimpleName()
universe@12 152 );
universe@12 153 continue;
universe@12 154 }
universe@12 155
universe@11 156 Class<?>[] params = method.getParameterTypes();
universe@11 157 if (params.length == 2
universe@11 158 && HttpServletRequest.class.isAssignableFrom(params[0])
universe@11 159 && HttpServletResponse.class.isAssignableFrom(params[1])) {
universe@34 160
universe@34 161 final String requestPath = "/" + mapping.get().requestPath();
universe@12 162
universe@11 163 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
universe@18 164 putIfAbsent(requestPath,
universe@11 165 (req, resp) -> invokeMapping(method, req, resp)) != null) {
universe@11 166 LOG.warn("{} {} has multiple mappings",
universe@11 167 mapping.get().method(),
universe@11 168 mapping.get().requestPath()
universe@11 169 );
universe@11 170 }
universe@12 171
universe@22 172 LOG.debug("{} {} maps to {}::{}",
universe@11 173 mapping.get().method(),
universe@18 174 requestPath,
universe@22 175 getClass().getSimpleName(),
universe@11 176 method.getName()
universe@11 177 );
universe@11 178 } else {
universe@12 179 LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
universe@11 180 method.getName(), RequestMapping.class.getSimpleName()
universe@11 181 );
universe@11 182 }
universe@11 183 }
universe@11 184 }
universe@12 185 } catch (SecurityException ex) {
universe@12 186 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 187 }
universe@11 188 }
universe@11 189
universe@11 190 @Override
universe@11 191 public void destroy() {
universe@11 192 mappings.clear();
universe@11 193 LOG.trace("{} destroyed", getServletName());
universe@11 194 }
universe@34 195
universe@13 196 /**
universe@13 197 * Sets the name of the dynamic fragment.
universe@34 198 * <p>
universe@13 199 * It is sufficient to specify the name without any extension. The extension
universe@13 200 * is added automatically if not specified.
universe@34 201 * <p>
universe@13 202 * The fragment must be located in the dynamic fragments folder.
universe@34 203 *
universe@34 204 * @param req the servlet request object
universe@13 205 * @param fragmentName the name of the fragment
universe@13 206 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
universe@13 207 */
universe@13 208 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
universe@13 209 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
universe@13 210 }
universe@34 211
universe@11 212 /**
universe@13 213 * Specifies the name of an additional stylesheet used by the module.
universe@34 214 * <p>
universe@13 215 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 216 * output.
universe@34 217 * <p>
universe@13 218 * It is sufficient to specify the name without any extension. The extension
universe@13 219 * is added automatically if not specified.
universe@34 220 *
universe@34 221 * @param req the servlet request object
universe@13 222 * @param stylesheet the name of the stylesheet
universe@11 223 */
universe@13 224 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 225 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 226 }
universe@34 227
universe@10 228 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 229 throws IOException, ServletException {
universe@34 230
universe@27 231 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu(getDatabaseFacade()));
universe@13 232 req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
universe@10 233 }
universe@34 234
universe@12 235 private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
universe@11 236 return Optional.ofNullable(mappings.get(method)).map(
universe@18 237 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
universe@11 238 );
universe@11 239 }
universe@34 240
universe@34 241 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 242 throws ServletException, IOException {
universe@12 243 switch (type) {
universe@34 244 case NONE:
universe@34 245 return;
universe@12 246 case HTML_FULL:
universe@12 247 forwardToFullView(req, resp);
universe@12 248 return;
universe@12 249 // TODO: implement remaining response types
universe@12 250 default:
universe@34 251 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
universe@12 252 }
universe@12 253 }
universe@34 254
universe@12 255 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
universe@12 256 throws ServletException, IOException {
universe@27 257
universe@20 258 // Synchronize module information with database
universe@20 259 getModuleManager().syncWithDatabase(getDatabaseFacade());
universe@34 260
universe@13 261 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@20 262 HttpSession session = req.getSession();
universe@13 263 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 264 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 265 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 266 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 267 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@34 268 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@14 269 } else {
universe@15 270 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
universe@15 271 resp.setLocale(sessionLocale);
universe@15 272 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
universe@13 273 }
universe@34 274
universe@21 275 // set some internal request attributes
universe@13 276 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@13 277 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@33 278 Optional.ofNullable(moduleInfoELProxy).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@34 279
universe@34 280
universe@21 281 // call the handler, if available, or send an HTTP 404 error
universe@12 282 Optional<HandlerMethod> mapping = findMapping(method, req);
universe@12 283 if (mapping.isPresent()) {
universe@34 284 forwardAsSpecified(mapping.get().apply(req, resp), req, resp);
universe@12 285 } else {
universe@12 286 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@12 287 }
universe@12 288 }
universe@34 289
universe@7 290 @Override
universe@7 291 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 292 throws ServletException, IOException {
universe@12 293 doProcess(HttpMethod.GET, req, resp);
universe@7 294 }
universe@7 295
universe@7 296 @Override
universe@7 297 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 298 throws ServletException, IOException {
universe@12 299 doProcess(HttpMethod.POST, req, resp);
universe@7 300 }
universe@7 301 }

mercurial