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

Mon, 18 May 2020 21:06:38 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 18 May 2020 21:06:38 +0200
changeset 63
51aa5e267c7f
parent 58
8d3047f78190
child 70
821c4950b619
permissions
-rw-r--r--

adds utility function to find an entity by ID (reduces code duplication)

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

mercurial