src/main/kotlin/de/uapcore/lightpit/AbstractServlet.kt

Wed, 28 Dec 2022 13:21:30 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 28 Dec 2022 13:21:30 +0100
changeset 254
55ca6cafc3dd
parent 247
e71ae69c68c0
child 298
1275eb652008
permissions
-rw-r--r--

#233 migrate to Jakarta EE and update dependencies

     1 /*
     2  * Copyright 2021 Mike Becker. All rights reserved.
     3  *
     4  * Redistribution and use in source and binary forms, with or without
     5  * modification, are permitted provided that the following conditions are met:
     6  *
     7  * 1. Redistributions of source code must retain the above copyright
     8  * notice, this list of conditions and the following disclaimer.
     9  *
    10  * 2. Redistributions in binary form must reproduce the above copyright
    11  * notice, this list of conditions and the following disclaimer in the
    12  * documentation and/or other materials provided with the distribution.
    13  *
    14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    17  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    20  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    21  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    22  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    24  */
    26 package de.uapcore.lightpit
    28 import de.uapcore.lightpit.DataSourceProvider.Companion.SC_ATTR_NAME
    29 import de.uapcore.lightpit.dao.DataAccessObject
    30 import de.uapcore.lightpit.dao.createDataAccessObject
    31 import jakarta.servlet.http.HttpServlet
    32 import jakarta.servlet.http.HttpServletRequest
    33 import jakarta.servlet.http.HttpServletResponse
    34 import java.sql.SQLException
    35 import java.util.*
    37 abstract class AbstractServlet : HttpServlet() {
    39     protected val logger = MyLogger()
    41     /**
    42      * Contains the GET request mappings.
    43      */
    44     private val getMappings = mutableMapOf<PathPattern, MappingMethod>()
    46     /**
    47      * Contains the POST request mappings.
    48      */
    49     private val postMappings = mutableMapOf<PathPattern, MappingMethod>()
    51     protected fun get(pattern: String, method: MappingMethod) {
    52         getMappings[PathPattern(pattern)] = method
    53     }
    55     protected fun post(pattern: String, method: MappingMethod) {
    56         postMappings[PathPattern(pattern)] = method
    57     }
    59     private fun notFound(http: HttpRequest, dao: DataAccessObject) {
    60         http.response.sendError(HttpServletResponse.SC_NOT_FOUND)
    61     }
    63     private fun findMapping(
    64         mappings: Map<PathPattern, MappingMethod>,
    65         req: HttpServletRequest
    66     ): Pair<PathPattern, MappingMethod> {
    67         val requestPath = sanitizedRequestPath(req)
    68         val candidates = mappings.filter { it.key.matches(requestPath) }
    69         return if (candidates.isEmpty()) {
    70             Pair(PathPattern(requestPath), ::notFound)
    71         } else {
    72             if (candidates.size > 1) {
    73                 logger.warn("Ambiguous mapping for request path '{0}'", requestPath)
    74             }
    75             candidates.entries.first().toPair()
    76         }
    77     }
    79     private fun invokeMapping(
    80         mapping: Pair<PathPattern, MappingMethod>,
    81         req: HttpServletRequest,
    82         resp: HttpServletResponse,
    83         dao: DataAccessObject
    84     ) {
    85         val params = mapping.first.obtainPathParameters(sanitizedRequestPath(req))
    86         val method = mapping.second
    87         logger.trace("invoke {0}", method)
    88         method(HttpRequest(req, resp, params), dao)
    89     }
    91     private fun sanitizedRequestPath(req: HttpServletRequest) = req.pathInfo ?: "/"
    93     private fun doProcess(
    94         req: HttpServletRequest,
    95         resp: HttpServletResponse,
    96         mappings: Map<PathPattern, MappingMethod>
    97     ) {
    98         val session = req.session
   100         // the very first thing to do is to force UTF-8
   101         req.characterEncoding = "UTF-8"
   103         // choose the requested language as session language (if available) or fall back to english, otherwise
   104         if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) {
   105             val availableLanguages = availableLanguages()
   106             val reqLocale = req.locale
   107             val sessionLocale = if (availableLanguages.contains(reqLocale)) reqLocale else availableLanguages.first()
   108             session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale)
   109             resp.locale = sessionLocale
   110             logger.debug(
   111                 "Setting language for new session {0}: {1}", session.id, sessionLocale.displayLanguage
   112             )
   113         } else {
   114             val sessionLocale = session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) as Locale
   115             resp.locale = sessionLocale
   116             logger.trace("Continuing session {0} with language {1}", session.id, sessionLocale)
   117         }
   119         // set some internal request attributes
   120         val http = HttpRequest(req, resp)
   121         val fullPath = req.servletPath + Optional.ofNullable(req.pathInfo).orElse("")
   122         req.setAttribute(Constants.REQ_ATTR_BASE_HREF, http.baseHref)
   123         req.setAttribute(Constants.REQ_ATTR_PATH, fullPath)
   124         req.getHeader("Referer")?.let {
   125             // TODO: add a sanity check to avoid link injection
   126             req.setAttribute(Constants.REQ_ATTR_REFERER, it)
   127         }
   129         // if this is an error path, bypass the normal flow
   130         if (fullPath.startsWith("/error/")) {
   131             http.styleSheets = listOf("error")
   132             http.render("error")
   133             return
   134         }
   136         // obtain a connection and create the data access objects
   137         val dsp = req.servletContext.getAttribute(SC_ATTR_NAME) as DataSourceProvider
   138         val dialect = dsp.dialect
   139         val ds = dsp.dataSource
   140         if (ds == null) {
   141             resp.sendError(
   142                 HttpServletResponse.SC_SERVICE_UNAVAILABLE,
   143                 "JNDI DataSource lookup failed. See log for details."
   144             )
   145             return
   146         }
   147         try {
   148             ds.connection.use { connection ->
   149                 val dao = createDataAccessObject(dialect, connection)
   150                 try {
   151                     connection.autoCommit = false
   152                     invokeMapping(findMapping(mappings, req), req, resp, dao)
   153                     connection.commit()
   154                 } catch (ex: SQLException) {
   155                     logger.warn("Database transaction failed (Code {0}): {1}", ex.errorCode, ex.message)
   156                     logger.debug("Details: ", ex)
   157                     resp.sendError(
   158                         HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
   159                         "Unhandled Transaction Error - Code: " + ex.errorCode
   160                     )
   161                     connection.rollback()
   162                 }
   163             }
   164         } catch (ex: SQLException) {
   165             logger.error("Severe Database Exception (Code {0}): {1}", ex.errorCode, ex.message)
   166             logger.debug("Details: ", ex)
   167             resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.errorCode)
   168         }
   169     }
   171     override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
   172         doProcess(req, resp, getMappings)
   173     }
   175     override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
   176         doProcess(req, resp, postMappings)
   177     }
   179     protected fun availableLanguages(): List<Locale> {
   180         val langTags = servletContext.getInitParameter(Constants.CTX_ATTR_LANGUAGES)?.split(",")?.map(String::trim) ?: emptyList()
   181         val locales = langTags.map(Locale::forLanguageTag).filter { it.language.isNotEmpty() }
   182         return locales.ifEmpty { listOf(Locale.ENGLISH) }
   183     }
   185 }

mercurial