Fri, 22 May 2020 17:19:09 +0200
improves error message for InvocationTargetExceptions
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");
61 /**
62 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
63 */
64 private LightPITModule.ELProxy moduleInfo = null;
66 @FunctionalInterface
67 protected interface SQLFindFunction<K, T> {
68 T apply(K key) throws SQLException;
70 default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException {
71 Objects.requireNonNull(before);
72 return (v) -> this.apply(before.apply(v));
73 }
75 default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException {
76 Objects.requireNonNull(after);
77 return (t) -> after.apply(this.apply(t));
78 }
80 static <K> Function<K, K> identity() {
81 return (t) -> t;
82 }
83 }
85 /**
86 * Invocation mapping gathered from the {@link RequestMapping} annotations.
87 * <p>
88 * Paths in this map must always start with a leading slash, although
89 * the specification in the annotation must not start with a leading slash.
90 * <p>
91 * The reason for this is the different handling of empty paths in
92 * {@link HttpServletRequest#getPathInfo()}.
93 */
94 private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
96 /**
97 * Gives implementing modules access to the {@link ModuleManager}.
98 *
99 * @return the module manager
100 */
101 protected final ModuleManager getModuleManager() {
102 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
103 }
106 /**
107 * Creates a set of data access objects for the specified connection.
108 *
109 * @param connection the SQL connection
110 * @return a set of data access objects
111 */
112 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
113 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
114 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
115 return new PGDataAccessObjects(connection);
116 }
117 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
118 }
120 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
121 try {
122 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
123 final var paramTypes = method.getParameterTypes();
124 final var paramValues = new Object[paramTypes.length];
125 for (int i = 0; i < paramTypes.length; i++) {
126 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
127 paramValues[i] = req;
128 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
129 paramValues[i] = resp;
130 }
131 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
132 paramValues[i] = dao;
133 }
134 }
135 return (ResponseType) method.invoke(this, paramValues);
136 } catch (InvocationTargetException ex) {
137 LOG.error("invocation of method {}::{} failed: {}",
138 method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage());
139 LOG.debug("Details: ", ex.getTargetException());
140 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage());
141 return ResponseType.NONE;
142 } catch (ReflectiveOperationException | ClassCastException ex) {
143 LOG.error("invocation of method {}::{} failed: {}",
144 method.getDeclaringClass().getName(), method.getName(), ex.getMessage());
145 LOG.debug("Details: ", ex);
146 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
147 return ResponseType.NONE;
148 }
149 }
151 @Override
152 public void init() throws ServletException {
153 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
154 .map(LightPITModule.ELProxy::new).orElse(null);
156 if (moduleInfo != null) {
157 scanForRequestMappings();
158 }
160 LOG.trace("{} initialized", getServletName());
161 }
163 private void scanForRequestMappings() {
164 try {
165 Method[] methods = getClass().getDeclaredMethods();
166 for (Method method : methods) {
167 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
168 if (mapping.isPresent()) {
169 if (!Modifier.isPublic(method.getModifiers())) {
170 LOG.warn("{} is annotated with {} but is not public",
171 method.getName(), RequestMapping.class.getSimpleName()
172 );
173 continue;
174 }
175 if (Modifier.isAbstract(method.getModifiers())) {
176 LOG.warn("{} is annotated with {} but is abstract",
177 method.getName(), RequestMapping.class.getSimpleName()
178 );
179 continue;
180 }
181 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
182 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
183 method.getName(), RequestMapping.class.getSimpleName()
184 );
185 continue;
186 }
188 boolean paramsInjectible = true;
189 for (var param : method.getParameterTypes()) {
190 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
191 || HttpServletResponse.class.isAssignableFrom(param)
192 || DataAccessObjects.class.isAssignableFrom(param);
193 }
194 if (paramsInjectible) {
195 String requestPath = "/" + mapping.get().requestPath();
197 if (mappings
198 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
199 .putIfAbsent(requestPath, 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 requestPath,
209 getClass().getSimpleName(),
210 method.getName()
211 );
212 } else {
213 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
214 method.getName(), RequestMapping.class.getSimpleName()
215 );
216 }
217 }
218 }
219 } catch (SecurityException ex) {
220 LOG.error("Scan for request mappings on declared methods failed.", ex);
221 }
222 }
224 @Override
225 public void destroy() {
226 mappings.clear();
227 LOG.trace("{} destroyed", getServletName());
228 }
230 /**
231 * Sets the name of the dynamic fragment.
232 * <p>
233 * It is sufficient to specify the name without any extension. The extension
234 * is added automatically if not specified.
235 * <p>
236 * The fragment must be located in the dynamic fragments folder.
237 *
238 * @param req the servlet request object
239 * @param fragmentName the name of the fragment
240 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
241 * @see Constants#REQ_ATTR_FRAGMENT
242 */
243 protected void setDynamicFragment(HttpServletRequest req, String fragmentName) {
244 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
245 }
247 /**
248 * Sets the breadcrumbs menu.
249 *
250 * @param req the servlet request object
251 * @param breadcrumbs the menu entries for the breadcrumbs menu
252 * @see Constants#REQ_ATTR_BREADCRUMBS
253 */
254 protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
255 req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
256 }
258 /**
259 * @param req the servlet request object
260 * @param location the location where to redirect
261 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
262 */
263 protected void setRedirectLocation(HttpServletRequest req, String location) {
264 if (location.startsWith("./")) {
265 location = location.replaceFirst("\\./", Functions.baseHref(req));
266 }
267 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
268 }
270 /**
271 * Specifies the name of an additional stylesheet used by the module.
272 * <p>
273 * Setting an additional stylesheet is optional, but quite common for HTML
274 * output.
275 * <p>
276 * It is sufficient to specify the name without any extension. The extension
277 * is added automatically if not specified.
278 *
279 * @param req the servlet request object
280 * @param stylesheet the name of the stylesheet
281 */
282 public void setStylesheet(HttpServletRequest req, String stylesheet) {
283 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
284 }
286 /**
287 * Obtains a request parameter of the specified type.
288 * The specified type must have a single-argument constructor accepting a string to perform conversion.
289 * The constructor of the specified type may throw an exception on conversion failures.
290 *
291 * @param req the servlet request object
292 * @param clazz the class object of the expected type
293 * @param name the name of the parameter
294 * @param <T> the expected type
295 * @return the parameter value or an empty optional, if no parameter with the specified name was found
296 */
297 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
298 final String paramValue = req.getParameter(name);
299 if (paramValue == null) return Optional.empty();
300 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
301 try {
302 final Constructor<T> ctor = clazz.getConstructor(String.class);
303 return Optional.of(ctor.newInstance(paramValue));
304 } catch (ReflectiveOperationException e) {
305 throw new RuntimeException(e);
306 }
308 }
310 /**
311 * Tries to look up an entity with a key obtained from a request parameter.
312 *
313 * @param req the servlet request object
314 * @param clazz the class representing the type of the request parameter
315 * @param name the name of the request parameter
316 * @param find the find function (typically a DAO function)
317 * @param <T> the type of the request parameter
318 * @param <R> the type of the looked up entity
319 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
320 * @throws SQLException if the find function throws an exception
321 */
322 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
323 final var param = getParameter(req, clazz, name);
324 if (param.isPresent()) {
325 return Optional.ofNullable(find.apply(param.get()));
326 } else {
327 return Optional.empty();
328 }
329 }
331 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
332 throws IOException, ServletException {
334 final var mainMenu = new ArrayList<MenuEntry>(getModuleManager().getMainMenu());
335 for (var entry : mainMenu) {
336 if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
337 entry.setActive(true);
338 }
339 }
340 req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
341 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
342 }
344 private String sanitizeRequestPath(HttpServletRequest req) {
345 return Optional.ofNullable(req.getPathInfo()).orElse("/");
346 }
348 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
349 return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
350 }
352 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
353 throws ServletException, IOException {
354 switch (type) {
355 case NONE:
356 return;
357 case HTML:
358 forwardToFullView(req, resp);
359 return;
360 // TODO: implement remaining response types
361 default:
362 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
363 }
364 }
366 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
368 // choose the requested language as session language (if available) or fall back to english, otherwise
369 HttpSession session = req.getSession();
370 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
371 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
372 Optional<Locale> reqLocale = Optional.of(req.getLocale());
373 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
374 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
375 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
376 } else {
377 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
378 resp.setLocale(sessionLocale);
379 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
380 }
382 // set some internal request attributes
383 final String fullPath = Functions.fullPath(req);
384 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
385 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
386 Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
388 // if this is an error path, bypass the normal flow
389 if (fullPath.startsWith("/error/")) {
390 final var mapping = findMapping(method, req);
391 if (mapping.isPresent()) {
392 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
393 }
394 return;
395 }
397 // obtain a connection and create the data access objects
398 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
399 final var ds = db.getDataSource();
400 if (ds == null) {
401 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
402 return;
403 }
404 try (final var connection = ds.getConnection()) {
405 final var dao = createDataAccessObjects(connection);
406 try {
407 connection.setAutoCommit(false);
408 // call the handler, if available, or send an HTTP 404 error
409 final var mapping = findMapping(method, req);
410 if (mapping.isPresent()) {
411 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
412 } else {
413 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
414 }
415 connection.commit();
416 } catch (SQLException ex) {
417 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
418 LOG.debug("Details: ", ex);
419 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
420 connection.rollback();
421 }
422 } catch (SQLException ex) {
423 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
424 LOG.debug("Details: ", ex);
425 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
426 }
427 }
429 @Override
430 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
431 throws ServletException, IOException {
432 doProcess(HttpMethod.GET, req, resp);
433 }
435 @Override
436 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
437 throws ServletException, IOException {
438 doProcess(HttpMethod.POST, req, resp);
439 }
440 }