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