Thu, 13 May 2021 11:28:50 +0200
#109 - add RSS feed
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 javax.servlet.http.HttpServletRequest
32 import javax.servlet.http.HttpServletResponse
33 import javax.servlet.http.HttpSession
34 import kotlin.math.min
36 typealias MappingMethod = (HttpRequest, DataAccessObject) -> Unit
37 typealias PathParameters = Map<String, String>
39 class HttpRequest(
40 val request: HttpServletRequest,
41 val response: HttpServletResponse,
42 val pathParams: PathParameters = emptyMap()
43 ) {
44 val session: HttpSession = request.session
46 val remoteUser: String? = request.remoteUser
48 /**
49 * The name of the content page.
50 *
51 * @see Constants#REQ_ATTR_CONTENT_PAGE
52 */
53 var contentPage = ""
54 set(value) {
55 field = value
56 request.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, jspPath(value))
57 }
59 /**
60 * A list of additional style sheets.
61 *
62 * @see Constants#REQ_ATTR_STYLESHEET
63 */
64 var styleSheets = emptyList<String>()
65 set(value) {
66 field = value
67 request.setAttribute(Constants.REQ_ATTR_STYLESHEET,
68 value.map { it.withExt(".css") }
69 )
70 }
72 /**
73 * The name of the navigation menu JSP.
74 *
75 * @see Constants#REQ_ATTR_NAVIGATION
76 */
77 var navigationMenu: NavMenu? = null
78 set(value) {
79 field = value
80 request.setAttribute(Constants.REQ_ATTR_NAVIGATION, navigationMenu)
81 }
83 var redirectLocation = ""
84 set(value) {
85 field = value
86 request.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, baseHref + value)
87 }
89 /**
90 * The view object.
91 *
92 * @see Constants#REQ_ATTR_VIEWMODEL
93 */
94 var view: View? = null
95 set(value) {
96 field = value
97 request.setAttribute(Constants.REQ_ATTR_VIEWMODEL, value)
98 }
100 /**
101 * The base path of this application.
102 */
103 val baseHref get() = "${request.scheme}://${request.serverName}:${request.serverPort}${request.contextPath}/"
105 private fun String.withExt(ext: String) = if (endsWith(ext)) this else plus(ext)
106 private fun jspPath(name: String) = Constants.JSP_PATH_PREFIX.plus(name).withExt(".jsp")
108 fun param(name: String): String? = request.getParameter(name)
109 fun paramArray(name: String): Array<String> = request.getParameterValues(name) ?: emptyArray()
111 fun forward(jsp: String) {
112 request.getRequestDispatcher(jspPath(jsp)).forward(request, response)
113 }
115 fun render(page: String? = null) {
116 page?.let { contentPage = it }
117 forward("site")
118 }
120 fun renderCommit(location: String? = null) {
121 location?.let { redirectLocation = it }
122 contentPage = Constants.JSP_COMMIT_SUCCESSFUL
123 render()
124 }
125 }
127 /**
128 * A path pattern optionally containing placeholders.
129 *
130 * The special directories . and .. are disallowed in the pattern.
131 * Placeholders start with a % sign.
132 *
133 * @param pattern the pattern
134 */
135 class PathPattern(pattern: String) {
136 private val nodePatterns: List<String>
137 private val collection: Boolean
139 private fun parse(pattern: String): List<String> {
140 val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
141 require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
142 return nodes
143 }
145 /**
146 * Matches a path against this pattern.
147 * The path must be canonical in the sense that no . or .. parts occur.
148 *
149 * @param path the path to match
150 * @return true if the path matches the pattern, false otherwise
151 */
152 fun matches(path: String): Boolean {
153 if (collection xor path.endsWith("/")) return false
154 val nodes = parse(path)
155 if (nodePatterns.size != nodes.size) return false
156 for (i in nodePatterns.indices) {
157 val pattern = nodePatterns[i]
158 val node = nodes[i]
159 if (pattern.startsWith("%")) continue
160 if (pattern != node) return false
161 }
162 return true
163 }
165 /**
166 * Returns the path parameters found in the specified path using this pattern.
167 * The return value of this method is undefined, if the patter does not match.
168 *
169 * @param path the path
170 * @return the path parameters, if any, or an empty map
171 * @see .matches
172 */
173 fun obtainPathParameters(path: String): PathParameters {
174 val params = mutableMapOf<String, String>()
175 val nodes = parse(path)
176 for (i in 0 until min(nodes.size, nodePatterns.size)) {
177 val pattern = nodePatterns[i]
178 val node = nodes[i]
179 if (pattern.startsWith("%")) {
180 params[pattern.substring(1)] = node
181 }
182 }
183 return params
184 }
186 override fun hashCode(): Int {
187 val str = StringBuilder()
188 for (node in nodePatterns) {
189 if (node.startsWith("%")) {
190 str.append("/%")
191 } else {
192 str.append('/')
193 str.append(node)
194 }
195 }
196 if (collection) str.append('/')
197 return str.toString().hashCode()
198 }
200 override fun equals(other: Any?): Boolean {
201 if (other is PathPattern) {
202 if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
203 for (i in nodePatterns.indices) {
204 val left = nodePatterns[i]
205 val right = other.nodePatterns[i]
206 if (left.startsWith("%") && right.startsWith("%")) continue
207 if (left != right) return false
208 }
209 return true
210 } else {
211 return false
212 }
213 }
215 init {
216 nodePatterns = parse(pattern)
217 collection = pattern.endsWith("/")
218 }
219 }