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