Sat, 23 May 2020 13:52:04 +0200
bloat removal 2/3 - moduleInfo
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 {@link LightPITModule}s.
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 * Gives implementing modules access to the {@link ModuleManager}.
94 *
95 * @return the module manager
96 */
97 protected final ModuleManager getModuleManager() {
98 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
99 }
101 /**
102 * Returns the name of the resource bundle associated with this servlet.
103 * @return the resource bundle base name
104 */
105 protected abstract String getResourceBundleName();
108 /**
109 * Creates a set of data access objects for the specified connection.
110 *
111 * @param connection the SQL connection
112 * @return a set of data access objects
113 */
114 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
115 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
116 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
117 return new PGDataAccessObjects(connection);
118 }
119 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
120 }
122 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
123 try {
124 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
125 final var paramTypes = method.getParameterTypes();
126 final var paramValues = new Object[paramTypes.length];
127 for (int i = 0; i < paramTypes.length; i++) {
128 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
129 paramValues[i] = req;
130 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
131 paramValues[i] = resp;
132 }
133 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
134 paramValues[i] = dao;
135 }
136 }
137 return (ResponseType) method.invoke(this, paramValues);
138 } catch (InvocationTargetException ex) {
139 LOG.error("invocation of method {}::{} failed: {}",
140 method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
141 LOG.debug("Details: ", ex.getTargetException());
142 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
143 return ResponseType.NONE;
144 } catch (ReflectiveOperationException | ClassCastException ex) {
145 LOG.error("invocation of method {}::{} failed: {}",
146 method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
147 LOG.debug("Details: ", ex);
148 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
149 return ResponseType.NONE;
150 }
151 }
153 @Override
154 public void init() throws ServletException {
155 scanForRequestMappings();
157 LOG.trace("{} initialized", getServletName());
158 }
160 private void scanForRequestMappings() {
161 try {
162 Method[] methods = getClass().getDeclaredMethods();
163 for (Method method : methods) {
164 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
165 if (mapping.isPresent()) {
166 if (!Modifier.isPublic(method.getModifiers())) {
167 LOG.warn("{} is annotated with {} but is not public",
168 method.getName(), RequestMapping.class.getSimpleName()
169 );
170 continue;
171 }
172 if (Modifier.isAbstract(method.getModifiers())) {
173 LOG.warn("{} is annotated with {} but is abstract",
174 method.getName(), RequestMapping.class.getSimpleName()
175 );
176 continue;
177 }
178 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
179 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
180 method.getName(), RequestMapping.class.getSimpleName()
181 );
182 continue;
183 }
185 boolean paramsInjectible = true;
186 for (var param : method.getParameterTypes()) {
187 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
188 || HttpServletResponse.class.isAssignableFrom(param)
189 || DataAccessObjects.class.isAssignableFrom(param);
190 }
191 if (paramsInjectible) {
192 String requestPath = "/" + mapping.get().requestPath();
194 if (mappings
195 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
196 .putIfAbsent(requestPath, method) != null) {
197 LOG.warn("{} {} has multiple mappings",
198 mapping.get().method(),
199 mapping.get().requestPath()
200 );
201 }
203 LOG.debug("{} {} maps to {}::{}",
204 mapping.get().method(),
205 requestPath,
206 getClass().getSimpleName(),
207 method.getName()
208 );
209 } else {
210 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
211 method.getName(), RequestMapping.class.getSimpleName()
212 );
213 }
214 }
215 }
216 } catch (SecurityException ex) {
217 LOG.error("Scan for request mappings on declared methods failed.", ex);
218 }
219 }
221 @Override
222 public void destroy() {
223 mappings.clear();
224 LOG.trace("{} destroyed", getServletName());
225 }
227 /**
228 * Sets the name of the content page.
229 * <p>
230 * It is sufficient to specify the name without any extension. The extension
231 * is added automatically if not specified.
232 *
233 * @param req the servlet request object
234 * @param pageName the name of the content page
235 * @see Constants#REQ_ATTR_CONTENT_PAGE
236 */
237 protected void setContentPage(HttpServletRequest req, String pageName) {
238 req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
239 }
241 /**
242 * Sets the breadcrumbs menu.
243 *
244 * @param req the servlet request object
245 * @param breadcrumbs the menu entries for the breadcrumbs menu
246 * @see Constants#REQ_ATTR_BREADCRUMBS
247 */
248 protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
249 req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
250 }
252 /**
253 * @param req the servlet request object
254 * @param location the location where to redirect
255 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
256 */
257 protected void setRedirectLocation(HttpServletRequest req, String location) {
258 if (location.startsWith("./")) {
259 location = location.replaceFirst("\\./", Functions.baseHref(req));
260 }
261 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
262 }
264 /**
265 * Specifies the name of an additional stylesheet used by the module.
266 * <p>
267 * Setting an additional stylesheet is optional, but quite common for HTML
268 * output.
269 * <p>
270 * It is sufficient to specify the name without any extension. The extension
271 * is added automatically if not specified.
272 *
273 * @param req the servlet request object
274 * @param stylesheet the name of the stylesheet
275 */
276 public void setStylesheet(HttpServletRequest req, String stylesheet) {
277 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
278 }
280 /**
281 * Obtains a request parameter of the specified type.
282 * The specified type must have a single-argument constructor accepting a string to perform conversion.
283 * The constructor of the specified type may throw an exception on conversion failures.
284 *
285 * @param req the servlet request object
286 * @param clazz the class object of the expected type
287 * @param name the name of the parameter
288 * @param <T> the expected type
289 * @return the parameter value or an empty optional, if no parameter with the specified name was found
290 */
291 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
292 final String paramValue = req.getParameter(name);
293 if (paramValue == null) return Optional.empty();
294 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
295 if (java.sql.Date.class.isAssignableFrom(clazz)) {
296 try {
297 return Optional.of((T)java.sql.Date.valueOf(paramValue));
298 } catch (IllegalArgumentException ex) {
299 return Optional.empty();
300 }
301 }
302 try {
303 final Constructor<T> ctor = clazz.getConstructor(String.class);
304 return Optional.of(ctor.newInstance(paramValue));
305 } catch (ReflectiveOperationException e) {
306 throw new RuntimeException(e);
307 }
309 }
311 /**
312 * Tries to look up an entity with a key obtained from a request parameter.
313 *
314 * @param req the servlet request object
315 * @param clazz the class representing the type of the request parameter
316 * @param name the name of the request parameter
317 * @param find the find function (typically a DAO function)
318 * @param <T> the type of the request parameter
319 * @param <R> the type of the looked up entity
320 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
321 * @throws SQLException if the find function throws an exception
322 */
323 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
324 final var param = getParameter(req, clazz, name);
325 if (param.isPresent()) {
326 return Optional.ofNullable(find.apply(param.get()));
327 } else {
328 return Optional.empty();
329 }
330 }
332 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
333 throws IOException, ServletException {
335 final var mainMenu = new ArrayList<MenuEntry>(getModuleManager().getMainMenu());
336 for (var entry : mainMenu) {
337 if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
338 entry.setActive(true);
339 }
340 }
341 req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
342 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
343 }
345 private String sanitizeRequestPath(HttpServletRequest req) {
346 return Optional.ofNullable(req.getPathInfo()).orElse("/");
347 }
349 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
350 return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
351 }
353 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
354 throws ServletException, IOException {
355 switch (type) {
356 case NONE:
357 return;
358 case HTML:
359 forwardToFullView(req, resp);
360 return;
361 // TODO: implement remaining response types
362 default:
363 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
364 }
365 }
367 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
369 // choose the requested language as session language (if available) or fall back to english, otherwise
370 HttpSession session = req.getSession();
371 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
372 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
373 Optional<Locale> reqLocale = Optional.of(req.getLocale());
374 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
375 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
376 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
377 } else {
378 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
379 resp.setLocale(sessionLocale);
380 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
381 }
383 // set some internal request attributes
384 final String fullPath = Functions.fullPath(req);
385 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
386 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
387 req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
389 // if this is an error path, bypass the normal flow
390 if (fullPath.startsWith("/error/")) {
391 final var mapping = findMapping(method, req);
392 if (mapping.isPresent()) {
393 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
394 }
395 return;
396 }
398 // obtain a connection and create the data access objects
399 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
400 final var ds = db.getDataSource();
401 if (ds == null) {
402 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
403 return;
404 }
405 try (final var connection = ds.getConnection()) {
406 final var dao = createDataAccessObjects(connection);
407 try {
408 connection.setAutoCommit(false);
409 // call the handler, if available, or send an HTTP 404 error
410 final var mapping = findMapping(method, req);
411 if (mapping.isPresent()) {
412 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
413 } else {
414 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
415 }
416 connection.commit();
417 } catch (SQLException ex) {
418 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
419 LOG.debug("Details: ", ex);
420 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
421 connection.rollback();
422 }
423 } catch (SQLException ex) {
424 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
425 LOG.debug("Details: ", ex);
426 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
427 }
428 }
430 @Override
431 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
432 throws ServletException, IOException {
433 doProcess(HttpMethod.GET, req, resp);
434 }
436 @Override
437 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
438 throws ServletException, IOException {
439 doProcess(HttpMethod.POST, req, resp);
440 }
441 }