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

Wed, 13 May 2020 18:45:28 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 13 May 2020 18:45:28 +0200
changeset 43
9abf0bf44c7b
parent 42
f962ff9dd44e
child 45
cc7f082c5ef3
permissions
-rw-r--r--

renames some crappy constants

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@33 42 import java.lang.reflect.Method;
universe@33 43 import java.lang.reflect.Modifier;
universe@38 44 import java.sql.Connection;
universe@38 45 import java.sql.SQLException;
universe@33 46 import java.util.*;
universe@7 47
universe@7 48 /**
universe@7 49 * A special implementation of a HTTPServlet which is focused on implementing
universe@7 50 * the necessary functionality for {@link LightPITModule}s.
universe@7 51 */
universe@9 52 public abstract class AbstractLightPITServlet extends HttpServlet {
universe@34 53
universe@10 54 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
universe@34 55
universe@43 56 private static final String SITE_JSP = Functions.jspPath("site");
universe@33 57
universe@11 58 /**
universe@11 59 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
universe@11 60 */
universe@36 61 private LightPITModule.ELProxy moduleInfo = null;
universe@33 62
universe@10 63 /**
universe@11 64 * Invocation mapping gathered from the {@link RequestMapping} annotations.
universe@34 65 * <p>
universe@18 66 * Paths in this map must always start with a leading slash, although
universe@18 67 * the specification in the annotation must not start with a leading slash.
universe@34 68 * <p>
universe@34 69 * The reason for this is the different handling of empty paths in
universe@18 70 * {@link HttpServletRequest#getPathInfo()}.
universe@11 71 */
universe@39 72 private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
universe@11 73
universe@11 74 /**
universe@10 75 * Gives implementing modules access to the {@link ModuleManager}.
universe@33 76 *
universe@10 77 * @return the module manager
universe@10 78 */
universe@10 79 protected final ModuleManager getModuleManager() {
universe@10 80 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
universe@10 81 }
universe@33 82
universe@38 83
universe@34 84 /**
universe@38 85 * Creates a set of data access objects for the specified connection.
universe@33 86 *
universe@38 87 * @param connection the SQL connection
universe@38 88 * @return a set of data access objects
universe@17 89 */
universe@38 90 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
universe@38 91 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@39 92 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
universe@39 93 return new PGDataAccessObjects(connection);
universe@38 94 }
universe@39 95 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
universe@17 96 }
universe@33 97
universe@38 98 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
universe@11 99 try {
universe@14 100 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
universe@42 101 final var paramTypes = method.getParameterTypes();
universe@42 102 final var paramValues = new Object[paramTypes.length];
universe@42 103 for (int i = 0; i < paramTypes.length; i++) {
universe@42 104 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
universe@42 105 paramValues[i] = req;
universe@42 106 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
universe@42 107 paramValues[i] = resp;
universe@42 108 }
universe@42 109 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
universe@42 110 paramValues[i] = dao;
universe@42 111 }
universe@42 112 }
universe@42 113 return (ResponseType) method.invoke(this, paramValues);
universe@12 114 } catch (ReflectiveOperationException | ClassCastException ex) {
universe@38 115 LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
universe@38 116 LOG.debug("Details: ", ex);
universe@12 117 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
universe@12 118 return ResponseType.NONE;
universe@11 119 }
universe@11 120 }
universe@11 121
universe@11 122 @Override
universe@11 123 public void init() throws ServletException {
universe@36 124 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
universe@36 125 .map(LightPITModule.ELProxy::new).orElse(null);
universe@33 126
universe@33 127 if (moduleInfo != null) {
universe@12 128 scanForRequestMappings();
universe@12 129 }
universe@33 130
universe@12 131 LOG.trace("{} initialized", getServletName());
universe@12 132 }
universe@12 133
universe@12 134 private void scanForRequestMappings() {
universe@12 135 try {
universe@11 136 Method[] methods = getClass().getDeclaredMethods();
universe@11 137 for (Method method : methods) {
universe@11 138 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
universe@11 139 if (mapping.isPresent()) {
universe@11 140 if (!Modifier.isPublic(method.getModifiers())) {
universe@11 141 LOG.warn("{} is annotated with {} but is not public",
universe@11 142 method.getName(), RequestMapping.class.getSimpleName()
universe@11 143 );
universe@11 144 continue;
universe@11 145 }
universe@11 146 if (Modifier.isAbstract(method.getModifiers())) {
universe@11 147 LOG.warn("{} is annotated with {} but is abstract",
universe@11 148 method.getName(), RequestMapping.class.getSimpleName()
universe@11 149 );
universe@11 150 continue;
universe@11 151 }
universe@12 152 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
universe@12 153 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
universe@12 154 method.getName(), RequestMapping.class.getSimpleName()
universe@12 155 );
universe@12 156 continue;
universe@12 157 }
universe@12 158
universe@42 159 boolean paramsInjectible = true;
universe@42 160 for (var param : method.getParameterTypes()) {
universe@42 161 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
universe@42 162 || HttpServletResponse.class.isAssignableFrom(param)
universe@42 163 || DataAccessObjects.class.isAssignableFrom(param);
universe@42 164 }
universe@42 165 if (paramsInjectible) {
universe@34 166 final String requestPath = "/" + mapping.get().requestPath();
universe@12 167
universe@39 168 if (mappings
universe@39 169 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
universe@39 170 .putIfAbsent(requestPath, method) != null) {
universe@11 171 LOG.warn("{} {} has multiple mappings",
universe@11 172 mapping.get().method(),
universe@11 173 mapping.get().requestPath()
universe@11 174 );
universe@11 175 }
universe@12 176
universe@22 177 LOG.debug("{} {} maps to {}::{}",
universe@11 178 mapping.get().method(),
universe@18 179 requestPath,
universe@22 180 getClass().getSimpleName(),
universe@11 181 method.getName()
universe@11 182 );
universe@11 183 } else {
universe@42 184 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
universe@11 185 method.getName(), RequestMapping.class.getSimpleName()
universe@11 186 );
universe@11 187 }
universe@11 188 }
universe@11 189 }
universe@12 190 } catch (SecurityException ex) {
universe@12 191 LOG.error("Scan for request mappings on declared methods failed.", ex);
universe@11 192 }
universe@11 193 }
universe@11 194
universe@11 195 @Override
universe@11 196 public void destroy() {
universe@11 197 mappings.clear();
universe@11 198 LOG.trace("{} destroyed", getServletName());
universe@11 199 }
universe@34 200
universe@13 201 /**
universe@13 202 * Sets the name of the dynamic fragment.
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 * <p>
universe@13 207 * The fragment must be located in the dynamic fragments folder.
universe@34 208 *
universe@34 209 * @param req the servlet request object
universe@13 210 * @param fragmentName the name of the fragment
universe@13 211 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
universe@13 212 */
universe@13 213 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
universe@13 214 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
universe@13 215 }
universe@34 216
universe@11 217 /**
universe@13 218 * Specifies the name of an additional stylesheet used by the module.
universe@34 219 * <p>
universe@13 220 * Setting an additional stylesheet is optional, but quite common for HTML
universe@13 221 * output.
universe@34 222 * <p>
universe@13 223 * It is sufficient to specify the name without any extension. The extension
universe@13 224 * is added automatically if not specified.
universe@34 225 *
universe@34 226 * @param req the servlet request object
universe@13 227 * @param stylesheet the name of the stylesheet
universe@11 228 */
universe@13 229 public void setStylesheet(HttpServletRequest req, String stylesheet) {
universe@13 230 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
universe@10 231 }
universe@34 232
universe@10 233 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
universe@10 234 throws IOException, ServletException {
universe@34 235
universe@36 236 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
universe@43 237 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
universe@10 238 }
universe@34 239
universe@39 240 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
universe@39 241 return Optional.ofNullable(mappings.get(method))
universe@39 242 .map(rm -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
universe@39 243 );
universe@11 244 }
universe@34 245
universe@34 246 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
universe@12 247 throws ServletException, IOException {
universe@12 248 switch (type) {
universe@34 249 case NONE:
universe@34 250 return;
universe@43 251 case HTML:
universe@12 252 forwardToFullView(req, resp);
universe@12 253 return;
universe@12 254 // TODO: implement remaining response types
universe@12 255 default:
universe@34 256 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
universe@12 257 }
universe@12 258 }
universe@34 259
universe@38 260 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
universe@27 261
universe@13 262 // choose the requested language as session language (if available) or fall back to english, otherwise
universe@20 263 HttpSession session = req.getSession();
universe@13 264 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
universe@13 265 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
universe@13 266 Optional<Locale> reqLocale = Optional.of(req.getLocale());
universe@13 267 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
universe@13 268 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
universe@34 269 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
universe@14 270 } else {
universe@15 271 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
universe@15 272 resp.setLocale(sessionLocale);
universe@15 273 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
universe@13 274 }
universe@34 275
universe@21 276 // set some internal request attributes
universe@13 277 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
universe@13 278 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
universe@36 279 Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
universe@34 280
universe@38 281 // obtain a connection and create the data access objects
universe@38 282 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
universe@38 283 try (final var connection = db.getDataSource().getConnection()) {
universe@38 284 final var dao = createDataAccessObjects(connection);
universe@39 285 try {
universe@39 286 connection.setAutoCommit(false);
universe@39 287 // call the handler, if available, or send an HTTP 404 error
universe@39 288 final var mapping = findMapping(method, req);
universe@39 289 if (mapping.isPresent()) {
universe@39 290 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
universe@39 291 } else {
universe@39 292 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
universe@39 293 }
universe@39 294 connection.commit();
universe@39 295 } catch (SQLException ex) {
universe@39 296 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
universe@39 297 LOG.debug("Details: ", ex);
universe@39 298 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code:" + ex.getErrorCode());
universe@39 299 connection.rollback();
universe@38 300 }
universe@38 301 } catch (SQLException ex) {
universe@39 302 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
universe@38 303 LOG.debug("Details: ", ex);
universe@38 304 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code:" + ex.getErrorCode());
universe@12 305 }
universe@12 306 }
universe@34 307
universe@7 308 @Override
universe@7 309 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
universe@7 310 throws ServletException, IOException {
universe@12 311 doProcess(HttpMethod.GET, req, resp);
universe@7 312 }
universe@7 313
universe@7 314 @Override
universe@7 315 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
universe@7 316 throws ServletException, IOException {
universe@12 317 doProcess(HttpMethod.POST, req, resp);
universe@7 318 }
universe@7 319 }

mercurial