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

Sat, 22 Jul 2023 22:32:04 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 22 Jul 2023 22:32:04 +0200
changeset 284
671c1c8fbf1c
parent 260
fb2ae2d63a56
child 292
703591e739f4
permissions
-rw-r--r--

add full support for commit references - fixes #276

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@254 31 import jakarta.servlet.http.HttpServletRequest
universe@254 32 import jakarta.servlet.http.HttpServletResponse
universe@254 33 import jakarta.servlet.http.HttpSession
universe@205 34 import java.util.*
universe@179 35 import kotlin.math.min
universe@225 36 import java.sql.Date as SqlDate
universe@179 37
universe@184 38 typealias MappingMethod = (HttpRequest, DataAccessObject) -> Unit
universe@184 39 typealias PathParameters = Map<String, String>
universe@184 40
universe@209 41 sealed interface ValidationResult<T>
universe@209 42 class ValidationError<T>(val message: String): ValidationResult<T>
universe@209 43 class ValidatedValue<T>(val result: T): ValidationResult<T>
universe@209 44
universe@184 45 class HttpRequest(
universe@184 46 val request: HttpServletRequest,
universe@184 47 val response: HttpServletResponse,
universe@184 48 val pathParams: PathParameters = emptyMap()
universe@184 49 ) {
universe@184 50 val session: HttpSession = request.session
universe@184 51
universe@184 52 val remoteUser: String? = request.remoteUser
universe@179 53
universe@179 54 /**
universe@184 55 * The name of the content page.
universe@179 56 *
universe@184 57 * @see Constants#REQ_ATTR_CONTENT_PAGE
universe@179 58 */
universe@184 59 var contentPage = ""
universe@184 60 set(value) {
universe@184 61 field = value
universe@184 62 request.setAttribute(Constants.REQ_ATTR_CONTENT_PAGE, jspPath(value))
universe@184 63 }
universe@179 64
universe@179 65 /**
universe@205 66 * The name of the content page.
universe@205 67 *
universe@207 68 * @see Constants#REQ_ATTR_PAGE_TITLE
universe@205 69 */
universe@205 70 var pageTitle = ""
universe@205 71 set(value) {
universe@205 72 field = value
universe@205 73 request.setAttribute(Constants.REQ_ATTR_PAGE_TITLE, value)
universe@205 74 }
universe@205 75
universe@205 76 /**
universe@184 77 * A list of additional style sheets.
universe@179 78 *
universe@184 79 * @see Constants#REQ_ATTR_STYLESHEET
universe@179 80 */
universe@184 81 var styleSheets = emptyList<String>()
universe@184 82 set(value) {
universe@184 83 field = value
universe@184 84 request.setAttribute(Constants.REQ_ATTR_STYLESHEET,
universe@184 85 value.map { it.withExt(".css") }
universe@184 86 )
universe@184 87 }
universe@179 88
universe@184 89 /**
universe@207 90 * A list of additional style sheets.
universe@207 91 *
universe@207 92 * @see Constants#REQ_ATTR_JAVASCRIPT
universe@207 93 */
universe@207 94 var javascript = ""
universe@207 95 set(value) {
universe@207 96 field = value
universe@207 97 request.setAttribute(Constants.REQ_ATTR_JAVASCRIPT,
universe@207 98 value.withExt(".js")
universe@207 99 )
universe@207 100 }
universe@207 101
universe@207 102 /**
universe@184 103 * The name of the navigation menu JSP.
universe@184 104 *
universe@184 105 * @see Constants#REQ_ATTR_NAVIGATION
universe@184 106 */
universe@184 107 var navigationMenu: NavMenu? = null
universe@184 108 set(value) {
universe@184 109 field = value
universe@184 110 request.setAttribute(Constants.REQ_ATTR_NAVIGATION, navigationMenu)
universe@184 111 }
universe@184 112
universe@199 113 var redirectLocation: String? = null
universe@184 114 set(value) {
universe@184 115 field = value
universe@199 116 if (value == null) {
universe@199 117 request.removeAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION)
universe@199 118 } else {
universe@199 119 request.setAttribute(Constants.REQ_ATTR_REDIRECT_LOCATION, baseHref + value)
universe@199 120 }
universe@184 121 }
universe@184 122
universe@199 123 var feedPath: String? = null
universe@198 124 set(value) {
universe@198 125 field = value
universe@199 126 if (value == null) {
universe@199 127 request.removeAttribute(Constants.REQ_ATTR_FEED_HREF)
universe@199 128 } else {
universe@199 129 request.setAttribute(Constants.REQ_ATTR_FEED_HREF, baseHref + value)
universe@199 130 }
universe@198 131 }
universe@198 132
universe@184 133 /**
universe@184 134 * The view object.
universe@184 135 *
universe@184 136 * @see Constants#REQ_ATTR_VIEWMODEL
universe@184 137 */
universe@184 138 var view: View? = null
universe@184 139 set(value) {
universe@184 140 field = value
universe@184 141 request.setAttribute(Constants.REQ_ATTR_VIEWMODEL, value)
universe@184 142 }
universe@184 143
universe@184 144 /**
universe@198 145 * Additional port info, if necessary.
universe@198 146 */
universe@198 147 private val portInfo =
universe@198 148 if ((request.scheme == "http" && request.serverPort == 80)
universe@198 149 || (request.scheme == "https" && request.serverPort == 443)
universe@198 150 ) "" else ":${request.serverPort}"
universe@198 151
universe@198 152 /**
universe@184 153 * The base path of this application.
universe@184 154 */
universe@198 155 val baseHref get() = "${request.scheme}://${request.serverName}$portInfo${request.contextPath}/"
universe@198 156
universe@184 157 private fun String.withExt(ext: String) = if (endsWith(ext)) this else plus(ext)
universe@184 158 private fun jspPath(name: String) = Constants.JSP_PATH_PREFIX.plus(name).withExt(".jsp")
universe@184 159
universe@184 160 fun param(name: String): String? = request.getParameter(name)
universe@184 161 fun paramArray(name: String): Array<String> = request.getParameterValues(name) ?: emptyArray()
universe@184 162
universe@210 163 fun <T> param(name: String, validator: (String?) -> (ValidationResult<T>),
universe@210 164 defaultValue: T, errorMessages: MutableList<String>): T {
universe@209 165 return when (val result = validator(param(name))) {
universe@209 166 is ValidationError -> {
universe@209 167 errorMessages.add(i18n(result.message))
universe@210 168 defaultValue
universe@209 169 }
universe@209 170 is ValidatedValue -> {
universe@209 171 result.result
universe@209 172 }
universe@209 173 }
universe@209 174 }
universe@209 175
universe@284 176 val body: String by lazy {
universe@284 177 request.reader.lineSequence().joinToString("\n")
universe@284 178 }
universe@284 179
universe@198 180 private fun forward(jsp: String) {
universe@195 181 request.getRequestDispatcher(jspPath(jsp)).forward(request, response)
universe@195 182 }
universe@195 183
universe@198 184 fun renderFeed(page: String? = null) {
universe@198 185 page?.let { contentPage = it }
universe@198 186 forward("feed")
universe@198 187 }
universe@198 188
universe@184 189 fun render(page: String? = null) {
universe@184 190 page?.let { contentPage = it }
universe@195 191 forward("site")
universe@184 192 }
universe@184 193
universe@184 194 fun renderCommit(location: String? = null) {
universe@184 195 location?.let { redirectLocation = it }
universe@184 196 contentPage = Constants.JSP_COMMIT_SUCCESSFUL
universe@184 197 render()
universe@184 198 }
universe@205 199
universe@260 200 fun i18n(key: String): String = ResourceBundle.getBundle("localization/strings", response.locale).getString(key)
universe@184 201 }
universe@179 202
universe@179 203 /**
universe@179 204 * A path pattern optionally containing placeholders.
universe@179 205 *
universe@179 206 * The special directories . and .. are disallowed in the pattern.
universe@184 207 * Placeholders start with a % sign.
universe@179 208 *
universe@179 209 * @param pattern the pattern
universe@179 210 */
universe@179 211 class PathPattern(pattern: String) {
universe@179 212 private val nodePatterns: List<String>
universe@179 213 private val collection: Boolean
universe@179 214
universe@179 215 private fun parse(pattern: String): List<String> {
universe@179 216 val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
universe@179 217 require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
universe@179 218 return nodes
universe@179 219 }
universe@179 220
universe@179 221 /**
universe@179 222 * Matches a path against this pattern.
universe@179 223 * The path must be canonical in the sense that no . or .. parts occur.
universe@179 224 *
universe@179 225 * @param path the path to match
universe@179 226 * @return true if the path matches the pattern, false otherwise
universe@179 227 */
universe@179 228 fun matches(path: String): Boolean {
universe@179 229 if (collection xor path.endsWith("/")) return false
universe@179 230 val nodes = parse(path)
universe@179 231 if (nodePatterns.size != nodes.size) return false
universe@179 232 for (i in nodePatterns.indices) {
universe@179 233 val pattern = nodePatterns[i]
universe@179 234 val node = nodes[i]
universe@184 235 if (pattern.startsWith("%")) continue
universe@179 236 if (pattern != node) return false
universe@179 237 }
universe@179 238 return true
universe@179 239 }
universe@179 240
universe@179 241 /**
universe@179 242 * Returns the path parameters found in the specified path using this pattern.
universe@179 243 * The return value of this method is undefined, if the patter does not match.
universe@179 244 *
universe@179 245 * @param path the path
universe@179 246 * @return the path parameters, if any, or an empty map
universe@179 247 * @see .matches
universe@179 248 */
universe@179 249 fun obtainPathParameters(path: String): PathParameters {
universe@184 250 val params = mutableMapOf<String, String>()
universe@179 251 val nodes = parse(path)
universe@179 252 for (i in 0 until min(nodes.size, nodePatterns.size)) {
universe@179 253 val pattern = nodePatterns[i]
universe@179 254 val node = nodes[i]
universe@184 255 if (pattern.startsWith("%")) {
universe@179 256 params[pattern.substring(1)] = node
universe@179 257 }
universe@179 258 }
universe@179 259 return params
universe@179 260 }
universe@179 261
universe@179 262 override fun hashCode(): Int {
universe@179 263 val str = StringBuilder()
universe@179 264 for (node in nodePatterns) {
universe@184 265 if (node.startsWith("%")) {
universe@184 266 str.append("/%")
universe@179 267 } else {
universe@179 268 str.append('/')
universe@179 269 str.append(node)
universe@179 270 }
universe@179 271 }
universe@179 272 if (collection) str.append('/')
universe@179 273 return str.toString().hashCode()
universe@179 274 }
universe@179 275
universe@179 276 override fun equals(other: Any?): Boolean {
universe@179 277 if (other is PathPattern) {
universe@179 278 if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
universe@179 279 for (i in nodePatterns.indices) {
universe@179 280 val left = nodePatterns[i]
universe@179 281 val right = other.nodePatterns[i]
universe@184 282 if (left.startsWith("%") && right.startsWith("%")) continue
universe@179 283 if (left != right) return false
universe@179 284 }
universe@179 285 return true
universe@179 286 } else {
universe@179 287 return false
universe@179 288 }
universe@179 289 }
universe@179 290
universe@179 291 init {
universe@179 292 nodePatterns = parse(pattern)
universe@179 293 collection = pattern.endsWith("/")
universe@179 294 }
universe@179 295 }
universe@179 296
universe@225 297 // <editor-fold desc="Validators">
universe@225 298
universe@225 299 fun dateOptValidator(input: String?): ValidationResult<SqlDate?> {
universe@225 300 return if (input.isNullOrBlank()) {
universe@225 301 ValidatedValue(null)
universe@225 302 } else {
universe@225 303 try {
universe@225 304 ValidatedValue(SqlDate.valueOf(input))
universe@225 305 } catch (ignored: IllegalArgumentException) {
universe@225 306 ValidationError("validation.date.format")
universe@225 307 }
universe@225 308 }
universe@225 309 }
universe@225 310
universe@227 311 fun boolValidator(input: String?): ValidationResult<Boolean> {
universe@227 312 return if (input.isNullOrBlank()) {
universe@227 313 ValidatedValue(false)
universe@227 314 } else {
universe@227 315 ValidatedValue(!(input.equals("false", true) || input == "0"))
universe@227 316 }
universe@227 317 }
universe@227 318
universe@225 319 // </editor-fold>

mercurial