Thu, 15 Oct 2020 18:36:05 +0200
adds the possibility to specify path parameters to RequestMapping
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 if (mappings
198 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
199 .putIfAbsent(pathPattern, method) != null) {
200 LOG.warn("{} {} has multiple mappings",
201 mapping.get().method(),
202 mapping.get().requestPath()
203 );
204 }
206 LOG.debug("{} {} maps to {}::{}",
207 mapping.get().method(),
208 mapping.get().requestPath(),
209 getClass().getSimpleName(),
210 method.getName()
211 );
212 } catch (IllegalArgumentException ex) {
213 LOG.warn("Request mapping for {} failed: path pattern '{}' is syntactically invalid",
214 method.getName(), mapping.get().requestPath()
215 );
216 }
217 } else {
218 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest, HttpServletResponse, PathParameters, and DataAccessObjects are allowed",
219 method.getName(), RequestMapping.class.getSimpleName()
220 );
221 }
222 }
223 }
224 } catch (SecurityException ex) {
225 LOG.error("Scan for request mappings on declared methods failed.", ex);
226 }
227 }
229 @Override
230 public void destroy() {
231 mappings.clear();
232 LOG.trace("{} destroyed", getServletName());
233 }
235 /**
236 * Sets the name of the content page.
237 * <p>
238 * It is sufficient to specify the name without any extension. The extension
239 * is added automatically if not specified.
240 *
241 * @param req the servlet request object
242 * @param pageName the name of the content page
243 * @see Constants#REQ_ATTR_CONTENT_PAGE
244 */
245 protected void setContentPage(HttpServletRequest req, String pageName) {
246 req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
247 }
249 /**
250 * Sets the navigation menu.
251 *
252 * @param req the servlet request object
253 * @param jspName the name of the menu's jsp file
254 * @see Constants#REQ_ATTR_NAVIGATION
255 */
256 protected void setNavigationMenu(HttpServletRequest req, String jspName) {
257 req.setAttribute(Constants.REQ_ATTR_NAVIGATION, Functions.jspPath(jspName));
258 }
260 /**
261 * @param req the servlet request object
262 * @param location the location where to redirect
263 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
264 */
265 protected void setRedirectLocation(HttpServletRequest req, String location) {
266 if (location.startsWith("./")) {
267 location = location.replaceFirst("\\./", Functions.baseHref(req));
268 }
269 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
270 }
272 /**
273 * Specifies the name of an additional stylesheet used by the module.
274 * <p>
275 * Setting an additional stylesheet is optional, but quite common for HTML
276 * output.
277 * <p>
278 * It is sufficient to specify the name without any extension. The extension
279 * is added automatically if not specified.
280 *
281 * @param req the servlet request object
282 * @param stylesheet the name of the stylesheet
283 */
284 public void setStylesheet(HttpServletRequest req, String stylesheet) {
285 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
286 }
288 /**
289 * Sets the view model object.
290 * The type must match the expected type in the JSP file.
291 *
292 * @param req the servlet request object
293 * @param viewModel the view model object
294 */
295 public void setViewModel(HttpServletRequest req, Object viewModel) {
296 req.setAttribute(Constants.REQ_ATTR_VIEWMODEL, viewModel);
297 }
299 /**
300 * Obtains a request parameter of the specified type.
301 * The specified type must have a single-argument constructor accepting a string to perform conversion.
302 * The constructor of the specified type may throw an exception on conversion failures.
303 *
304 * @param req the servlet request object
305 * @param clazz the class object of the expected type
306 * @param name the name of the parameter
307 * @param <T> the expected type
308 * @return the parameter value or an empty optional, if no parameter with the specified name was found
309 */
310 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
311 if (clazz.isArray()) {
312 final String[] paramValues = req.getParameterValues(name);
313 int len = paramValues == null ? 0 : paramValues.length;
314 final var array = (T) Array.newInstance(clazz.getComponentType(), len);
315 for (int i = 0; i < len; i++) {
316 try {
317 final Constructor<?> ctor = clazz.getComponentType().getConstructor(String.class);
318 Array.set(array, i, ctor.newInstance(paramValues[i]));
319 } catch (ReflectiveOperationException e) {
320 throw new RuntimeException(e);
321 }
322 }
323 return Optional.of(array);
324 } else {
325 final String paramValue = req.getParameter(name);
326 if (paramValue == null) return Optional.empty();
327 if (clazz.equals(Boolean.class)) {
328 if (paramValue.toLowerCase().equals("false") || paramValue.equals("0")) {
329 return Optional.of((T) Boolean.FALSE);
330 } else {
331 return Optional.of((T) Boolean.TRUE);
332 }
333 }
334 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
335 if (java.sql.Date.class.isAssignableFrom(clazz)) {
336 try {
337 return Optional.of((T) java.sql.Date.valueOf(paramValue));
338 } catch (IllegalArgumentException ex) {
339 return Optional.empty();
340 }
341 }
342 try {
343 final Constructor<T> ctor = clazz.getConstructor(String.class);
344 return Optional.of(ctor.newInstance(paramValue));
345 } catch (ReflectiveOperationException e) {
346 // does not type check and is not convertible - treat as if the parameter was never set
347 return Optional.empty();
348 }
349 }
350 }
352 /**
353 * Tries to look up an entity with a key obtained from a request parameter.
354 *
355 * @param req the servlet request object
356 * @param clazz the class representing the type of the request parameter
357 * @param name the name of the request parameter
358 * @param find the find function (typically a DAO function)
359 * @param <T> the type of the request parameter
360 * @param <R> the type of the looked up entity
361 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
362 * @throws SQLException if the find function throws an exception
363 */
364 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
365 final var param = getParameter(req, clazz, name);
366 if (param.isPresent()) {
367 return Optional.ofNullable(find.apply(param.get()));
368 } else {
369 return Optional.empty();
370 }
371 }
373 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
374 throws IOException, ServletException {
376 final String lightpitBundle = "localization.lightpit";
377 final var mainMenu = List.of(
378 new MenuEntry(new ResourceKey(lightpitBundle, "menu.projects"), "projects/"),
379 new MenuEntry(new ResourceKey(lightpitBundle, "menu.users"), "teams/"),
380 new MenuEntry(new ResourceKey(lightpitBundle, "menu.languages"), "language/")
381 );
382 for (var entry : mainMenu) {
383 if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
384 entry.setActive(true);
385 }
386 }
387 req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
388 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
389 }
391 private String sanitizeRequestPath(HttpServletRequest req) {
392 return Optional.ofNullable(req.getPathInfo()).orElse("/");
393 }
395 private Optional<Map.Entry<PathPattern, Method>> findMapping(HttpMethod method, HttpServletRequest req) {
396 return Optional.ofNullable(mappings.get(method)).flatMap(rm ->
397 rm.entrySet().stream().filter(
398 kv -> kv.getKey().matches(sanitizeRequestPath(req))
399 ).findAny()
400 );
401 }
403 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
404 throws ServletException, IOException {
405 switch (type) {
406 case NONE:
407 return;
408 case HTML:
409 forwardToFullView(req, resp);
410 return;
411 // TODO: implement remaining response types
412 default:
413 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
414 }
415 }
417 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
419 // choose the requested language as session language (if available) or fall back to english, otherwise
420 HttpSession session = req.getSession();
421 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
422 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
423 Optional<Locale> reqLocale = Optional.of(req.getLocale());
424 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
425 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
426 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
427 } else {
428 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
429 resp.setLocale(sessionLocale);
430 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
431 }
433 // set some internal request attributes
434 final String fullPath = Functions.fullPath(req);
435 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
436 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
437 req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName());
439 // if this is an error path, bypass the normal flow
440 if (fullPath.startsWith("/error/")) {
441 final var mapping = findMapping(method, req);
442 if (mapping.isPresent()) {
443 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
444 }
445 return;
446 }
448 // obtain a connection and create the data access objects
449 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
450 final var ds = db.getDataSource();
451 if (ds == null) {
452 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
453 return;
454 }
455 try (final var connection = ds.getConnection()) {
456 final var dao = createDataAccessObjects(connection);
457 try {
458 connection.setAutoCommit(false);
459 // call the handler, if available, or send an HTTP 404 error
460 final var mapping = findMapping(method, req);
461 if (mapping.isPresent()) {
462 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
463 } else {
464 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
465 }
466 connection.commit();
467 } catch (SQLException ex) {
468 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
469 LOG.debug("Details: ", ex);
470 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
471 connection.rollback();
472 }
473 } catch (SQLException ex) {
474 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
475 LOG.debug("Details: ", ex);
476 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
477 }
478 }
480 @Override
481 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
482 throws ServletException, IOException {
483 doProcess(HttpMethod.GET, req, resp);
484 }
486 @Override
487 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
488 throws ServletException, IOException {
489 doProcess(HttpMethod.POST, req, resp);
490 }
491 }