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

Thu, 19 Nov 2020 13:58:54 +0100

author
mike@uapl01.localdomain
date
Thu, 19 Nov 2020 13:58:54 +0100
changeset 159
86b5d8a1662f
parent 158
4f912cd42876
child 160
e2d09cf3fb96
permissions
-rw-r--r--

migrates DAO classes

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

mercurial