Sun, 01 Apr 2018 18:25:31 +0200
minor changes to logging output
universe@7 | 1 | /* |
universe@7 | 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. |
universe@7 | 3 | * |
universe@7 | 4 | * Copyright 2017 Mike Becker. All rights reserved. |
universe@7 | 5 | * |
universe@7 | 6 | * Redistribution and use in source and binary forms, with or without |
universe@7 | 7 | * modification, are permitted provided that the following conditions are met: |
universe@7 | 8 | * |
universe@7 | 9 | * 1. Redistributions of source code must retain the above copyright |
universe@7 | 10 | * notice, this list of conditions and the following disclaimer. |
universe@7 | 11 | * |
universe@7 | 12 | * 2. Redistributions in binary form must reproduce the above copyright |
universe@7 | 13 | * notice, this list of conditions and the following disclaimer in the |
universe@7 | 14 | * documentation and/or other materials provided with the distribution. |
universe@7 | 15 | * |
universe@7 | 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
universe@7 | 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
universe@7 | 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
universe@7 | 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
universe@7 | 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
universe@7 | 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
universe@7 | 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
universe@7 | 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
universe@7 | 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
universe@7 | 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
universe@7 | 26 | * POSSIBILITY OF SUCH DAMAGE. |
universe@7 | 27 | * |
universe@7 | 28 | */ |
universe@7 | 29 | package de.uapcore.lightpit; |
universe@7 | 30 | |
universe@7 | 31 | import java.io.IOException; |
universe@11 | 32 | import java.lang.reflect.Method; |
universe@11 | 33 | import java.lang.reflect.Modifier; |
universe@13 | 34 | import java.util.Arrays; |
universe@11 | 35 | import java.util.HashMap; |
universe@13 | 36 | import java.util.List; |
universe@13 | 37 | import java.util.Locale; |
universe@11 | 38 | import java.util.Map; |
universe@11 | 39 | import java.util.Optional; |
universe@7 | 40 | import javax.servlet.ServletException; |
universe@7 | 41 | import javax.servlet.http.HttpServlet; |
universe@7 | 42 | import javax.servlet.http.HttpServletRequest; |
universe@7 | 43 | import javax.servlet.http.HttpServletResponse; |
universe@13 | 44 | import javax.servlet.http.HttpSession; |
universe@10 | 45 | import org.slf4j.Logger; |
universe@10 | 46 | import org.slf4j.LoggerFactory; |
universe@7 | 47 | |
universe@7 | 48 | /** |
universe@7 | 49 | * A special implementation of a HTTPServlet which is focused on implementing |
universe@7 | 50 | * the necessary functionality for {@link LightPITModule}s. |
universe@7 | 51 | */ |
universe@9 | 52 | public abstract class AbstractLightPITServlet extends HttpServlet { |
universe@7 | 53 | |
universe@10 | 54 | private static final Logger LOG = LoggerFactory.getLogger(AbstractLightPITServlet.class); |
universe@11 | 55 | |
universe@13 | 56 | private static final String HTML_FULL_DISPATCHER = Functions.jspPath("html_full"); |
universe@13 | 57 | |
universe@11 | 58 | /** |
universe@11 | 59 | * Store a reference to the annotation for quicker access. |
universe@11 | 60 | */ |
universe@11 | 61 | private Optional<LightPITModule> moduleInfo = Optional.empty(); |
universe@10 | 62 | |
universe@11 | 63 | /** |
universe@11 | 64 | * The EL proxy is necessary, because the EL resolver cannot handle annotation properties. |
universe@11 | 65 | */ |
universe@11 | 66 | private Optional<LightPITModule.ELProxy> moduleInfoELProxy = Optional.empty(); |
universe@10 | 67 | |
universe@12 | 68 | |
universe@12 | 69 | @FunctionalInterface |
universe@12 | 70 | private static interface HandlerMethod { |
universe@12 | 71 | ResponseType apply(HttpServletRequest t, HttpServletResponse u) throws IOException, ServletException; |
universe@12 | 72 | } |
universe@12 | 73 | |
universe@10 | 74 | /** |
universe@11 | 75 | * Invocation mapping gathered from the {@link RequestMapping} annotations. |
universe@18 | 76 | * |
universe@18 | 77 | * Paths in this map must always start with a leading slash, although |
universe@18 | 78 | * the specification in the annotation must not start with a leading slash. |
universe@18 | 79 | * |
universe@18 | 80 | * The reason for this is the different handling of empty paths in |
universe@18 | 81 | * {@link HttpServletRequest#getPathInfo()}. |
universe@11 | 82 | */ |
universe@12 | 83 | private final Map<HttpMethod, Map<String, HandlerMethod>> mappings = new HashMap<>(); |
universe@11 | 84 | |
universe@11 | 85 | /** |
universe@10 | 86 | * Gives implementing modules access to the {@link ModuleManager}. |
universe@10 | 87 | * @return the module manager |
universe@10 | 88 | */ |
universe@10 | 89 | protected final ModuleManager getModuleManager() { |
universe@10 | 90 | return (ModuleManager) getServletContext().getAttribute(ModuleManager.SC_ATTR_NAME); |
universe@10 | 91 | } |
universe@10 | 92 | |
universe@17 | 93 | /** |
universe@17 | 94 | * Gives implementing modules access to the {@link DatabaseFacade}. |
universe@17 | 95 | * @return the database facade |
universe@17 | 96 | */ |
universe@17 | 97 | protected final DatabaseFacade getDatabaseFacade() { |
universe@17 | 98 | return (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME); |
universe@17 | 99 | } |
universe@17 | 100 | |
universe@12 | 101 | private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 102 | throws IOException, ServletException { |
universe@11 | 103 | try { |
universe@14 | 104 | LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName()); |
universe@12 | 105 | return (ResponseType) method.invoke(this, req, resp); |
universe@12 | 106 | } catch (ReflectiveOperationException | ClassCastException ex) { |
universe@11 | 107 | LOG.error(String.format("invocation of method %s failed", method.getName()), ex); |
universe@12 | 108 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
universe@12 | 109 | return ResponseType.NONE; |
universe@11 | 110 | } |
universe@11 | 111 | } |
universe@11 | 112 | |
universe@11 | 113 | @Override |
universe@11 | 114 | public void init() throws ServletException { |
universe@11 | 115 | moduleInfo = Optional.ofNullable(this.getClass().getAnnotation(LightPITModule.class)); |
universe@11 | 116 | moduleInfoELProxy = moduleInfo.map(LightPITModule.ELProxy::convert); |
universe@11 | 117 | |
universe@11 | 118 | if (moduleInfo.isPresent()) { |
universe@12 | 119 | scanForRequestMappings(); |
universe@12 | 120 | } |
universe@12 | 121 | |
universe@12 | 122 | LOG.trace("{} initialized", getServletName()); |
universe@12 | 123 | } |
universe@12 | 124 | |
universe@12 | 125 | private void scanForRequestMappings() { |
universe@12 | 126 | try { |
universe@11 | 127 | Method[] methods = getClass().getDeclaredMethods(); |
universe@11 | 128 | for (Method method : methods) { |
universe@11 | 129 | Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class)); |
universe@11 | 130 | if (mapping.isPresent()) { |
universe@11 | 131 | if (!Modifier.isPublic(method.getModifiers())) { |
universe@11 | 132 | LOG.warn("{} is annotated with {} but is not public", |
universe@11 | 133 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 134 | ); |
universe@11 | 135 | continue; |
universe@11 | 136 | } |
universe@11 | 137 | if (Modifier.isAbstract(method.getModifiers())) { |
universe@11 | 138 | LOG.warn("{} is annotated with {} but is abstract", |
universe@11 | 139 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 140 | ); |
universe@11 | 141 | continue; |
universe@11 | 142 | } |
universe@12 | 143 | if (!ResponseType.class.isAssignableFrom(method.getReturnType())) { |
universe@12 | 144 | LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required", |
universe@12 | 145 | method.getName(), RequestMapping.class.getSimpleName() |
universe@12 | 146 | ); |
universe@12 | 147 | continue; |
universe@12 | 148 | } |
universe@12 | 149 | |
universe@11 | 150 | Class<?>[] params = method.getParameterTypes(); |
universe@11 | 151 | if (params.length == 2 |
universe@11 | 152 | && HttpServletRequest.class.isAssignableFrom(params[0]) |
universe@11 | 153 | && HttpServletResponse.class.isAssignableFrom(params[1])) { |
universe@18 | 154 | |
universe@18 | 155 | final String requestPath = "/"+mapping.get().requestPath(); |
universe@12 | 156 | |
universe@11 | 157 | if (mappings.computeIfAbsent(mapping.get().method(), k -> new HashMap<>()). |
universe@18 | 158 | putIfAbsent(requestPath, |
universe@11 | 159 | (req, resp) -> invokeMapping(method, req, resp)) != null) { |
universe@11 | 160 | LOG.warn("{} {} has multiple mappings", |
universe@11 | 161 | mapping.get().method(), |
universe@11 | 162 | mapping.get().requestPath() |
universe@11 | 163 | ); |
universe@11 | 164 | } |
universe@12 | 165 | |
universe@22 | 166 | LOG.debug("{} {} maps to {}::{}", |
universe@11 | 167 | mapping.get().method(), |
universe@18 | 168 | requestPath, |
universe@22 | 169 | getClass().getSimpleName(), |
universe@11 | 170 | method.getName() |
universe@11 | 171 | ); |
universe@11 | 172 | } else { |
universe@12 | 173 | LOG.warn("{} is annotated with {} but has the wrong parameters - (HttpServletRequest,HttpServletResponse) required", |
universe@11 | 174 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 175 | ); |
universe@11 | 176 | } |
universe@11 | 177 | } |
universe@11 | 178 | } |
universe@12 | 179 | } catch (SecurityException ex) { |
universe@12 | 180 | LOG.error("Scan for request mappings on declared methods failed.", ex); |
universe@11 | 181 | } |
universe@11 | 182 | } |
universe@11 | 183 | |
universe@11 | 184 | @Override |
universe@11 | 185 | public void destroy() { |
universe@11 | 186 | mappings.clear(); |
universe@11 | 187 | LOG.trace("{} destroyed", getServletName()); |
universe@11 | 188 | } |
universe@11 | 189 | |
universe@13 | 190 | /** |
universe@13 | 191 | * Sets the name of the dynamic fragment. |
universe@13 | 192 | * |
universe@13 | 193 | * It is sufficient to specify the name without any extension. The extension |
universe@13 | 194 | * is added automatically if not specified. |
universe@13 | 195 | * |
universe@13 | 196 | * The fragment must be located in the dynamic fragments folder. |
universe@13 | 197 | * |
universe@13 | 198 | * @param req the servlet request object |
universe@13 | 199 | * @param fragmentName the name of the fragment |
universe@13 | 200 | * @see Constants#DYN_FRAGMENT_PATH_PREFIX |
universe@13 | 201 | */ |
universe@13 | 202 | public void setDynamicFragment(HttpServletRequest req, String fragmentName) { |
universe@13 | 203 | req.setAttribute(Constants.REQ_ATTR_FRAGMENT, Functions.dynFragmentPath(fragmentName)); |
universe@13 | 204 | } |
universe@11 | 205 | |
universe@11 | 206 | /** |
universe@13 | 207 | * Specifies the name of an additional stylesheet used by the module. |
universe@13 | 208 | * |
universe@13 | 209 | * Setting an additional stylesheet is optional, but quite common for HTML |
universe@13 | 210 | * output. |
universe@13 | 211 | * |
universe@13 | 212 | * It is sufficient to specify the name without any extension. The extension |
universe@13 | 213 | * is added automatically if not specified. |
universe@11 | 214 | * |
universe@11 | 215 | * @param req the servlet request object |
universe@13 | 216 | * @param stylesheet the name of the stylesheet |
universe@11 | 217 | */ |
universe@13 | 218 | public void setStylesheet(HttpServletRequest req, String stylesheet) { |
universe@13 | 219 | req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css")); |
universe@10 | 220 | } |
universe@10 | 221 | |
universe@10 | 222 | private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp) |
universe@10 | 223 | throws IOException, ServletException { |
universe@10 | 224 | |
universe@11 | 225 | req.setAttribute(Constants.REQ_ATTR_MENU, getModuleManager().getMainMenu()); |
universe@13 | 226 | req.getRequestDispatcher(HTML_FULL_DISPATCHER).forward(req, resp); |
universe@10 | 227 | } |
universe@10 | 228 | |
universe@12 | 229 | private Optional<HandlerMethod> findMapping(HttpMethod method, HttpServletRequest req) { |
universe@11 | 230 | return Optional.ofNullable(mappings.get(method)).map( |
universe@18 | 231 | (rm) -> rm.get(Optional.ofNullable(req.getPathInfo()).orElse("/")) |
universe@11 | 232 | ); |
universe@11 | 233 | } |
universe@11 | 234 | |
universe@12 | 235 | private void forwardAsSepcified(ResponseType type, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 236 | throws ServletException, IOException { |
universe@12 | 237 | switch (type) { |
universe@12 | 238 | case NONE: return; |
universe@12 | 239 | case HTML_FULL: |
universe@12 | 240 | forwardToFullView(req, resp); |
universe@12 | 241 | return; |
universe@12 | 242 | // TODO: implement remaining response types |
universe@12 | 243 | default: |
universe@12 | 244 | // this code should be unreachable |
universe@12 | 245 | LOG.error("ResponseType switch is not exhaustive - this is a bug!"); |
universe@12 | 246 | throw new UnsupportedOperationException(); |
universe@12 | 247 | } |
universe@12 | 248 | } |
universe@12 | 249 | |
universe@12 | 250 | private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 251 | throws ServletException, IOException { |
universe@13 | 252 | |
universe@20 | 253 | // Synchronize module information with database |
universe@20 | 254 | getModuleManager().syncWithDatabase(getDatabaseFacade()); |
universe@13 | 255 | |
universe@13 | 256 | // choose the requested language as session language (if available) or fall back to english, otherwise |
universe@20 | 257 | HttpSession session = req.getSession(); |
universe@13 | 258 | if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) { |
universe@13 | 259 | Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList); |
universe@13 | 260 | Optional<Locale> reqLocale = Optional.of(req.getLocale()); |
universe@13 | 261 | Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH); |
universe@13 | 262 | session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale); |
universe@13 | 263 | LOG.debug("Settng language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage()); |
universe@14 | 264 | } else { |
universe@15 | 265 | Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE); |
universe@15 | 266 | resp.setLocale(sessionLocale); |
universe@15 | 267 | LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale); |
universe@13 | 268 | } |
universe@13 | 269 | |
universe@21 | 270 | // set some internal request attributes |
universe@13 | 271 | req.setAttribute(Constants.REQ_ATTR_PATH, Functions.fullPath(req)); |
universe@13 | 272 | req.setAttribute(Constants.REQ_ATTR_MODULE_CLASSNAME, this.getClass().getName()); |
universe@13 | 273 | moduleInfoELProxy.ifPresent((proxy) -> req.setAttribute(Constants.REQ_ATTR_MODULE_INFO, proxy)); |
universe@13 | 274 | |
universe@21 | 275 | |
universe@21 | 276 | // call the handler, if available, or send an HTTP 404 error |
universe@12 | 277 | Optional<HandlerMethod> mapping = findMapping(method, req); |
universe@12 | 278 | if (mapping.isPresent()) { |
universe@12 | 279 | forwardAsSepcified(mapping.get().apply(req, resp), req, resp); |
universe@12 | 280 | } else { |
universe@12 | 281 | resp.sendError(HttpServletResponse.SC_NOT_FOUND); |
universe@12 | 282 | } |
universe@12 | 283 | } |
universe@12 | 284 | |
universe@7 | 285 | @Override |
universe@7 | 286 | protected final void doGet(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 287 | throws ServletException, IOException { |
universe@12 | 288 | doProcess(HttpMethod.GET, req, resp); |
universe@7 | 289 | } |
universe@7 | 290 | |
universe@7 | 291 | @Override |
universe@7 | 292 | protected final void doPost(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 293 | throws ServletException, IOException { |
universe@12 | 294 | doProcess(HttpMethod.POST, req, resp); |
universe@7 | 295 | } |
universe@7 | 296 | } |