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

Tue, 12 May 2020 22:03:00 +0200

author
Mike Becker <universe@uap-core.de>
date
Tue, 12 May 2020 22:03:00 +0200
changeset 39
e722861558bb
parent 38
cf85ef18f231
child 40
276ef00a336d
permissions
-rw-r--r--

fixes minor issues that were reported by default inspection

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

mercurial