src/main/kotlin/de/uapcore/lightpit/RequestMapping.kt

Sun, 01 Aug 2021 18:56:28 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 01 Aug 2021 18:56:28 +0200
changeset 205
7725a79416f3
parent 199
59393c8cc557
child 207
479dd7993ef9
permissions
-rw-r--r--

#115 adds custom page titles

universe@179 1 /*
universe@179 2 * Copyright 2021 Mike Becker. All rights reserved.
universe@179 3 *
universe@179 4 * Redistribution and use in source and binary forms, with or without
universe@179 5 * modification, are permitted provided that the following conditions are met:
universe@179 6 *
universe@179 7 * 1. Redistributions of source code must retain the above copyright
universe@179 8 * notice, this list of conditions and the following disclaimer.
universe@179 9 *
universe@179 10 * 2. Redistributions in binary form must reproduce the above copyright
universe@179 11 * notice, this list of conditions and the following disclaimer in the
universe@179 12 * documentation and/or other materials provided with the distribution.
universe@179 13 *
universe@179 14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
universe@179 15 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
universe@179 16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
universe@179 17 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
universe@179 18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
universe@179 19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
universe@179 20 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
universe@179 21 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
universe@179 22 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
universe@179 23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
universe@179 24 */
universe@179 25
universe@179 26 package de.uapcore.lightpit
universe@179 27
universe@184 28 import de.uapcore.lightpit.dao.DataAccessObject
universe@184 29 import de.uapcore.lightpit.viewmodel.NavMenu
universe@184 30 import de.uapcore.lightpit.viewmodel.View
universe@205 31 import java.util.*
universe@184 32 import javax.servlet.http.HttpServletRequest
universe@184 33 import javax.servlet.http.HttpServletResponse
universe@184 34 import javax.servlet.http.HttpSession
universe@179 35 import kotlin.math.min
universe@179 36
universe@184 37 typealias MappingMethod = (HttpRequest, DataAccessObject) -> Unit
universe@184 38 typealias PathParameters = Map<String, String>
universe@184 39
universe@184 40 class HttpRequest(
universe@184 41 val request: HttpServletRequest,
universe@184 42 val response: HttpServletResponse,
universe@184 43 val pathParams: PathParameters = emptyMap()
universe@184 44 ) {
universe@184 45 val session: HttpSession = request.session
universe@184 46
universe@184 47 val remoteUser: String? = request.remoteUser
universe@179 48
universe@179 49 /**
universe@184 50 * The name of the content page.
universe@179 51 *
universe@184 52 * @see Constants#REQ_ATTR_CONTENT_PAGE
universe@179 53 */
universe@184 54 var contentPage = ""
universe@184 55 set(value) {
universe@184 56 field = value
universe@184 57 request.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, jspPath(value))
universe@184 58 }
universe@179 59
universe@179 60 /**
universe@205 61 * The name of the content page.
universe@205 62 *
universe@205 63 * @see Constants#REQ_ATTR_CONTENT_PAGE
universe@205 64 */
universe@205 65 var pageTitle = ""
universe@205 66 set(value) {
universe@205 67 field = value
universe@205 68 request.setAttribute(Constants.REQ_ATTR_PAGE_TITLE, value)
universe@205 69 }
universe@205 70
universe@205 71 /**
universe@184 72 * A list of additional style sheets.
universe@179 73 *
universe@184 74 * @see Constants#REQ_ATTR_STYLESHEET
universe@179 75 */
universe@184 76 var styleSheets = emptyList<String>()
universe@184 77 set(value) {
universe@184 78 field = value
universe@184 79 request.setAttribute(Constants.REQ_ATTR_STYLESHEET,
universe@184 80 value.map { it.withExt(".css") }
universe@184 81 )
universe@184 82 }
universe@179 83
universe@184 84 /**
universe@184 85 * The name of the navigation menu JSP.
universe@184 86 *
universe@184 87 * @see Constants#REQ_ATTR_NAVIGATION
universe@184 88 */
universe@184 89 var navigationMenu: NavMenu? = null
universe@184 90 set(value) {
universe@184 91 field = value
universe@184 92 request.setAttribute(Constants.REQ_ATTR_NAVIGATION, navigationMenu)
universe@184 93 }
universe@184 94
universe@199 95 var redirectLocation: String? = null
universe@184 96 set(value) {
universe@184 97 field = value
universe@199 98 if (value == null) {
universe@199 99 request.removeAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION)
universe@199 100 } else {
universe@199 101 request.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, baseHref + value)
universe@199 102 }
universe@184 103 }
universe@184 104
universe@199 105 var feedPath: String? = null
universe@198 106 set(value) {
universe@198 107 field = value
universe@199 108 if (value == null) {
universe@199 109 request.removeAttribute(Constants.REQ_ATTR_FEED_HREF)
universe@199 110 } else {
universe@199 111 request.setAttribute(Constants.REQ_ATTR_FEED_HREF, baseHref + value)
universe@199 112 }
universe@198 113 }
universe@198 114
universe@184 115 /**
universe@184 116 * The view object.
universe@184 117 *
universe@184 118 * @see Constants#REQ_ATTR_VIEWMODEL
universe@184 119 */
universe@184 120 var view: View? = null
universe@184 121 set(value) {
universe@184 122 field = value
universe@184 123 request.setAttribute(Constants.REQ_ATTR_VIEWMODEL, value)
universe@184 124 }
universe@184 125
universe@184 126 /**
universe@198 127 * Additional port info, if necessary.
universe@198 128 */
universe@198 129 private val portInfo =
universe@198 130 if ((request.scheme == "http" && request.serverPort == 80)
universe@198 131 || (request.scheme == "https" && request.serverPort == 443)
universe@198 132 ) "" else ":${request.serverPort}"
universe@198 133
universe@198 134 /**
universe@184 135 * The base path of this application.
universe@184 136 */
universe@198 137 val baseHref get() = "${request.scheme}://${request.serverName}$portInfo${request.contextPath}/"
universe@198 138
universe@184 139 private fun String.withExt(ext: String) = if (endsWith(ext)) this else plus(ext)
universe@184 140 private fun jspPath(name: String) = Constants.JSP_PATH_PREFIX.plus(name).withExt(".jsp")
universe@184 141
universe@184 142 fun param(name: String): String? = request.getParameter(name)
universe@184 143 fun paramArray(name: String): Array<String> = request.getParameterValues(name) ?: emptyArray()
universe@184 144
universe@198 145 private fun forward(jsp: String) {
universe@195 146 request.getRequestDispatcher(jspPath(jsp)).forward(request, response)
universe@195 147 }
universe@195 148
universe@198 149 fun renderFeed(page: String? = null) {
universe@198 150 page?.let { contentPage = it }
universe@198 151 forward("feed")
universe@198 152 }
universe@198 153
universe@184 154 fun render(page: String? = null) {
universe@184 155 page?.let { contentPage = it }
universe@195 156 forward("site")
universe@184 157 }
universe@184 158
universe@184 159 fun renderCommit(location: String? = null) {
universe@184 160 location?.let { redirectLocation = it }
universe@184 161 contentPage = Constants.JSP_COMMIT_SUCCESSFUL
universe@184 162 render()
universe@184 163 }
universe@205 164
universe@205 165 fun i18n(key: String) = ResourceBundle.getBundle("localization/strings", response.locale).getString(key)
universe@184 166 }
universe@179 167
universe@179 168 /**
universe@179 169 * A path pattern optionally containing placeholders.
universe@179 170 *
universe@179 171 * The special directories . and .. are disallowed in the pattern.
universe@184 172 * Placeholders start with a % sign.
universe@179 173 *
universe@179 174 * @param pattern the pattern
universe@179 175 */
universe@179 176 class PathPattern(pattern: String) {
universe@179 177 private val nodePatterns: List<String>
universe@179 178 private val collection: Boolean
universe@179 179
universe@179 180 private fun parse(pattern: String): List<String> {
universe@179 181 val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
universe@179 182 require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
universe@179 183 return nodes
universe@179 184 }
universe@179 185
universe@179 186 /**
universe@179 187 * Matches a path against this pattern.
universe@179 188 * The path must be canonical in the sense that no . or .. parts occur.
universe@179 189 *
universe@179 190 * @param path the path to match
universe@179 191 * @return true if the path matches the pattern, false otherwise
universe@179 192 */
universe@179 193 fun matches(path: String): Boolean {
universe@179 194 if (collection xor path.endsWith("/")) return false
universe@179 195 val nodes = parse(path)
universe@179 196 if (nodePatterns.size != nodes.size) return false
universe@179 197 for (i in nodePatterns.indices) {
universe@179 198 val pattern = nodePatterns[i]
universe@179 199 val node = nodes[i]
universe@184 200 if (pattern.startsWith("%")) continue
universe@179 201 if (pattern != node) return false
universe@179 202 }
universe@179 203 return true
universe@179 204 }
universe@179 205
universe@179 206 /**
universe@179 207 * Returns the path parameters found in the specified path using this pattern.
universe@179 208 * The return value of this method is undefined, if the patter does not match.
universe@179 209 *
universe@179 210 * @param path the path
universe@179 211 * @return the path parameters, if any, or an empty map
universe@179 212 * @see .matches
universe@179 213 */
universe@179 214 fun obtainPathParameters(path: String): PathParameters {
universe@184 215 val params = mutableMapOf<String, String>()
universe@179 216 val nodes = parse(path)
universe@179 217 for (i in 0 until min(nodes.size, nodePatterns.size)) {
universe@179 218 val pattern = nodePatterns[i]
universe@179 219 val node = nodes[i]
universe@184 220 if (pattern.startsWith("%")) {
universe@179 221 params[pattern.substring(1)] = node
universe@179 222 }
universe@179 223 }
universe@179 224 return params
universe@179 225 }
universe@179 226
universe@179 227 override fun hashCode(): Int {
universe@179 228 val str = StringBuilder()
universe@179 229 for (node in nodePatterns) {
universe@184 230 if (node.startsWith("%")) {
universe@184 231 str.append("/%")
universe@179 232 } else {
universe@179 233 str.append('/')
universe@179 234 str.append(node)
universe@179 235 }
universe@179 236 }
universe@179 237 if (collection) str.append('/')
universe@179 238 return str.toString().hashCode()
universe@179 239 }
universe@179 240
universe@179 241 override fun equals(other: Any?): Boolean {
universe@179 242 if (other is PathPattern) {
universe@179 243 if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
universe@179 244 for (i in nodePatterns.indices) {
universe@179 245 val left = nodePatterns[i]
universe@179 246 val right = other.nodePatterns[i]
universe@184 247 if (left.startsWith("%") && right.startsWith("%")) continue
universe@179 248 if (left != right) return false
universe@179 249 }
universe@179 250 return true
universe@179 251 } else {
universe@179 252 return false
universe@179 253 }
universe@179 254 }
universe@179 255
universe@179 256 init {
universe@179 257 nodePatterns = parse(pattern)
universe@179 258 collection = pattern.endsWith("/")
universe@179 259 }
universe@179 260 }
universe@179 261

mercurial