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