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

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

mercurial