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