Fri, 09 Oct 2020 15:35:48 +0200
adds application level issue sorting (fixes #19)
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@83 | 42 | import java.lang.reflect.*; |
universe@38 | 43 | import java.sql.Connection; |
universe@38 | 44 | import java.sql.SQLException; |
universe@33 | 45 | import java.util.*; |
universe@63 | 46 | import java.util.function.Function; |
universe@7 | 47 | |
universe@7 | 48 | /** |
universe@7 | 49 | * A special implementation of a HTTPServlet which is focused on implementing |
universe@79 | 50 | * the necessary functionality for LightPIT pages. |
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@33 | 58 | |
universe@63 | 59 | @FunctionalInterface |
universe@63 | 60 | protected interface SQLFindFunction<K, T> { |
universe@63 | 61 | T apply(K key) throws SQLException; |
universe@63 | 62 | |
universe@63 | 63 | default <V> SQLFindFunction<V, T> compose(Function<? super V, ? extends K> before) throws SQLException { |
universe@63 | 64 | Objects.requireNonNull(before); |
universe@63 | 65 | return (v) -> this.apply(before.apply(v)); |
universe@63 | 66 | } |
universe@63 | 67 | |
universe@63 | 68 | default <V> SQLFindFunction<K, V> andThen(Function<? super T, ? extends V> after) throws SQLException { |
universe@63 | 69 | Objects.requireNonNull(after); |
universe@63 | 70 | return (t) -> after.apply(this.apply(t)); |
universe@63 | 71 | } |
universe@63 | 72 | |
universe@63 | 73 | static <K> Function<K, K> identity() { |
universe@63 | 74 | return (t) -> t; |
universe@63 | 75 | } |
universe@63 | 76 | } |
universe@63 | 77 | |
universe@10 | 78 | /** |
universe@11 | 79 | * Invocation mapping gathered from the {@link RequestMapping} annotations. |
universe@34 | 80 | * <p> |
universe@18 | 81 | * Paths in this map must always start with a leading slash, although |
universe@18 | 82 | * the specification in the annotation must not start with a leading slash. |
universe@34 | 83 | * <p> |
universe@34 | 84 | * The reason for this is the different handling of empty paths in |
universe@18 | 85 | * {@link HttpServletRequest#getPathInfo()}. |
universe@11 | 86 | */ |
universe@39 | 87 | private final Map<HttpMethod, Map<String, Method>> mappings = new HashMap<>(); |
universe@11 | 88 | |
universe@11 | 89 | /** |
universe@78 | 90 | * Returns the name of the resource bundle associated with this servlet. |
universe@86 | 91 | * |
universe@78 | 92 | * @return the resource bundle base name |
universe@78 | 93 | */ |
universe@78 | 94 | protected abstract String getResourceBundleName(); |
universe@78 | 95 | |
universe@38 | 96 | |
universe@34 | 97 | /** |
universe@38 | 98 | * Creates a set of data access objects for the specified connection. |
universe@33 | 99 | * |
universe@38 | 100 | * @param connection the SQL connection |
universe@38 | 101 | * @return a set of data access objects |
universe@17 | 102 | */ |
universe@38 | 103 | private DataAccessObjects createDataAccessObjects(Connection connection) throws SQLException { |
universe@38 | 104 | final var df = (DatabaseFacade) getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME); |
universe@39 | 105 | if (df.getSQLDialect() == DatabaseFacade.Dialect.Postgres) { |
universe@39 | 106 | return new PGDataAccessObjects(connection); |
universe@38 | 107 | } |
universe@39 | 108 | throw new AssertionError("Non-exhaustive if-else - this is a bug."); |
universe@17 | 109 | } |
universe@33 | 110 | |
universe@38 | 111 | private ResponseType invokeMapping(Method method, HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException { |
universe@11 | 112 | try { |
universe@14 | 113 | LOG.trace("invoke {}#{}", method.getDeclaringClass().getName(), method.getName()); |
universe@42 | 114 | final var paramTypes = method.getParameterTypes(); |
universe@42 | 115 | final var paramValues = new Object[paramTypes.length]; |
universe@42 | 116 | for (int i = 0; i < paramTypes.length; i++) { |
universe@42 | 117 | if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) { |
universe@42 | 118 | paramValues[i] = req; |
universe@42 | 119 | } else if (paramTypes[i].isAssignableFrom(HttpServletResponse.class)) { |
universe@42 | 120 | paramValues[i] = resp; |
universe@42 | 121 | } |
universe@42 | 122 | if (paramTypes[i].isAssignableFrom(DataAccessObjects.class)) { |
universe@42 | 123 | paramValues[i] = dao; |
universe@42 | 124 | } |
universe@42 | 125 | } |
universe@42 | 126 | return (ResponseType) method.invoke(this, paramValues); |
universe@73 | 127 | } catch (InvocationTargetException ex) { |
universe@73 | 128 | LOG.error("invocation of method {}::{} failed: {}", |
universe@73 | 129 | method.getDeclaringClass().getName(), method.getName(), ex.getTargetException().getMessage()); |
universe@73 | 130 | LOG.debug("Details: ", ex.getTargetException()); |
universe@73 | 131 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getTargetException().getMessage()); |
universe@73 | 132 | return ResponseType.NONE; |
universe@12 | 133 | } catch (ReflectiveOperationException | ClassCastException ex) { |
universe@73 | 134 | LOG.error("invocation of method {}::{} failed: {}", |
universe@73 | 135 | method.getDeclaringClass().getName(), method.getName(), ex.getMessage()); |
universe@38 | 136 | LOG.debug("Details: ", ex); |
universe@73 | 137 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); |
universe@12 | 138 | return ResponseType.NONE; |
universe@11 | 139 | } |
universe@11 | 140 | } |
universe@11 | 141 | |
universe@11 | 142 | @Override |
universe@11 | 143 | public void init() throws ServletException { |
universe@78 | 144 | scanForRequestMappings(); |
universe@33 | 145 | |
universe@12 | 146 | LOG.trace("{} initialized", getServletName()); |
universe@12 | 147 | } |
universe@12 | 148 | |
universe@12 | 149 | private void scanForRequestMappings() { |
universe@12 | 150 | try { |
universe@11 | 151 | Method[] methods = getClass().getDeclaredMethods(); |
universe@11 | 152 | for (Method method : methods) { |
universe@11 | 153 | Optional<RequestMapping> mapping = Optional.ofNullable(method.getAnnotation(RequestMapping.class)); |
universe@11 | 154 | if (mapping.isPresent()) { |
universe@11 | 155 | if (!Modifier.isPublic(method.getModifiers())) { |
universe@11 | 156 | LOG.warn("{} is annotated with {} but is not public", |
universe@11 | 157 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 158 | ); |
universe@11 | 159 | continue; |
universe@11 | 160 | } |
universe@11 | 161 | if (Modifier.isAbstract(method.getModifiers())) { |
universe@11 | 162 | LOG.warn("{} is annotated with {} but is abstract", |
universe@11 | 163 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 164 | ); |
universe@11 | 165 | continue; |
universe@11 | 166 | } |
universe@12 | 167 | if (!ResponseType.class.isAssignableFrom(method.getReturnType())) { |
universe@12 | 168 | LOG.warn("{} is annotated with {} but has the wrong return type - 'ResponseType' required", |
universe@12 | 169 | method.getName(), RequestMapping.class.getSimpleName() |
universe@12 | 170 | ); |
universe@12 | 171 | continue; |
universe@12 | 172 | } |
universe@12 | 173 | |
universe@42 | 174 | boolean paramsInjectible = true; |
universe@42 | 175 | for (var param : method.getParameterTypes()) { |
universe@42 | 176 | paramsInjectible &= HttpServletRequest.class.isAssignableFrom(param) |
universe@42 | 177 | || HttpServletResponse.class.isAssignableFrom(param) |
universe@42 | 178 | || DataAccessObjects.class.isAssignableFrom(param); |
universe@42 | 179 | } |
universe@42 | 180 | if (paramsInjectible) { |
universe@58 | 181 | String requestPath = "/" + mapping.get().requestPath(); |
universe@12 | 182 | |
universe@39 | 183 | if (mappings |
universe@39 | 184 | .computeIfAbsent(mapping.get().method(), k -> new HashMap<>()) |
universe@39 | 185 | .putIfAbsent(requestPath, method) != null) { |
universe@11 | 186 | LOG.warn("{} {} has multiple mappings", |
universe@11 | 187 | mapping.get().method(), |
universe@11 | 188 | mapping.get().requestPath() |
universe@11 | 189 | ); |
universe@11 | 190 | } |
universe@12 | 191 | |
universe@22 | 192 | LOG.debug("{} {} maps to {}::{}", |
universe@11 | 193 | mapping.get().method(), |
universe@18 | 194 | requestPath, |
universe@22 | 195 | getClass().getSimpleName(), |
universe@11 | 196 | method.getName() |
universe@11 | 197 | ); |
universe@11 | 198 | } else { |
universe@42 | 199 | LOG.warn("{} is annotated with {} but has the wrong parameters - only HttpServletRequest. HttpServletResponse, and DataAccessObjects are allowed", |
universe@11 | 200 | method.getName(), RequestMapping.class.getSimpleName() |
universe@11 | 201 | ); |
universe@11 | 202 | } |
universe@11 | 203 | } |
universe@11 | 204 | } |
universe@12 | 205 | } catch (SecurityException ex) { |
universe@12 | 206 | LOG.error("Scan for request mappings on declared methods failed.", ex); |
universe@11 | 207 | } |
universe@11 | 208 | } |
universe@11 | 209 | |
universe@11 | 210 | @Override |
universe@11 | 211 | public void destroy() { |
universe@11 | 212 | mappings.clear(); |
universe@11 | 213 | LOG.trace("{} destroyed", getServletName()); |
universe@11 | 214 | } |
universe@34 | 215 | |
universe@13 | 216 | /** |
universe@74 | 217 | * Sets the name of the content page. |
universe@34 | 218 | * <p> |
universe@13 | 219 | * It is sufficient to specify the name without any extension. The extension |
universe@13 | 220 | * is added automatically if not specified. |
universe@34 | 221 | * |
universe@74 | 222 | * @param req the servlet request object |
universe@74 | 223 | * @param pageName the name of the content page |
universe@74 | 224 | * @see Constants#REQ_ATTR_CONTENT_PAGE |
universe@13 | 225 | */ |
universe@74 | 226 | protected void setContentPage(HttpServletRequest req, String pageName) { |
universe@74 | 227 | req.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, Functions.jspPath(pageName)); |
universe@13 | 228 | } |
universe@34 | 229 | |
universe@11 | 230 | /** |
universe@96 | 231 | * Sets the navigation menu. |
universe@71 | 232 | * |
universe@109 | 233 | * @param req the servlet request object |
universe@109 | 234 | * @param jspName the name of the menu's jsp file |
universe@96 | 235 | * @see Constants#REQ_ATTR_NAVIGATION |
universe@71 | 236 | */ |
universe@109 | 237 | protected void setNavigationMenu(HttpServletRequest req, String jspName) { |
universe@109 | 238 | req.setAttribute(Constants.REQ_ATTR_NAVIGATION, Functions.jspPath(jspName)); |
universe@71 | 239 | } |
universe@71 | 240 | |
universe@71 | 241 | /** |
universe@47 | 242 | * @param req the servlet request object |
universe@47 | 243 | * @param location the location where to redirect |
universe@47 | 244 | * @see Constants#REQ_ATTR_REDIRECT_LOCATION |
universe@47 | 245 | */ |
universe@63 | 246 | protected void setRedirectLocation(HttpServletRequest req, String location) { |
universe@47 | 247 | if (location.startsWith("./")) { |
universe@47 | 248 | location = location.replaceFirst("\\./", Functions.baseHref(req)); |
universe@47 | 249 | } |
universe@47 | 250 | req.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, location); |
universe@47 | 251 | } |
universe@47 | 252 | |
universe@47 | 253 | /** |
universe@13 | 254 | * Specifies the name of an additional stylesheet used by the module. |
universe@34 | 255 | * <p> |
universe@13 | 256 | * Setting an additional stylesheet is optional, but quite common for HTML |
universe@13 | 257 | * output. |
universe@34 | 258 | * <p> |
universe@13 | 259 | * It is sufficient to specify the name without any extension. The extension |
universe@13 | 260 | * is added automatically if not specified. |
universe@34 | 261 | * |
universe@34 | 262 | * @param req the servlet request object |
universe@13 | 263 | * @param stylesheet the name of the stylesheet |
universe@11 | 264 | */ |
universe@13 | 265 | public void setStylesheet(HttpServletRequest req, String stylesheet) { |
universe@13 | 266 | req.setAttribute(Constants.REQ_ATTR_STYLESHEET, Functions.enforceExt(stylesheet, ".css")); |
universe@10 | 267 | } |
universe@34 | 268 | |
universe@47 | 269 | /** |
universe@86 | 270 | * Sets the view model object. |
universe@86 | 271 | * The type must match the expected type in the JSP file. |
universe@86 | 272 | * |
universe@86 | 273 | * @param req the servlet request object |
universe@86 | 274 | * @param viewModel the view model object |
universe@86 | 275 | */ |
universe@86 | 276 | public void setViewModel(HttpServletRequest req, Object viewModel) { |
universe@86 | 277 | req.setAttribute(Constants.REQ_ATTR_VIEWMODEL, viewModel); |
universe@86 | 278 | } |
universe@86 | 279 | |
universe@86 | 280 | /** |
universe@47 | 281 | * Obtains a request parameter of the specified type. |
universe@47 | 282 | * The specified type must have a single-argument constructor accepting a string to perform conversion. |
universe@47 | 283 | * The constructor of the specified type may throw an exception on conversion failures. |
universe@47 | 284 | * |
universe@71 | 285 | * @param req the servlet request object |
universe@47 | 286 | * @param clazz the class object of the expected type |
universe@71 | 287 | * @param name the name of the parameter |
universe@71 | 288 | * @param <T> the expected type |
universe@47 | 289 | * @return the parameter value or an empty optional, if no parameter with the specified name was found |
universe@47 | 290 | */ |
universe@71 | 291 | protected <T> Optional<T> getParameter(HttpServletRequest req, Class<T> clazz, String name) { |
universe@83 | 292 | if (clazz.isArray()) { |
universe@83 | 293 | final String[] paramValues = req.getParameterValues(name); |
universe@83 | 294 | int len = paramValues == null ? 0 : paramValues.length; |
universe@83 | 295 | final var array = (T) Array.newInstance(clazz.getComponentType(), len); |
universe@86 | 296 | for (int i = 0; i < len; i++) { |
universe@83 | 297 | try { |
universe@83 | 298 | final Constructor<?> ctor = clazz.getComponentType().getConstructor(String.class); |
universe@83 | 299 | Array.set(array, i, ctor.newInstance(paramValues[i])); |
universe@83 | 300 | } catch (ReflectiveOperationException e) { |
universe@83 | 301 | throw new RuntimeException(e); |
universe@83 | 302 | } |
universe@83 | 303 | } |
universe@83 | 304 | return Optional.of(array); |
universe@83 | 305 | } else { |
universe@83 | 306 | final String paramValue = req.getParameter(name); |
universe@83 | 307 | if (paramValue == null) return Optional.empty(); |
universe@83 | 308 | if (clazz.equals(Boolean.class)) { |
universe@83 | 309 | if (paramValue.toLowerCase().equals("false") || paramValue.equals("0")) { |
universe@83 | 310 | return Optional.of((T) Boolean.FALSE); |
universe@83 | 311 | } else { |
universe@83 | 312 | return Optional.of((T) Boolean.TRUE); |
universe@83 | 313 | } |
universe@83 | 314 | } |
universe@83 | 315 | if (clazz.equals(String.class)) return Optional.of((T) paramValue); |
universe@83 | 316 | if (java.sql.Date.class.isAssignableFrom(clazz)) { |
universe@83 | 317 | try { |
universe@83 | 318 | return Optional.of((T) java.sql.Date.valueOf(paramValue)); |
universe@83 | 319 | } catch (IllegalArgumentException ex) { |
universe@83 | 320 | return Optional.empty(); |
universe@83 | 321 | } |
universe@83 | 322 | } |
universe@83 | 323 | try { |
universe@83 | 324 | final Constructor<T> ctor = clazz.getConstructor(String.class); |
universe@83 | 325 | return Optional.of(ctor.newInstance(paramValue)); |
universe@83 | 326 | } catch (ReflectiveOperationException e) { |
universe@106 | 327 | // does not type check and is not convertible - treat as if the parameter was never set |
universe@106 | 328 | return Optional.empty(); |
universe@80 | 329 | } |
universe@80 | 330 | } |
universe@47 | 331 | } |
universe@47 | 332 | |
universe@63 | 333 | /** |
universe@63 | 334 | * Tries to look up an entity with a key obtained from a request parameter. |
universe@63 | 335 | * |
universe@71 | 336 | * @param req the servlet request object |
universe@63 | 337 | * @param clazz the class representing the type of the request parameter |
universe@71 | 338 | * @param name the name of the request parameter |
universe@71 | 339 | * @param find the find function (typically a DAO function) |
universe@71 | 340 | * @param <T> the type of the request parameter |
universe@71 | 341 | * @param <R> the type of the looked up entity |
universe@63 | 342 | * @return the retrieved entity or an empty optional if there is no such entity or the request parameter was missing |
universe@63 | 343 | * @throws SQLException if the find function throws an exception |
universe@63 | 344 | */ |
universe@71 | 345 | protected <T, R> Optional<R> findByParameter(HttpServletRequest req, Class<T> clazz, String name, SQLFindFunction<? super T, ? extends R> find) throws SQLException { |
universe@63 | 346 | final var param = getParameter(req, clazz, name); |
universe@63 | 347 | if (param.isPresent()) { |
universe@63 | 348 | return Optional.ofNullable(find.apply(param.get())); |
universe@63 | 349 | } else { |
universe@63 | 350 | return Optional.empty(); |
universe@63 | 351 | } |
universe@63 | 352 | } |
universe@63 | 353 | |
universe@10 | 354 | private void forwardToFullView(HttpServletRequest req, HttpServletResponse resp) |
universe@10 | 355 | throws IOException, ServletException { |
universe@34 | 356 | |
universe@79 | 357 | final String lightpitBundle = "localization.lightpit"; |
universe@79 | 358 | final var mainMenu = List.of( |
universe@79 | 359 | new MenuEntry(new ResourceKey(lightpitBundle, "menu.projects"), "projects/"), |
universe@79 | 360 | new MenuEntry(new ResourceKey(lightpitBundle, "menu.users"), "teams/"), |
universe@79 | 361 | new MenuEntry(new ResourceKey(lightpitBundle, "menu.languages"), "language/") |
universe@79 | 362 | ); |
universe@71 | 363 | for (var entry : mainMenu) { |
universe@71 | 364 | if (Functions.fullPath(req).startsWith("/" + entry.getPathName())) { |
universe@71 | 365 | entry.setActive(true); |
universe@71 | 366 | } |
universe@71 | 367 | } |
universe@71 | 368 | req.setAttribute(Constants.REQ_ATTR_MENU, mainMenu); |
universe@43 | 369 | req.getRequestDispatcher(SITE_JSP).forward(req, resp); |
universe@10 | 370 | } |
universe@34 | 371 | |
universe@45 | 372 | private String sanitizeRequestPath(HttpServletRequest req) { |
universe@45 | 373 | return Optional.ofNullable(req.getPathInfo()).orElse("/"); |
universe@45 | 374 | } |
universe@45 | 375 | |
universe@39 | 376 | private Optional<Method> findMapping(HttpMethod method, HttpServletRequest req) { |
universe@45 | 377 | return Optional.ofNullable(mappings.get(method)).map(rm -> rm.get(sanitizeRequestPath(req))); |
universe@11 | 378 | } |
universe@34 | 379 | |
universe@34 | 380 | private void forwardAsSpecified(ResponseType type, HttpServletRequest req, HttpServletResponse resp) |
universe@12 | 381 | throws ServletException, IOException { |
universe@12 | 382 | switch (type) { |
universe@34 | 383 | case NONE: |
universe@34 | 384 | return; |
universe@43 | 385 | case HTML: |
universe@12 | 386 | forwardToFullView(req, resp); |
universe@12 | 387 | return; |
universe@12 | 388 | // TODO: implement remaining response types |
universe@12 | 389 | default: |
universe@34 | 390 | throw new AssertionError("ResponseType switch is not exhaustive - this is a bug!"); |
universe@12 | 391 | } |
universe@12 | 392 | } |
universe@34 | 393 | |
universe@38 | 394 | private void doProcess(HttpMethod method, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { |
universe@27 | 395 | |
universe@13 | 396 | // choose the requested language as session language (if available) or fall back to english, otherwise |
universe@20 | 397 | HttpSession session = req.getSession(); |
universe@13 | 398 | if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) { |
universe@13 | 399 | Optional<List<String>> availableLanguages = Functions.availableLanguages(getServletContext()).map(Arrays::asList); |
universe@13 | 400 | Optional<Locale> reqLocale = Optional.of(req.getLocale()); |
universe@13 | 401 | Locale sessionLocale = reqLocale.filter((rl) -> availableLanguages.map((al) -> al.contains(rl.getLanguage())).orElse(false)).orElse(Locale.ENGLISH); |
universe@13 | 402 | session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale); |
universe@34 | 403 | LOG.debug("Setting language for new session {}: {}", session.getId(), sessionLocale.getDisplayLanguage()); |
universe@14 | 404 | } else { |
universe@15 | 405 | Locale sessionLocale = (Locale) session.getAttribute(Constants.SESSION_ATTR_LANGUAGE); |
universe@15 | 406 | resp.setLocale(sessionLocale); |
universe@15 | 407 | LOG.trace("Continuing session {} with language {}", session.getId(), sessionLocale); |
universe@13 | 408 | } |
universe@34 | 409 | |
universe@21 | 410 | // set some internal request attributes |
universe@53 | 411 | final String fullPath = Functions.fullPath(req); |
universe@47 | 412 | req.setAttribute(Constants.REQ_ATTR_BASE_HREF, Functions.baseHref(req)); |
universe@53 | 413 | req.setAttribute(Constants.REQ_ATTR_PATH, fullPath); |
universe@78 | 414 | req.setAttribute(Constants.REQ_ATTR_RESOURCE_BUNDLE, getResourceBundleName()); |
universe@34 | 415 | |
universe@53 | 416 | // if this is an error path, bypass the normal flow |
universe@53 | 417 | if (fullPath.startsWith("/error/")) { |
universe@53 | 418 | final var mapping = findMapping(method, req); |
universe@53 | 419 | if (mapping.isPresent()) { |
universe@53 | 420 | forwardAsSpecified(invokeMapping(mapping.get(), req, resp, null), req, resp); |
universe@53 | 421 | } |
universe@53 | 422 | return; |
universe@53 | 423 | } |
universe@53 | 424 | |
universe@38 | 425 | // obtain a connection and create the data access objects |
universe@38 | 426 | final var db = (DatabaseFacade) req.getServletContext().getAttribute(DatabaseFacade.SC_ATTR_NAME); |
universe@53 | 427 | final var ds = db.getDataSource(); |
universe@53 | 428 | if (ds == null) { |
universe@53 | 429 | resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "JNDI DataSource lookup failed. See log for details."); |
universe@53 | 430 | return; |
universe@53 | 431 | } |
universe@53 | 432 | try (final var connection = ds.getConnection()) { |
universe@38 | 433 | final var dao = createDataAccessObjects(connection); |
universe@39 | 434 | try { |
universe@39 | 435 | connection.setAutoCommit(false); |
universe@39 | 436 | // call the handler, if available, or send an HTTP 404 error |
universe@39 | 437 | final var mapping = findMapping(method, req); |
universe@39 | 438 | if (mapping.isPresent()) { |
universe@39 | 439 | forwardAsSpecified(invokeMapping(mapping.get(), req, resp, dao), req, resp); |
universe@39 | 440 | } else { |
universe@39 | 441 | resp.sendError(HttpServletResponse.SC_NOT_FOUND); |
universe@39 | 442 | } |
universe@39 | 443 | connection.commit(); |
universe@39 | 444 | } catch (SQLException ex) { |
universe@39 | 445 | LOG.warn("Database transaction failed (Code {}): {}", ex.getErrorCode(), ex.getMessage()); |
universe@39 | 446 | LOG.debug("Details: ", ex); |
universe@54 | 447 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unhandled Transaction Error - Code: " + ex.getErrorCode()); |
universe@39 | 448 | connection.rollback(); |
universe@38 | 449 | } |
universe@38 | 450 | } catch (SQLException ex) { |
universe@39 | 451 | LOG.error("Severe Database Exception (Code {}): {}", ex.getErrorCode(), ex.getMessage()); |
universe@38 | 452 | LOG.debug("Details: ", ex); |
universe@54 | 453 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.getErrorCode()); |
universe@12 | 454 | } |
universe@12 | 455 | } |
universe@34 | 456 | |
universe@7 | 457 | @Override |
universe@7 | 458 | protected final void doGet(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 459 | throws ServletException, IOException { |
universe@12 | 460 | doProcess(HttpMethod.GET, req, resp); |
universe@7 | 461 | } |
universe@7 | 462 | |
universe@7 | 463 | @Override |
universe@7 | 464 | protected final void doPost(HttpServletRequest req, HttpServletResponse resp) |
universe@7 | 465 | throws ServletException, IOException { |
universe@12 | 466 | doProcess(HttpMethod.POST, req, resp); |
universe@7 | 467 | } |
universe@7 | 468 | } |