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