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

Sat, 23 May 2020 14:13:09 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 23 May 2020 14:13:09 +0200
changeset 79
f64255a88d66
parent 78
bb4c52bf3439
child 80
27a25f32048e
permissions
-rw-r--r--

bloat removal 3/3 - LightPITModule annotation and ModuleManager

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@38 31 import de.uapcore.lightpit.dao.DataAccessObjects;
universe@38 32 import de.uapcore.lightpit.dao.postgres.PGDataAccessObjects;
universe@33 33 import org.slf4j.Logger;
universe@33 34 import org.slf4j.LoggerFactory;
universe@33 35
universe@7 36 import javax.servlet.ServletException;
universe@7 37 import javax.servlet.http.HttpServlet;
universe@7 38 import javax.servlet.http.HttpServletRequest;
universe@7 39 import javax.servlet.http.HttpServletResponse;
universe@13 40 import javax.servlet.http.HttpSession;
universe@33 41 import java.io.IOException;
universe@47 42 import java.lang.reflect.Constructor;
universe@73 43 import java.lang.reflect.InvocationTargetException;
universe@33 44 import java.lang.reflect.Method;
universe@33 45 import java.lang.reflect.Modifier;
universe@38 46 import java.sql.Connection;
universe@38 47 import java.sql.SQLException;
universe@33 48 import java.util.*;
universe@63 49 import java.util.function.Function;
universe@7 50
universe@7 51 /**
universe@7 52 * A special implementation of a HTTPServlet which is focused on implementing
universe@79 53 * the necessary functionality for LightPIT pages.
universe@7 54 */
universe@9 55 public abstract class AbstractLightPITServlet extends HttpServlet {
universe@34 56
universe@10 57 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@34 58
universe@43 59 private static final String SITE_JSP = Functions.jspPath("site");
universe@33 60
universe@33 61
universe@63 62 @FunctionalInterface
universe@63 63 protected interface SQLFindFunction<K, T> {
universe@63 64 T apply(K key) throws SQLException;
universe@63 65
universe@63 66 default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
universe@63 67 Objects.requireNonNull(before);
universe@63 68 return (v) -> this.apply(before.apply(v));
universe@63 69 }
universe@63 70
universe@63 71 default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
universe@63 72 Objects.requireNonNull(after);
universe@63 73 return (t) -> after.apply(this.apply(t));
universe@63 74 }
universe@63 75
universe@63 76 static <K> Function<K, K> identity() {
universe@63 77 return (t) -> t;
universe@63 78 }
universe@63 79 }
universe@63 80
universe@10 81 /**
universe@11 82 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@34 83 * <p>
universe@18 84 * Paths in this map must always start with a leading slash, although
universe@18 85 * the specification in the annotation must not start with a leading slash.
universe@34 86 * <p>
universe@34 87 * The reason for this is the different handling of empty paths in
universe@18 88 * {@link HttpServletRequest#getPathInfo()}.
universe@11 89 */
universe@39 90 private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
universe@11 91
universe@11 92 /**
universe@78 93 * Returns the name of the resource bundle associated with this servlet.
universe@78 94 * @return the resource bundle base name
universe@78 95 */
universe@78 96 protected abstract String getResourceBundleName();
universe@78 97
universe@38 98
universe@34 99 /**
universe@38 100 * Creates a set of data access objects for the specified connection.
universe@33 101 *
universe@38 102 * @param connection the SQL connection
universe@38 103 * @return a set of data access objects
universe@17 104 */
universe@38 105 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
universe@38 106 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@39 107 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
universe@39 108 return new PGDataAccessObjects(connection);
universe@38 109 }
universe@39 110 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
universe@17 111 }
universe@33 112
universe@38 113 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
universe@11 114 try {
universe@14 115 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
universe@42 116 final var paramTypes = method.getParameterTypes();
universe@42 117 final var paramValues = new Object[paramTypes.length];
universe@42 118 for (int i = 0; i < paramTypes.length; i++) {
universe@42 119 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
universe@42 120 paramValues[i] = req;
universe@42 121 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
universe@42 122 paramValues[i] = resp;
universe@42 123 }
universe@42 124 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
universe@42 125 paramValues[i] = dao;
universe@42 126 }
universe@42 127 }
universe@42 128 return (ResponseType) method.invoke(this, paramValues);
universe@73 129 } catch (InvocationTargetException ex) {
universe@73 130 LOG.error("invocation of method {}::{} failed: {}",
universe@73 131 method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
universe@73 132 LOG.debug("Details: ", ex.getTargetException());
universe@73 133 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
universe@73 134 return ResponseType.NONE;
universe@12 135 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@73 136 LOG.error("invocation of method {}::{} failed: {}",
universe@73 137 method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
universe@38 138 LOG.debug("Details: ", ex);
universe@73 139 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
universe@12 140 return ResponseType.NONE;
universe@11 141 }
universe@11 142 }
universe@11 143
universe@11 144 @Override
universe@11 145 public void init() throws ServletException {
universe@78 146 scanForRequestMappings();
universe@33 147
universe@12 148 LOG.trace("{} initialized", getServletName());
universe@12 149 }
universe@12 150
universe@12 151 private void scanForRequestMappings() {
universe@12 152 try {
universe@11 153 Method[] methods = getClass().getDeclaredMethods();
universe@11 154 for (Method method : methods) {
universe@11 155 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 156 if (mapping.isPresent()) {
universe@11 157 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 158 LOG.warn("{} is annotated with {} but is not public",
universe@11 159 method.getName(), RequestMapping.class.getSimpleName()
universe@11 160 );
universe@11 161 continue;
universe@11 162 }
universe@11 163 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 164 LOG.warn("{} is annotated with {} but is abstract",
universe@11 165 method.getName(), RequestMapping.class.getSimpleName()
universe@11 166 );
universe@11 167 continue;
universe@11 168 }
universe@12 169 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 170 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 171 method.getName(), RequestMapping.class.getSimpleName()
universe@12 172 );
universe@12 173 continue;
universe@12 174 }
universe@12 175
universe@42 176 boolean paramsInjectible = true;
universe@42 177 for (var param : method.getParameterTypes()) {
universe@42 178 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
universe@42 179 || HttpServletResponse.class.isAssignableFrom(param)
universe@42 180 || DataAccessObjects.class.isAssignableFrom(param);
universe@42 181 }
universe@42 182 if (paramsInjectible) {
universe@58 183 String requestPath = "/" + mapping.get().requestPath();
universe@12 184
universe@39 185 if (mappings
universe@39 186 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
universe@39 187 .putIfAbsent(requestPath, method) != null) {
universe@11 188 LOG.warn("{} {} has multiple mappings",
universe@11 189 mapping.get().method(),
universe@11 190 mapping.get().requestPath()
universe@11 191 );
universe@11 192 }
universe@12 193
universe@22 194 LOG.debug("{} {} maps to {}::{}",
universe@11 195 mapping.get().method(),
universe@18 196 requestPath,
universe@22 197 getClass().getSimpleName(),
universe@11 198 method.getName()
universe@11 199 );
universe@11 200 } else {
universe@42 201 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
universe@11 202 method.getName(), RequestMapping.class.getSimpleName()
universe@11 203 );
universe@11 204 }
universe@11 205 }
universe@11 206 }
universe@12 207 } catch (SecurityException ex) {
universe@12 208 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 209 }
universe@11 210 }
universe@11 211
universe@11 212 @Override
universe@11 213 public void destroy() {
universe@11 214 mappings.clear();
universe@11 215 LOG.trace("{} destroyed", getServletName());
universe@11 216 }
universe@34 217
universe@13 218 /**
universe@74 219 * Sets the name of the content page.
universe@34 220 * <p>
universe@13 221 * It is sufficient to specify the name without any extension. The extension
universe@13 222 * is added automatically if not specified.
universe@34 223 *
universe@74 224 * @param req the servlet request object
universe@74 225 * @param pageName the name of the content page
universe@74 226 * @see Constants#REQ_ATTR_CONTENT_PAGE
universe@13 227 */
universe@74 228 protected void setContentPage(HttpServletRequest req, String pageName) {
universe@74 229 req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
universe@13 230 }
universe@34 231
universe@11 232 /**
universe@71 233 * Sets the breadcrumbs menu.
universe@71 234 *
universe@71 235 * @param req the servlet request object
universe@71 236 * @param breadcrumbs the menu entries for the breadcrumbs menu
universe@71 237 * @see Constants#REQ_ATTR_BREADCRUMBS
universe@71 238 */
universe@71 239 protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
universe@71 240 req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
universe@71 241 }
universe@71 242
universe@71 243 /**
universe@47 244 * @param req the servlet request object
universe@47 245 * @param location the location where to redirect
universe@47 246 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
universe@47 247 */
universe@63 248 protected void setRedirectLocation(HttpServletRequest req, String location) {
universe@47 249 if (location.startsWith("./")) {
universe@47 250 location = location.replaceFirst("\\./", Functions.baseHref(req));
universe@47 251 }
universe@47 252 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
universe@47 253 }
universe@47 254
universe@47 255 /**
universe@13 256 * Specifies the name of an additional stylesheet used by the module.
universe@34 257 * <p>
universe@13 258 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 259 * output.
universe@34 260 * <p>
universe@13 261 * It is sufficient to specify the name without any extension. The extension
universe@13 262 * is added automatically if not specified.
universe@34 263 *
universe@34 264 * @param req the servlet request object
universe@13 265 * @param stylesheet the name of the stylesheet
universe@11 266 */
universe@13 267 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 268 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 269 }
universe@34 270
universe@47 271 /**
universe@47 272 * Obtains a request parameter of the specified type.
universe@47 273 * The specified type must have a single-argument constructor accepting a string to perform conversion.
universe@47 274 * The constructor of the specified type may throw an exception on conversion failures.
universe@47 275 *
universe@71 276 * @param req the servlet request object
universe@47 277 * @param clazz the class object of the expected type
universe@71 278 * @param name the name of the parameter
universe@71 279 * @param <T> the expected type
universe@47 280 * @return the parameter value or an empty optional, if no parameter with the specified name was found
universe@47 281 */
universe@71 282 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
universe@47 283 final String paramValue = req.getParameter(name);
universe@47 284 if (paramValue == null) return Optional.empty();
universe@71 285 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
universe@75 286 if (java.sql.Date.class.isAssignableFrom(clazz)) {
universe@75 287 try {
universe@75 288 return Optional.of((T)java.sql.Date.valueOf(paramValue));
universe@75 289 } catch (IllegalArgumentException ex) {
universe@75 290 return Optional.empty();
universe@75 291 }
universe@75 292 }
universe@47 293 try {
universe@47 294 final Constructor<T> ctor = clazz.getConstructor(String.class);
universe@47 295 return Optional.of(ctor.newInstance(paramValue));
universe@47 296 } catch (ReflectiveOperationException e) {
universe@47 297 throw new RuntimeException(e);
universe@47 298 }
universe@47 299
universe@47 300 }
universe@47 301
universe@63 302 /**
universe@63 303 * Tries to look up an entity with a key obtained from a request parameter.
universe@63 304 *
universe@71 305 * @param req the servlet request object
universe@63 306 * @param clazz the class representing the type of the request parameter
universe@71 307 * @param name the name of the request parameter
universe@71 308 * @param find the find function (typically a DAO function)
universe@71 309 * @param <T> the type of the request parameter
universe@71 310 * @param <R> the type of the looked up entity
universe@63 311 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
universe@63 312 * @throws SQLException if the find function throws an exception
universe@63 313 */
universe@71 314 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
universe@63 315 final var param = getParameter(req, clazz, name);
universe@63 316 if (param.isPresent()) {
universe@63 317 return Optional.ofNullable(find.apply(param.get()));
universe@63 318 } else {
universe@63 319 return Optional.empty();
universe@63 320 }
universe@63 321 }
universe@63 322
universe@10 323 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 324 throws IOException, ServletException {
universe@34 325
universe@79 326 final String lightpitBundle = "localization.lightpit";
universe@79 327 final var mainMenu = List.of(
universe@79 328 new MenuEntry(new ResourceKey(lightpitBundle, "menu.projects"), "projects/"),
universe@79 329 new MenuEntry(new ResourceKey(lightpitBundle, "menu.users"), "teams/"),
universe@79 330 new MenuEntry(new ResourceKey(lightpitBundle, "menu.languages"), "language/")
universe@79 331 );
universe@71 332 for (var entry : mainMenu) {
universe@71 333 if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
universe@71 334 entry.setActive(true);
universe@71 335 }
universe@71 336 }
universe@71 337 req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
universe@43 338 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
universe@10 339 }
universe@34 340
universe@45 341 private String sanitizeRequestPath(HttpServletRequest req) {
universe@45 342 return Optional.ofNullable(req.getPathInfo()).orElse("/");
universe@45 343 }
universe@45 344
universe@39 345 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
universe@45 346 return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
universe@11 347 }
universe@34 348
universe@34 349 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 350 throws ServletException, IOException {
universe@12 351 switch (type) {
universe@34 352 case NONE:
universe@34 353 return;
universe@43 354 case HTML:
universe@12 355 forwardToFullView(req, resp);
universe@12 356 return;
universe@12 357 // TODO: implement remaining response types
universe@12 358 default:
universe@34 359 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
universe@12 360 }
universe@12 361 }
universe@34 362
universe@38 363 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
universe@27 364
universe@13 365 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@20 366 HttpSession session = req.getSession();
universe@13 367 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 368 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 369 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 370 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 371 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@34 372 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@14 373 } else {
universe@15 374 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
universe@15 375 resp.setLocale(sessionLocale);
universe@15 376 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
universe@13 377 }
universe@34 378
universe@21 379 // set some internal request attributes
universe@53 380 final String fullPath = Functions.fullPath(req);
universe@47 381 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
universe@53 382 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
universe@78 383 req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
universe@34 384
universe@53 385 // if this is an error path, bypass the normal flow
universe@53 386 if (fullPath.startsWith("/error/")) {
universe@53 387 final var mapping = findMapping(method, req);
universe@53 388 if (mapping.isPresent()) {
universe@53 389 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
universe@53 390 }
universe@53 391 return;
universe@53 392 }
universe@53 393
universe@38 394 // obtain a connection and create the data access objects
universe@38 395 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@53 396 final var ds = db.getDataSource();
universe@53 397 if (ds == null) {
universe@53 398 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
universe@53 399 return;
universe@53 400 }
universe@53 401 try (final var connection = ds.getConnection()) {
universe@38 402 final var dao = createDataAccessObjects(connection);
universe@39 403 try {
universe@39 404 connection.setAutoCommit(false);
universe@39 405 // call the handler, if available, or send an HTTP 404 error
universe@39 406 final var mapping = findMapping(method, req);
universe@39 407 if (mapping.isPresent()) {
universe@39 408 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
universe@39 409 } else {
universe@39 410 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@39 411 }
universe@39 412 connection.commit();
universe@39 413 } catch (SQLException ex) {
universe@39 414 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
universe@39 415 LOG.debug("Details: ", ex);
universe@54 416 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
universe@39 417 connection.rollback();
universe@38 418 }
universe@38 419 } catch (SQLException ex) {
universe@39 420 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
universe@38 421 LOG.debug("Details: ", ex);
universe@54 422 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
universe@12 423 }
universe@12 424 }
universe@34 425
universe@7 426 @Override
universe@7 427 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 428 throws ServletException, IOException {
universe@12 429 doProcess(HttpMethod.GET, req, resp);
universe@7 430 }
universe@7 431
universe@7 432 @Override
universe@7 433 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 434 throws ServletException, IOException {
universe@12 435 doProcess(HttpMethod.POST, req, resp);
universe@7 436 }
universe@7 437 }

mercurial