Sun, 01 Aug 2021 18:56:28 +0200
#115 adds custom page titles
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.dao.DataAccessObject
29 import de.uapcore.lightpit.viewmodel.NavMenu
30 import de.uapcore.lightpit.viewmodel.View
31 import java.util.*
32 import javax.servlet.http.HttpServletRequest
33 import javax.servlet.http.HttpServletResponse
34 import javax.servlet.http.HttpSession
35 import kotlin.math.min
37 typealias MappingMethod = (HttpRequest, DataAccessObject) -> Unit
38 typealias PathParameters = Map<String, String>
40 class HttpRequest(
41 val request: HttpServletRequest,
42 val response: HttpServletResponse,
43 val pathParams: PathParameters = emptyMap()
44 ) {
45 val session: HttpSession = request.session
47 val remoteUser: String? = request.remoteUser
49 /**
50 * The name of the content page.
51 *
52 * @see Constants#REQ_ATTR_CONTENT_PAGE
53 */
54 var contentPage = ""
55 set(value) {
56 field = value
57 request.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, jspPath(value))
58 }
60 /**
61 * The name of the content page.
62 *
63 * @see Constants#REQ_ATTR_CONTENT_PAGE
64 */
65 var pageTitle = ""
66 set(value) {
67 field = value
68 request.setAttribute(Constants.REQ_ATTR_PAGE_TITLE, value)
69 }
71 /**
72 * A list of additional style sheets.
73 *
74 * @see Constants#REQ_ATTR_STYLESHEET
75 */
76 var styleSheets = emptyList<String>()
77 set(value) {
78 field = value
79 request.setAttribute(Constants.REQ_ATTR_STYLESHEET,
80 value.map { it.withExt(".css") }
81 )
82 }
84 /**
85 * The name of the navigation menu JSP.
86 *
87 * @see Constants#REQ_ATTR_NAVIGATION
88 */
89 var navigationMenu: NavMenu? = null
90 set(value) {
91 field = value
92 request.setAttribute(Constants.REQ_ATTR_NAVIGATION, navigationMenu)
93 }
95 var redirectLocation: String? = null
96 set(value) {
97 field = value
98 if (value == null) {
99 request.removeAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION)
100 } else {
101 request.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, baseHref + value)
102 }
103 }
105 var feedPath: String? = null
106 set(value) {
107 field = value
108 if (value == null) {
109 request.removeAttribute(Constants.REQ_ATTR_FEED_HREF)
110 } else {
111 request.setAttribute(Constants.REQ_ATTR_FEED_HREF, baseHref + value)
112 }
113 }
115 /**
116 * The view object.
117 *
118 * @see Constants#REQ_ATTR_VIEWMODEL
119 */
120 var view: View? = null
121 set(value) {
122 field = value
123 request.setAttribute(Constants.REQ_ATTR_VIEWMODEL, value)
124 }
126 /**
127 * Additional port info, if necessary.
128 */
129 private val portInfo =
130 if ((request.scheme == "http" && request.serverPort == 80)
131 || (request.scheme == "https" && request.serverPort == 443)
132 ) "" else ":${request.serverPort}"
134 /**
135 * The base path of this application.
136 */
137 val baseHref get() = "${request.scheme}://${request.serverName}$portInfo${request.contextPath}/"
139 private fun String.withExt(ext: String) = if (endsWith(ext)) this else plus(ext)
140 private fun jspPath(name: String) = Constants.JSP_PATH_PREFIX.plus(name).withExt(".jsp")
142 fun param(name: String): String? = request.getParameter(name)
143 fun paramArray(name: String): Array<String> = request.getParameterValues(name) ?: emptyArray()
145 private fun forward(jsp: String) {
146 request.getRequestDispatcher(jspPath(jsp)).forward(request, response)
147 }
149 fun renderFeed(page: String? = null) {
150 page?.let { contentPage = it }
151 forward("feed")
152 }
154 fun render(page: String? = null) {
155 page?.let { contentPage = it }
156 forward("site")
157 }
159 fun renderCommit(location: String? = null) {
160 location?.let { redirectLocation = it }
161 contentPage = Constants.JSP_COMMIT_SUCCESSFUL
162 render()
163 }
165 fun i18n(key: String) = ResourceBundle.getBundle("localization/strings", response.locale).getString(key)
166 }
168 /**
169 * A path pattern optionally containing placeholders.
170 *
171 * The special directories . and .. are disallowed in the pattern.
172 * Placeholders start with a % sign.
173 *
174 * @param pattern the pattern
175 */
176 class PathPattern(pattern: String) {
177 private val nodePatterns: List<String>
178 private val collection: Boolean
180 private fun parse(pattern: String): List<String> {
181 val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
182 require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
183 return nodes
184 }
186 /**
187 * Matches a path against this pattern.
188 * The path must be canonical in the sense that no . or .. parts occur.
189 *
190 * @param path the path to match
191 * @return true if the path matches the pattern, false otherwise
192 */
193 fun matches(path: String): Boolean {
194 if (collection xor path.endsWith("/")) return false
195 val nodes = parse(path)
196 if (nodePatterns.size != nodes.size) return false
197 for (i in nodePatterns.indices) {
198 val pattern = nodePatterns[i]
199 val node = nodes[i]
200 if (pattern.startsWith("%")) continue
201 if (pattern != node) return false
202 }
203 return true
204 }
206 /**
207 * Returns the path parameters found in the specified path using this pattern.
208 * The return value of this method is undefined, if the patter does not match.
209 *
210 * @param path the path
211 * @return the path parameters, if any, or an empty map
212 * @see .matches
213 */
214 fun obtainPathParameters(path: String): PathParameters {
215 val params = mutableMapOf<String, String>()
216 val nodes = parse(path)
217 for (i in 0 until min(nodes.size, nodePatterns.size)) {
218 val pattern = nodePatterns[i]
219 val node = nodes[i]
220 if (pattern.startsWith("%")) {
221 params[pattern.substring(1)] = node
222 }
223 }
224 return params
225 }
227 override fun hashCode(): Int {
228 val str = StringBuilder()
229 for (node in nodePatterns) {
230 if (node.startsWith("%")) {
231 str.append("/%")
232 } else {
233 str.append('/')
234 str.append(node)
235 }
236 }
237 if (collection) str.append('/')
238 return str.toString().hashCode()
239 }
241 override fun equals(other: Any?): Boolean {
242 if (other is PathPattern) {
243 if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
244 for (i in nodePatterns.indices) {
245 val left = nodePatterns[i]
246 val right = other.nodePatterns[i]
247 if (left.startsWith("%") && right.startsWith("%")) continue
248 if (left != right) return false
249 }
250 return true
251 } else {
252 return false
253 }
254 }
256 init {
257 nodePatterns = parse(pattern)
258 collection = pattern.endsWith("/")
259 }
260 }