Thu, 13 May 2021 19:31:09 +0200
fixes wrong handling of feeds - only one channel per feed is allowed
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 var feedPath = ""
90 set(value) {
91 field = value
92 request.setAttribute(Constants.REQ_ATTR_FEED_HREF, baseHref + value)
93 }
95 /**
96 * The view object.
97 *
98 * @see Constants#REQ_ATTR_VIEWMODEL
99 */
100 var view: View? = null
101 set(value) {
102 field = value
103 request.setAttribute(Constants.REQ_ATTR_VIEWMODEL, value)
104 }
106 /**
107 * Additional port info, if necessary.
108 */
109 private val portInfo =
110 if ((request.scheme == "http" && request.serverPort == 80)
111 || (request.scheme == "https" && request.serverPort == 443)
112 ) "" else ":${request.serverPort}"
114 /**
115 * The base path of this application.
116 */
117 val baseHref get() = "${request.scheme}://${request.serverName}$portInfo${request.contextPath}/"
119 init {
120 feedPath = "feed/projects.rss"
121 }
123 private fun String.withExt(ext: String) = if (endsWith(ext)) this else plus(ext)
124 private fun jspPath(name: String) = Constants.JSP_PATH_PREFIX.plus(name).withExt(".jsp")
126 fun param(name: String): String? = request.getParameter(name)
127 fun paramArray(name: String): Array<String> = request.getParameterValues(name) ?: emptyArray()
129 private fun forward(jsp: String) {
130 request.getRequestDispatcher(jspPath(jsp)).forward(request, response)
131 }
133 fun renderFeed(page: String? = null) {
134 page?.let { contentPage = it }
135 forward("feed")
136 }
138 fun render(page: String? = null) {
139 page?.let { contentPage = it }
140 forward("site")
141 }
143 fun renderCommit(location: String? = null) {
144 location?.let { redirectLocation = it }
145 contentPage = Constants.JSP_COMMIT_SUCCESSFUL
146 render()
147 }
148 }
150 /**
151 * A path pattern optionally containing placeholders.
152 *
153 * The special directories . and .. are disallowed in the pattern.
154 * Placeholders start with a % sign.
155 *
156 * @param pattern the pattern
157 */
158 class PathPattern(pattern: String) {
159 private val nodePatterns: List<String>
160 private val collection: Boolean
162 private fun parse(pattern: String): List<String> {
163 val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
164 require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
165 return nodes
166 }
168 /**
169 * Matches a path against this pattern.
170 * The path must be canonical in the sense that no . or .. parts occur.
171 *
172 * @param path the path to match
173 * @return true if the path matches the pattern, false otherwise
174 */
175 fun matches(path: String): Boolean {
176 if (collection xor path.endsWith("/")) return false
177 val nodes = parse(path)
178 if (nodePatterns.size != nodes.size) return false
179 for (i in nodePatterns.indices) {
180 val pattern = nodePatterns[i]
181 val node = nodes[i]
182 if (pattern.startsWith("%")) continue
183 if (pattern != node) return false
184 }
185 return true
186 }
188 /**
189 * Returns the path parameters found in the specified path using this pattern.
190 * The return value of this method is undefined, if the patter does not match.
191 *
192 * @param path the path
193 * @return the path parameters, if any, or an empty map
194 * @see .matches
195 */
196 fun obtainPathParameters(path: String): PathParameters {
197 val params = mutableMapOf<String, String>()
198 val nodes = parse(path)
199 for (i in 0 until min(nodes.size, nodePatterns.size)) {
200 val pattern = nodePatterns[i]
201 val node = nodes[i]
202 if (pattern.startsWith("%")) {
203 params[pattern.substring(1)] = node
204 }
205 }
206 return params
207 }
209 override fun hashCode(): Int {
210 val str = StringBuilder()
211 for (node in nodePatterns) {
212 if (node.startsWith("%")) {
213 str.append("/%")
214 } else {
215 str.append('/')
216 str.append(node)
217 }
218 }
219 if (collection) str.append('/')
220 return str.toString().hashCode()
221 }
223 override fun equals(other: Any?): Boolean {
224 if (other is PathPattern) {
225 if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
226 for (i in nodePatterns.indices) {
227 val left = nodePatterns[i]
228 val right = other.nodePatterns[i]
229 if (left.startsWith("%") && right.startsWith("%")) continue
230 if (left != right) return false
231 }
232 return true
233 } else {
234 return false
235 }
236 }
238 init {
239 nodePatterns = parse(pattern)
240 collection = pattern.endsWith("/")
241 }
242 }