Fri, 22 May 2020 21:23:57 +0200
adds the ability to create and edit issues
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 content page.
232 * <p>
233 * It is sufficient to specify the name without any extension. The extension
234 * is added automatically if not specified.
235 *
236 * @param req the servlet request object
237 * @param pageName the name of the content page
238 * @see Constants#REQ_ATTR_CONTENT_PAGE
239 */
240 protected void setContentPage(HttpServletRequest req, String pageName) {
241 req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName));
242 }
244 /**
245 * Sets the breadcrumbs menu.
246 *
247 * @param req the servlet request object
248 * @param breadcrumbs the menu entries for the breadcrumbs menu
249 * @see Constants#REQ_ATTR_BREADCRUMBS
250 */
251 protected void setBreadcrumbs(HttpServletRequest req, List<MenuEntry> breadcrumbs) {
252 req.setAttribute(Constants.REQ_ATTR_BREADCRUMBS, breadcrumbs);
253 }
255 /**
256 * @param req the servlet request object
257 * @param location the location where to redirect
258 * @see Constants#REQ_ATTR_REDIRECT_LOCATION
259 */
260 protected void setRedirectLocation(HttpServletRequest req, String location) {
261 if (location.startsWith("./")) {
262 location = location.replaceFirst("\\./", Functions.baseHref(req));
263 }
264 req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location);
265 }
267 /**
268 * Specifies the name of an additional stylesheet used by the module.
269 * <p>
270 * Setting an additional stylesheet is optional, but quite common for HTML
271 * output.
272 * <p>
273 * It is sufficient to specify the name without any extension. The extension
274 * is added automatically if not specified.
275 *
276 * @param req the servlet request object
277 * @param stylesheet the name of the stylesheet
278 */
279 public void setStylesheet(HttpServletRequest req, String stylesheet) {
280 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
281 }
283 /**
284 * Obtains a request parameter of the specified type.
285 * The specified type must have a single-argument constructor accepting a string to perform conversion.
286 * The constructor of the specified type may throw an exception on conversion failures.
287 *
288 * @param req the servlet request object
289 * @param clazz the class object of the expected type
290 * @param name the name of the parameter
291 * @param <T> the expected type
292 * @return the parameter value or an empty optional, if no parameter with the specified name was found
293 */
294 protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) {
295 final String paramValue = req.getParameter(name);
296 if (paramValue == null) return Optional.empty();
297 if (clazz.equals(String.class)) return Optional.of((T) paramValue);
298 if (java.sql.Date.class.isAssignableFrom(clazz)) {
299 try {
300 return Optional.of((T)java.sql.Date.valueOf(paramValue));
301 } catch (IllegalArgumentException ex) {
302 return Optional.empty();
303 }
304 }
305 try {
306 final Constructor<T> ctor = clazz.getConstructor(String.class);
307 return Optional.of(ctor.newInstance(paramValue));
308 } catch (ReflectiveOperationException e) {
309 throw new RuntimeException(e);
310 }
312 }
314 /**
315 * Tries to look up an entity with a key obtained from a request parameter.
316 *
317 * @param req the servlet request object
318 * @param clazz the class representing the type of the request parameter
319 * @param name the name of the request parameter
320 * @param find the find function (typically a DAO function)
321 * @param <T> the type of the request parameter
322 * @param <R> the type of the looked up entity
323 * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing
324 * @throws SQLException if the find function throws an exception
325 */
326 protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException {
327 final var param = getParameter(req, clazz, name);
328 if (param.isPresent()) {
329 return Optional.ofNullable(find.apply(param.get()));
330 } else {
331 return Optional.empty();
332 }
333 }
335 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
336 throws IOException, ServletException {
338 final var mainMenu = new ArrayList<MenuEntry>(getModuleManager().getMainMenu());
339 for (var entry : mainMenu) {
340 if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) {
341 entry.setActive(true);
342 }
343 }
344 req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu);
345 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
346 }
348 private String sanitizeRequestPath(HttpServletRequest req) {
349 return Optional.ofNullable(req.getPathInfo()).orElse("/");
350 }
352 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
353 return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
354 }
356 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
357 throws ServletException, IOException {
358 switch (type) {
359 case NONE:
360 return;
361 case HTML:
362 forwardToFullView(req, resp);
363 return;
364 // TODO: implement remaining response types
365 default:
366 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
367 }
368 }
370 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
372 // choose the requested language as session language (if available) or fall back to english, otherwise
373 HttpSession session = req.getSession();
374 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
375 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
376 Optional<Locale> reqLocale = Optional.of(req.getLocale());
377 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
378 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
379 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
380 } else {
381 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
382 resp.setLocale(sessionLocale);
383 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
384 }
386 // set some internal request attributes
387 final String fullPath = Functions.fullPath(req);
388 req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req));
389 req.setAttribute(Constants.REQ_ATTR_PATH, fullPath);
390 Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
392 // if this is an error path, bypass the normal flow
393 if (fullPath.startsWith("/error/")) {
394 final var mapping = findMapping(method, req);
395 if (mapping.isPresent()) {
396 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp);
397 }
398 return;
399 }
401 // obtain a connection and create the data access objects
402 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
403 final var ds = db.getDataSource();
404 if (ds == null) {
405 resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details.");
406 return;
407 }
408 try (final var connection = ds.getConnection()) {
409 final var dao = createDataAccessObjects(connection);
410 try {
411 connection.setAutoCommit(false);
412 // call the handler, if available, or send an HTTP 404 error
413 final var mapping = findMapping(method, req);
414 if (mapping.isPresent()) {
415 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
416 } else {
417 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
418 }
419 connection.commit();
420 } catch (SQLException ex) {
421 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
422 LOG.debug("Details: ", ex);
423 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode());
424 connection.rollback();
425 }
426 } catch (SQLException ex) {
427 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
428 LOG.debug("Details: ", ex);
429 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode());
430 }
431 }
433 @Override
434 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
435 throws ServletException, IOException {
436 doProcess(HttpMethod.GET, req, resp);
437 }
439 @Override
440 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
441 throws ServletException, IOException {
442 doProcess(HttpMethod.POST, req, resp);
443 }
444 }