Fri, 23 Oct 2020 12:38:20 +0200
removes (now) unnecessary possibility to customize the main menu
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.*;
43 import java.sql.Connection;
44 import java.sql.SQLException;
45 import java.util.*;
46 import java.util.function.Function;
48 /**
49 * A special implementation of a HTTPServlet which is focused on implementing
50 * the necessary functionality for LightPIT pages.
51 */
52 public abstract class AbstractLightPITServlet extends HttpServlet {
54 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
56 private static final String SITE_JSP = Functions.jspPath("site");
59 @FunctionalInterface
60 protected interface SQLFindFunction<K, T> {
61 T apply(K key) throws SQLException;
63 default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
64 Objects.requireNonNull(before);
65 return (v) -> this.apply(before.apply(v));
66 }
68 default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
69 Objects.requireNonNull(after);
70 return (t) -> after.apply(this.apply(t));
71 }
73 static <K> Function<K, K> identity() {
74 return (t) -> t;
75 }
76 }
78 /**
79 * Invocation mapping gathered from the {@link RequestMapping} annotations.
80 * <p>
81 * Paths in this map must always start with a leading slash, although
82 * the specification in the annotation must not start with a leading slash.
83 * <p>
84 * The reason for this is the different handling of empty paths in
85 * {@link HttpServletRequest#getPathInfo()}.
86 */
87 private final Map<HttpMethod, Map<PathPattern, Method>> mappings = new HashMap<>();
89 /**
90 * Returns the name of the resource bundle associated with this servlet.
91 *
92 * @return the resource bundle base name
93 */
94 protected abstract String getResourceBundleName();
97 /**
98 * Creates a set of data access objects for the specified connection.
99 *
100 * @param connection the SQL connection
101 * @return a set of data access objects
102 */
103 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
104 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
105 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
106 return new PGDataAccessObjects(connection);
107 }
108 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
109 }
111 private ResponseType invokeMapping(Map.Entry<PathPattern, Method> mapping, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
112 final var pathPattern = mapping.getKey();
113 final var method = mapping.getValue();
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 if (paramTypes[i].isAssignableFrom(PathParameters.class)) {
128 paramValues[i] = pathPattern.obtainPathParameters(sanitizeRequestPath(req));
129 }
130 }
131 return (ResponseType) method.invoke(this, paramValues);
132 } catch (InvocationTargetException ex) {
133 LOG.error("invocation of method {}::{} failed: {}",
134 method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
135 LOG.debug("Details: ", ex.getTargetException());
136 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
137 return ResponseType.NONE;
138 } catch (ReflectiveOperationException | ClassCastException ex) {
139 LOG.error("invocation of method {}::{} failed: {}",
140 method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
141 LOG.debug("Details: ", ex);
142 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
143 return ResponseType.NONE;
144 }
145 }
147 @Override
148 public void init() throws ServletException {
149 scanForRequestMappings();
151 LOG.trace("{} initialized", getServletName());
152 }
154 private void scanForRequestMappings() {
155 try {
156 Method[] methods = getClass().getDeclaredMethods();
157 for (Method method : methods) {
158 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
159 if (mapping.isPresent()) {
160 if (mapping.get().requestPath().isBlank()) {
161 LOG.warn("{} is annotated with {} but request path is empty",
162 method.getName(), RequestMapping.class.getSimpleName()
163 );
164 continue;
165 }
167 if (!Modifier.isPublic(method.getModifiers())) {
168 LOG.warn("{} is annotated with {} but is not public",
169 method.getName(), RequestMapping.class.getSimpleName()
170 );
171 continue;
172 }
173 if (Modifier.isAbstract(method.getModifiers())) {
174 LOG.warn("{} is annotated with {} but is abstract",
175 method.getName(), RequestMapping.class.getSimpleName()
176 );
177 continue;
178 }
179 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
180 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
181 method.getName(), RequestMapping.class.getSimpleName()
182 );
183 continue;
184 }
186 boolean paramsInjectible = true;
187 for (var param : method.getParameterTypes()) {
188 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
189 || HttpServletResponse.class.isAssignableFrom(param)
190 || PathParameters.class.isAssignableFrom(param)
191 || DataAccessObjects.class.isAssignableFrom(param);
192 }
193 if (paramsInjectible) {
194 try {
195 PathPattern pathPattern = new PathPattern(mapping.get().requestPath());
197 final var methodMappings = mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>());
198 final var currentMapping = methodMappings.putIfAbsent(pathPattern, method);
199 if (currentMapping != null) {
200 LOG.warn("Cannot map {} {} to {} in class {} - this would override the mapping to {}",
201 mapping.get().method(),
202 mapping.get().requestPath(),
203 method.getName(),
204 getClass().getSimpleName(),
205 currentMapping.getName()
206 );
207 }
209 LOG.debug("{} {} maps to {}::{}",
210 mapping.get().method(),
211 mapping.get().requestPath(),
212 getClass().getSimpleName(),
213 method.getName()
214 );
215 } catch (IllegalArgumentException ex) {
216 LOG.warn("Request mapping for {} failed: path pattern '{}' is syntactically invalid",
217 method.getName(), mapping.get().requestPath()
218 );
219 }
220 } else {
221 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest, HttpServletResponse, PathParameters, and DataAccessObjects are allowed",
222 method.getName(), RequestMapping.class.getSimpleName()
223 );
224 }
225 }
226 }
227 } catch (SecurityException ex) {
228 LOG.error("Scan for request mappings on declared methods failed.", ex);
229 }
230 }
232 @Override
233 public void destroy() {
234 mappings.clear();
235 LOG.trace("{} destroyed", getServletName());
236 }
238 /**
239 * Sets the name of the content page.
240 * <p>
241 * It is sufficient to specify the name without any extension. The extension
242 * is added automatically if not specified.
243 *
244 * @param req the servlet request object
245 * @param pageName the name of the content page
246 * @see Constants#REQ_ATTR_CONTENT_PAGE
247 */
248 protected void setContentPage(HttpServletRequest req, String pageName) {
249 req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
250 }
252 /**
253 * Sets the navigation menu.
254 *
255 * @param req the servlet request object
256 * @param jspName the name of the menu's jsp file
257 * @see Constants#REQ_ATTR_NAVIGATION
258 */
259 protected void setNavigationMenu(HttpServletRequest req, String jspName) {
260 req.setAttribute(Constants.REQ_ATTR_NAVIGATION, Functions.jspPath(jspName));
261 }
263 /**
264 * @param req the servlet request object
265 * @param location the location where to redirect
266 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
267 */
268 protected void setRedirectLocation(HttpServletRequest req, String location) {
269 if (location.startsWith("./")) {
270 location = location.replaceFirst("\\./", Functions.baseHref(req));
271 }
272 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
273 }
275 /**
276 * Specifies the name of an additional stylesheet used by the module.
277 * <p>
278 * Setting an additional stylesheet is optional, but quite common for HTML
279 * output.
280 * <p>
281 * It is sufficient to specify the name without any extension. The extension
282 * is added automatically if not specified.
283 *
284 * @param req the servlet request object
285 * @param stylesheet the name of the stylesheet
286 */
287 public void setStylesheet(HttpServletRequest req, String stylesheet) {
288 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
289 }
291 /**
292 * Sets the view model object.
293 * The type must match the expected type in the JSP file.
294 *
295 * @param req the servlet request object
296 * @param viewModel the view model object
297 */
298 public void setViewModel(HttpServletRequest req, Object viewModel) {
299 req.setAttribute(Constants.REQ_ATTR_VIEWMODEL, viewModel);
300 }
302 private <T> Optional<T> parseParameter(String paramValue, Class<T> clazz) {
303 if (paramValue == null) return Optional.empty();
304 if (clazz.equals(Boolean.class)) {
305 if (paramValue.toLowerCase().equals("false") || paramValue.equals("0")) {
306 return Optional.of((T) Boolean.FALSE);
307 } else {
308 return Optional.of((T) Boolean.TRUE);
309 }
310 }
311 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
312 if (java.sql.Date.class.isAssignableFrom(clazz)) {
313 try {
314 return Optional.of((T) java.sql.Date.valueOf(paramValue));
315 } catch (IllegalArgumentException ex) {
316 return Optional.empty();
317 }
318 }
319 try {
320 final Constructor<T> ctor = clazz.getConstructor(String.class);
321 return Optional.of(ctor.newInstance(paramValue));
322 } catch (ReflectiveOperationException e) {
323 // does not type check and is not convertible - treat as if the parameter was never set
324 return Optional.empty();
325 }
326 }
328 /**
329 * Obtains a request parameter of the specified type.
330 * The specified type must have a single-argument constructor accepting a string to perform conversion.
331 * The constructor of the specified type may throw an exception on conversion failures.
332 *
333 * @param req the servlet request object
334 * @param clazz the class object of the expected type
335 * @param name the name of the parameter
336 * @param <T> the expected type
337 * @return the parameter value or an empty optional, if no parameter with the specified name was found
338 */
339 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
340 if (clazz.isArray()) {
341 final String[] paramValues = req.getParameterValues(name);
342 int len = paramValues == null ? 0 : paramValues.length;
343 final var array = (T) Array.newInstance(clazz.getComponentType(), len);
344 for (int i = 0; i < len; i++) {
345 try {
346 final Constructor<?> ctor = clazz.getComponentType().getConstructor(String.class);
347 Array.set(array, i, ctor.newInstance(paramValues[i]));
348 } catch (ReflectiveOperationException e) {
349 throw new RuntimeException(e);
350 }
351 }
352 return Optional.of(array);
353 } else {
354 return parseParameter(req.getParameter(name), clazz);
355 }
356 }
358 /**
359 * Tries to look up an entity with a key obtained from a request parameter.
360 *
361 * @param req the servlet request object
362 * @param clazz the class representing the type of the request parameter
363 * @param name the name of the request parameter
364 * @param find the find function (typically a DAO function)
365 * @param <T> the type of the request parameter
366 * @param <R> the type of the looked up entity
367 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
368 * @throws SQLException if the find function throws an exception
369 */
370 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
371 final var param = getParameter(req, clazz, name);
372 if (param.isPresent()) {
373 return Optional.ofNullable(find.apply(param.get()));
374 } else {
375 return Optional.empty();
376 }
377 }
379 private String sanitizeRequestPath(HttpServletRequest req) {
380 return Optional.ofNullable(req.getPathInfo()).orElse("/");
381 }
383 private Optional<Map.Entry<PathPattern, Method>> findMapping(HttpMethod method, HttpServletRequest req) {
384 return Optional.ofNullable(mappings.get(method)).flatMap(rm ->
385 rm.entrySet().stream().filter(
386 kv -> kv.getKey().matches(sanitizeRequestPath(req))
387 ).findAny()
388 );
389 }
391 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
392 throws ServletException, IOException {
393 switch (type) {
394 case NONE:
395 return;
396 case HTML:
397 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
398 return;
399 // TODO: implement remaining response types
400 default:
401 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
402 }
403 }
405 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
407 // choose the requested language as session language (if available) or fall back to english, otherwise
408 HttpSession session = req.getSession();
409 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
410 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
411 Optional<Locale> reqLocale = Optional.of(req.getLocale());
412 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
413 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
414 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
415 } else {
416 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
417 resp.setLocale(sessionLocale);
418 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
419 }
421 // set some internal request attributes
422 final String fullPath = Functions.fullPath(req);
423 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
424 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
425 req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
427 // if this is an error path, bypass the normal flow
428 if (fullPath.startsWith("/error/")) {
429 final var mapping = findMapping(method, req);
430 if (mapping.isPresent()) {
431 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
432 }
433 return;
434 }
436 // obtain a connection and create the data access objects
437 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
438 final var ds = db.getDataSource();
439 if (ds == null) {
440 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
441 return;
442 }
443 try (final var connection = ds.getConnection()) {
444 final var dao = createDataAccessObjects(connection);
445 try {
446 connection.setAutoCommit(false);
447 // call the handler, if available, or send an HTTP 404 error
448 final var mapping = findMapping(method, req);
449 if (mapping.isPresent()) {
450 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
451 } else {
452 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
453 }
454 connection.commit();
455 } catch (SQLException ex) {
456 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
457 LOG.debug("Details: ", ex);
458 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
459 connection.rollback();
460 }
461 } catch (SQLException ex) {
462 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
463 LOG.debug("Details: ", ex);
464 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
465 }
466 }
468 @Override
469 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
470 throws ServletException, IOException {
471 doProcess(HttpMethod.GET, req, resp);
472 }
474 @Override
475 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
476 throws ServletException, IOException {
477 doProcess(HttpMethod.POST, req, resp);
478 }
479 }