Mon, 05 Apr 2021 17:56:46 +0200
project name and node may have 50 chars - fixes #118
184 | 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 | */ | |
25 | ||
26 | package de.uapcore.lightpit | |
27 | ||
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 java.sql.SQLException | |
32 | import java.util.* | |
33 | import javax.servlet.http.HttpServlet | |
34 | import javax.servlet.http.HttpServletRequest | |
35 | import javax.servlet.http.HttpServletResponse | |
36 | ||
37 | abstract class AbstractServlet : LoggingTrait, HttpServlet() { | |
38 | ||
39 | /** | |
40 | * Contains the GET request mappings. | |
41 | */ | |
42 | private val getMappings = mutableMapOf<PathPattern, MappingMethod>() | |
43 | ||
44 | /** | |
45 | * Contains the POST request mappings. | |
46 | */ | |
47 | private val postMappings = mutableMapOf<PathPattern, MappingMethod>() | |
48 | ||
49 | protected fun get(pattern: String, method: MappingMethod) { | |
50 | getMappings[PathPattern(pattern)] = method | |
51 | } | |
52 | ||
53 | protected fun post(pattern: String, method: MappingMethod) { | |
54 | postMappings[PathPattern(pattern)] = method | |
55 | } | |
56 | ||
57 | private fun notFound(http: HttpRequest, dao: DataAccessObject) { | |
58 | http.response.sendError(HttpServletResponse.SC_NOT_FOUND) | |
59 | } | |
60 | ||
61 | private fun findMapping( | |
62 | mappings: Map<PathPattern, MappingMethod>, | |
63 | req: HttpServletRequest | |
64 | ): Pair<PathPattern, MappingMethod> { | |
65 | val requestPath = sanitizedRequestPath(req) | |
66 | val candidates = mappings.filter { it.key.matches(requestPath) } | |
67 | return if (candidates.isEmpty()) { | |
68 | Pair(PathPattern(requestPath), ::notFound) | |
69 | } else { | |
70 | if (candidates.size > 1) { | |
71 | logger().warn("Ambiguous mapping for request path '{}'", requestPath) | |
72 | } | |
73 | candidates.entries.first().toPair() | |
74 | } | |
75 | } | |
76 | ||
77 | private fun invokeMapping( | |
78 | mapping: Pair<PathPattern, MappingMethod>, | |
79 | req: HttpServletRequest, | |
80 | resp: HttpServletResponse, | |
81 | dao: DataAccessObject | |
82 | ) { | |
83 | val params = mapping.first.obtainPathParameters(sanitizedRequestPath(req)) | |
84 | val method = mapping.second | |
85 | logger().trace("invoke {}", method) | |
86 | method(HttpRequest(req, resp, params), dao) | |
87 | } | |
88 | ||
89 | private fun sanitizedRequestPath(req: HttpServletRequest) = req.pathInfo ?: "/" | |
90 | ||
91 | private fun doProcess( | |
92 | req: HttpServletRequest, | |
93 | resp: HttpServletResponse, | |
94 | mappings: Map<PathPattern, MappingMethod> | |
95 | ) { | |
96 | val session = req.session | |
97 | ||
98 | // the very first thing to do is to force UTF-8 | |
99 | req.characterEncoding = "UTF-8" | |
100 | ||
101 | // choose the requested language as session language (if available) or fall back to english, otherwise | |
102 | if (session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) == null) { | |
103 | val availableLanguages = availableLanguages() | |
104 | val reqLocale = req.locale | |
105 | val sessionLocale = if (availableLanguages.contains(reqLocale)) reqLocale else availableLanguages.first() | |
106 | session.setAttribute(Constants.SESSION_ATTR_LANGUAGE, sessionLocale) | |
107 | logger().debug( | |
108 | "Setting language for new session {}: {}", session.id, sessionLocale.displayLanguage | |
109 | ) | |
110 | } else { | |
111 | val sessionLocale = session.getAttribute(Constants.SESSION_ATTR_LANGUAGE) as Locale | |
112 | resp.locale = sessionLocale | |
113 | logger().trace("Continuing session {} with language {}", session.id, sessionLocale) | |
114 | } | |
115 | ||
116 | // set some internal request attributes | |
117 | val http = HttpRequest(req, resp) | |
118 | val fullPath = req.servletPath + Optional.ofNullable(req.pathInfo).orElse("") | |
119 | req.setAttribute(Constants.REQ_ATTR_BASE_HREF, http.baseHref) | |
120 | req.setAttribute(Constants.REQ_ATTR_PATH, fullPath) | |
121 | req.getHeader("Referer")?.let { | |
122 | // TODO: add a sanity check to avoid link injection | |
123 | req.setAttribute(Constants.REQ_ATTR_REFERER, it) | |
124 | } | |
125 | ||
126 | // if this is an error path, bypass the normal flow | |
127 | if (fullPath.startsWith("/error/")) { | |
128 | http.styleSheets = listOf("error") | |
129 | http.render("error") | |
130 | return | |
131 | } | |
132 | ||
133 | // obtain a connection and create the data access objects | |
134 | val dsp = req.servletContext.getAttribute(SC_ATTR_NAME) as DataSourceProvider | |
135 | val dialect = dsp.dialect | |
136 | val ds = dsp.dataSource | |
137 | if (ds == null) { | |
138 | resp.sendError( | |
139 | HttpServletResponse.SC_SERVICE_UNAVAILABLE, | |
140 | "JNDI DataSource lookup failed. See log for details." | |
141 | ) | |
142 | return | |
143 | } | |
144 | try { | |
145 | ds.connection.use { connection -> | |
146 | val dao = createDataAccessObject(dialect, connection) | |
147 | try { | |
148 | connection.autoCommit = false | |
149 | invokeMapping(findMapping(mappings, req), req, resp, dao) | |
150 | connection.commit() | |
151 | } catch (ex: SQLException) { | |
152 | logger().warn("Database transaction failed (Code {}): {}", ex.errorCode, ex.message) | |
153 | logger().debug("Details: ", ex) | |
154 | resp.sendError( | |
155 | HttpServletResponse.SC_INTERNAL_SERVER_ERROR, | |
156 | "Unhandled Transaction Error - Code: " + ex.errorCode | |
157 | ) | |
158 | connection.rollback() | |
159 | } | |
160 | } | |
161 | } catch (ex: SQLException) { | |
162 | logger().error("Severe Database Exception (Code {}): {}", ex.errorCode, ex.message) | |
163 | logger().debug("Details: ", ex) | |
164 | resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database Error - Code: " + ex.errorCode) | |
165 | } | |
166 | } | |
167 | ||
168 | override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) { | |
169 | doProcess(req, resp, getMappings) | |
170 | } | |
171 | ||
172 | override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) { | |
173 | doProcess(req, resp, postMappings) | |
174 | } | |
175 | ||
176 | protected fun availableLanguages(): List<Locale> { | |
177 | val langTags = servletContext.getInitParameter(Constants.CTX_ATTR_LANGUAGES)?.split(",")?.map(String::trim) ?: emptyList() | |
178 | val locales = langTags.map(Locale::forLanguageTag).filter { it.language.isNotEmpty() } | |
179 | return if (locales.isEmpty()) listOf(Locale.ENGLISH) else locales | |
180 | } | |
181 | ||
182 | } |