Sat, 09 May 2020 17:01:29 +0200
cleanup and simplification of database access layer
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 org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
34 import javax.servlet.ServletException;
35 import javax.servlet.http.HttpServlet;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38 import javax.servlet.http.HttpSession;
39 import java.io.IOException;
40 import java.lang.reflect.Method;
41 import java.lang.reflect.Modifier;
42 import java.util.*;
44 /**
45 * A special implementation of a HTTPServlet which is focused on implementing
46 * the necessary functionality for {@link LightPITModule}s.
47 */
48 public abstract class AbstractLightPITServlet extends HttpServlet {
50 private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class);
52 private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full");
54 /**
55 * Store a reference to the annotation for quicker access.
56 */
57 private LightPITModule moduleInfo = null;
59 /**
60 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
61 */
62 private LightPITModule.ELProxy moduleInfoELProxy = null;
65 @FunctionalInterface
66 private interface HandlerMethod {
67 ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException;
68 }
70 /**
71 * Invocation mapping gathered from the {@link RequestMapping} annotations.
72 * <p>
73 * Paths in this map must always start with a leading slash, although
74 * the specification in the annotation must not start with a leading slash.
75 * <p>
76 * The reason for this is the different handling of empty paths in
77 * {@link HttpServletRequest#getPathInfo()}.
78 */
79 private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>();
81 /**
82 * Gives implementing modules access to the {@link ModuleManager}.
83 *
84 * @return the module manager
85 */
86 protected final ModuleManager getModuleManager() {
87 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
88 }
90 /**
91 * Returns the annotated module information.
92 *
93 * @return the module annotation
94 */
95 public final LightPITModule getModuleInfo() {
96 return moduleInfo;
97 }
99 /**
100 * Gives implementing modules access to the {@link DatabaseFacade}.
101 *
102 * @return the database facade
103 */
104 protected final DatabaseFacade getDatabaseFacade() {
105 return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
106 }
108 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) throws IOException {
109 try {
110 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
111 return (ResponseType) method.invoke(this, req, resp);
112 } catch (ReflectiveOperationException | ClassCastException ex) {
113 LOG.error(String.format("invocation of method %s failed", method.getName()), ex);
114 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
115 return ResponseType.NONE;
116 }
117 }
119 @Override
120 public void init() throws ServletException {
121 moduleInfo = this.getClass().getAnnotation(LightPITModule.class);
122 moduleInfoELProxy = moduleInfo == null ? null : LightPITModule.ELProxy.convert(moduleInfo);
124 if (moduleInfo != null) {
125 scanForRequestMappings();
126 }
128 LOG.trace("{} initialized", getServletName());
129 }
131 private void scanForRequestMappings() {
132 try {
133 Method[] methods = getClass().getDeclaredMethods();
134 for (Method method : methods) {
135 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
136 if (mapping.isPresent()) {
137 if (!Modifier.isPublic(method.getModifiers())) {
138 LOG.warn("{} is annotated with {} but is not public",
139 method.getName(), RequestMapping.class.getSimpleName()
140 );
141 continue;
142 }
143 if (Modifier.isAbstract(method.getModifiers())) {
144 LOG.warn("{} is annotated with {} but is abstract",
145 method.getName(), RequestMapping.class.getSimpleName()
146 );
147 continue;
148 }
149 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
150 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
151 method.getName(), RequestMapping.class.getSimpleName()
152 );
153 continue;
154 }
156 Class<?>[] params = method.getParameterTypes();
157 if (params.length == 2
158 && HttpServletRequest.class.isAssignableFrom(params[0])
159 && HttpServletResponse.class.isAssignableFrom(params[1])) {
161 final String requestPath = "/" + mapping.get().requestPath();
163 if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()).
164 putIfAbsent(requestPath,
165 (req, resp) -> invokeMapping(method, req, resp)) != null) {
166 LOG.warn("{} {} has multiple mappings",
167 mapping.get().method(),
168 mapping.get().requestPath()
169 );
170 }
172 LOG.debug("{} {} maps to {}::{}",
173 mapping.get().method(),
174 requestPath,
175 getClass().getSimpleName(),
176 method.getName()
177 );
178 } else {
179 LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required",
180 method.getName(), RequestMapping.class.getSimpleName()
181 );
182 }
183 }
184 }
185 } catch (SecurityException ex) {
186 LOG.error("Scan for request mappings on declared methods failed.", ex);
187 }
188 }
190 @Override
191 public void destroy() {
192 mappings.clear();
193 LOG.trace("{} destroyed", getServletName());
194 }
196 /**
197 * Sets the name of the dynamic fragment.
198 * <p>
199 * It is sufficient to specify the name without any extension. The extension
200 * is added automatically if not specified.
201 * <p>
202 * The fragment must be located in the dynamic fragments folder.
203 *
204 * @param req the servlet request object
205 * @param fragmentName the name of the fragment
206 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
207 */
208 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
209 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
210 }
212 /**
213 * Specifies the name of an additional stylesheet used by the module.
214 * <p>
215 * Setting an additional stylesheet is optional, but quite common for HTML
216 * output.
217 * <p>
218 * It is sufficient to specify the name without any extension. The extension
219 * is added automatically if not specified.
220 *
221 * @param req the servlet request object
222 * @param stylesheet the name of the stylesheet
223 */
224 public void setStylesheet(HttpServletRequest req, String stylesheet) {
225 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
226 }
228 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
229 throws IOException, ServletException {
231 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu(getDatabaseFacade()));
232 req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp);
233 }
235 private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) {
236 return Optional.ofNullable(mappings.get(method)).map(
237 (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/"))
238 );
239 }
241 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
242 throws ServletException, IOException {
243 switch (type) {
244 case NONE:
245 return;
246 case HTML_FULL:
247 forwardToFullView(req, resp);
248 return;
249 // TODO: implement remaining response types
250 default:
251 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
252 }
253 }
255 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp)
256 throws ServletException, IOException {
258 // Synchronize module information with database
259 getModuleManager().syncWithDatabase(getDatabaseFacade());
261 // choose the requested language as session language (if available) or fall back to english, otherwise
262 HttpSession session = req.getSession();
263 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
264 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
265 Optional<Locale> reqLocale = Optional.of(req.getLocale());
266 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
267 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
268 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
269 } else {
270 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
271 resp.setLocale(sessionLocale);
272 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
273 }
275 // set some internal request attributes
276 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
277 req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName());
278 Optional.ofNullable(moduleInfoELProxy).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
281 // call the handler, if available, or send an HTTP 404 error
282 Optional<HandlerMethod> mapping = findMapping(method, req);
283 if (mapping.isPresent()) {
284 forwardAsSpecified(mapping.get().apply(req, resp), req, resp);
285 } else {
286 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
287 }
288 }
290 @Override
291 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
292 throws ServletException, IOException {
293 doProcess(HttpMethod.GET, req, resp);
294 }
296 @Override
297 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
298 throws ServletException, IOException {
299 doProcess(HttpMethod.POST, req, resp);
300 }
301 }