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

Sun, 10 May 2020 10:11:37 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 10 May 2020 10:11:37 +0200
changeset 36
0f4f8f255c32
parent 34
824d4042c857
child 38
cf85ef18f231
permissions
-rw-r--r--

removes features that are not (and probably will not) used anyway

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

mercurial