src/main/java/de/uapcore/lightpit/AbstractLightPITServlet.java

Fri, 23 Oct 2020 12:38:20 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 23 Oct 2020 12:38:20 +0200
changeset 145
6d2d69fd1c12
parent 131
67df332e3146
child 151
b3f14cd4f3ab
permissions
-rw-r--r--

removes (now) unnecessary possibility to customize the main menu

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

mercurial