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