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