Wed, 13 May 2020 21:10:23 +0200
simplifies menu generation, adds submenus and removes VersionsModule (versions will be part of the ProjectsModule)
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.Method;
43 import java.lang.reflect.Modifier;
44 import java.sql.Connection;
45 import java.sql.SQLException;
46 import java.util.*;
48 /**
49 * A special implementation of a HTTPServlet which is focused on implementing
50 * the necessary functionality for {@link LightPITModule}s.
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");
58 /**
59 * The EL proxy is necessary, because the EL resolver cannot handle annotation properties.
60 */
61 private LightPITModule.ELProxy moduleInfo = null;
63 /**
64 * Invocation mapping gathered from the {@link RequestMapping} annotations.
65 * <p>
66 * Paths in this map must always start with a leading slash, although
67 * the specification in the annotation must not start with a leading slash.
68 * <p>
69 * The reason for this is the different handling of empty paths in
70 * {@link HttpServletRequest#getPathInfo()}.
71 */
72 private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>();
74 private final List<MenuEntry> subMenu = new ArrayList<>();
76 /**
77 * Gives implementing modules access to the {@link ModuleManager}.
78 *
79 * @return the module manager
80 */
81 protected final ModuleManager getModuleManager() {
82 return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME);
83 }
86 /**
87 * Creates a set of data access objects for the specified connection.
88 *
89 * @param connection the SQL connection
90 * @return a set of data access objects
91 */
92 private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException {
93 final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
94 if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) {
95 return new PGDataAccessObjects(connection);
96 }
97 throw new AssertionError("Non-exhaustive if-else - this is a bug.");
98 }
100 private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException {
101 try {
102 LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName());
103 final var paramTypes = method.getParameterTypes();
104 final var paramValues = new Object[paramTypes.length];
105 for (int i = 0; i < paramTypes.length; i++) {
106 if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
107 paramValues[i] = req;
108 } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) {
109 paramValues[i] = resp;
110 }
111 if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) {
112 paramValues[i] = dao;
113 }
114 }
115 return (ResponseType) method.invoke(this, paramValues);
116 } catch (ReflectiveOperationException | ClassCastException ex) {
117 LOG.error("invocation of method {} failed: {}", method.getName(), ex.getMessage());
118 LOG.debug("Details: ", ex);
119 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
120 return ResponseType.NONE;
121 }
122 }
124 @Override
125 public void init() throws ServletException {
126 moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class))
127 .map(LightPITModule.ELProxy::new).orElse(null);
129 if (moduleInfo != null) {
130 scanForRequestMappings();
131 }
133 LOG.trace("{} initialized", getServletName());
134 }
136 private void scanForRequestMappings() {
137 try {
138 Method[] methods = getClass().getDeclaredMethods();
139 for (Method method : methods) {
140 Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class));
141 if (mapping.isPresent()) {
142 if (!Modifier.isPublic(method.getModifiers())) {
143 LOG.warn("{} is annotated with {} but is not public",
144 method.getName(), RequestMapping.class.getSimpleName()
145 );
146 continue;
147 }
148 if (Modifier.isAbstract(method.getModifiers())) {
149 LOG.warn("{} is annotated with {} but is abstract",
150 method.getName(), RequestMapping.class.getSimpleName()
151 );
152 continue;
153 }
154 if (!ResponseType.class.isAssignableFrom(method.getReturnType())) {
155 LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required",
156 method.getName(), RequestMapping.class.getSimpleName()
157 );
158 continue;
159 }
161 boolean paramsInjectible = true;
162 for (var param : method.getParameterTypes()) {
163 paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param)
164 || HttpServletResponse.class.isAssignableFrom(param)
165 || DataAccessObjects.class.isAssignableFrom(param);
166 }
167 if (paramsInjectible) {
168 final String requestPath = "/" + mapping.get().requestPath();
170 if (mappings
171 .computeIfAbsent(mapping.get().method(), k -> new HashMap<>())
172 .putIfAbsent(requestPath, method) != null) {
173 LOG.warn("{} {} has multiple mappings",
174 mapping.get().method(),
175 mapping.get().requestPath()
176 );
177 }
179 final var menuKey = mapping.get().menuKey();
180 if (!menuKey.isBlank()) {
181 subMenu.add(new MenuEntry(
182 new ResourceKey(moduleInfo.getBundleBaseName(), menuKey),
183 moduleInfo.getModulePath() + requestPath,
184 mapping.get().menuSequence()));
185 }
187 LOG.debug("{} {} maps to {}::{}",
188 mapping.get().method(),
189 requestPath,
190 getClass().getSimpleName(),
191 method.getName()
192 );
193 } else {
194 LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed",
195 method.getName(), RequestMapping.class.getSimpleName()
196 );
197 }
198 }
199 }
200 } catch (SecurityException ex) {
201 LOG.error("Scan for request mappings on declared methods failed.", ex);
202 }
203 }
205 @Override
206 public void destroy() {
207 mappings.clear();
208 LOG.trace("{} destroyed", getServletName());
209 }
211 /**
212 * Sets the name of the dynamic fragment.
213 * <p>
214 * It is sufficient to specify the name without any extension. The extension
215 * is added automatically if not specified.
216 * <p>
217 * The fragment must be located in the dynamic fragments folder.
218 *
219 * @param req the servlet request object
220 * @param fragmentName the name of the fragment
221 * @see Constants#DYN_FRAGMENT_PATH_PREFIX
222 */
223 public void setDynamicFragment(HttpServletRequest req, String fragmentName) {
224 req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName));
225 }
227 /**
228 * Specifies the name of an additional stylesheet used by the module.
229 * <p>
230 * Setting an additional stylesheet is optional, but quite common for HTML
231 * output.
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 stylesheet the name of the stylesheet
238 */
239 public void setStylesheet(HttpServletRequest req, String stylesheet) {
240 req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css"));
241 }
243 private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp)
244 throws IOException, ServletException {
246 req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu());
247 req.setAttribute(Constants.REQ_ATTR_SUB_MENU, subMenu);
248 req.getRequestDispatcher(SITE_JSP).forward(req, resp);
249 }
251 private String sanitizeRequestPath(HttpServletRequest req) {
252 return Optional.ofNullable(req.getPathInfo()).orElse("/");
253 }
255 private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) {
256 return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req)));
257 }
259 private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp)
260 throws ServletException, IOException {
261 switch (type) {
262 case NONE:
263 return;
264 case HTML:
265 forwardToFullView(req, resp);
266 return;
267 // TODO: implement remaining response types
268 default:
269 throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!");
270 }
271 }
273 private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
275 // choose the requested language as session language (if available) or fall back to english, otherwise
276 HttpSession session = req.getSession();
277 if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
278 Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList);
279 Optional<Locale> reqLocale = Optional.of(req.getLocale());
280 Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH);
281 session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale);
282 LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage());
283 } else {
284 Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE);
285 resp.setLocale(sessionLocale);
286 LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale);
287 }
289 // set some internal request attributes
290 req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req));
291 Optional.ofNullable(moduleInfo).ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy));
293 // obtain a connection and create the data access objects
294 final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME);
295 try (final var connection = db.getDataSource().getConnection()) {
296 final var dao = createDataAccessObjects(connection);
297 try {
298 connection.setAutoCommit(false);
299 // call the handler, if available, or send an HTTP 404 error
300 final var mapping = findMapping(method, req);
301 if (mapping.isPresent()) {
302 forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp);
303 } else {
304 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
305 }
306 connection.commit();
307 } catch (SQLException ex) {
308 LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage());
309 LOG.debug("Details: ", ex);
310 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code:" + ex.getErrorCode());
311 connection.rollback();
312 }
313 } catch (SQLException ex) {
314 LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage());
315 LOG.debug("Details: ", ex);
316 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code:" + ex.getErrorCode());
317 }
318 }
320 @Override
321 protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
322 throws ServletException, IOException {
323 doProcess(HttpMethod.GET, req, resp);
324 }
326 @Override
327 protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
328 throws ServletException, IOException {
329 doProcess(HttpMethod.POST, req, resp);
330 }
331 }