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