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

Fri, 02 Apr 2021 11:59:14 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 02 Apr 2021 11:59:14 +0200
changeset 184
e8eecee6aadf
parent 179
623c340058f3
child 195
9c7aff3cbb14
permissions
-rw-r--r--

completes kotlin migration

     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 render(page: String? = null) {
   112         page?.let { contentPage = it }
   113         request.getRequestDispatcher(jspPath("site")).forward(request, response)
   114     }
   116     fun renderCommit(location: String? = null) {
   117         location?.let { redirectLocation = it }
   118         contentPage = Constants.JSP_COMMIT_SUCCESSFUL
   119         render()
   120     }
   121 }
   123 /**
   124  * A path pattern optionally containing placeholders.
   125  *
   126  * The special directories . and .. are disallowed in the pattern.
   127  * Placeholders start with a % sign.
   128  *
   129  * @param pattern the pattern
   130  */
   131 class PathPattern(pattern: String) {
   132     private val nodePatterns: List<String>
   133     private val collection: Boolean
   135     private fun parse(pattern: String): List<String> {
   136         val nodes = pattern.split("/").filter { it.isNotBlank() }.toList()
   137         require(nodes.none { it == "." || it == ".." }) { "Path must not contain '.' or '..' nodes." }
   138         return nodes
   139     }
   141     /**
   142      * Matches a path against this pattern.
   143      * The path must be canonical in the sense that no . or .. parts occur.
   144      *
   145      * @param path the path to match
   146      * @return true if the path matches the pattern, false otherwise
   147      */
   148     fun matches(path: String): Boolean {
   149         if (collection xor path.endsWith("/")) return false
   150         val nodes = parse(path)
   151         if (nodePatterns.size != nodes.size) return false
   152         for (i in nodePatterns.indices) {
   153             val pattern = nodePatterns[i]
   154             val node = nodes[i]
   155             if (pattern.startsWith("%")) continue
   156             if (pattern != node) return false
   157         }
   158         return true
   159     }
   161     /**
   162      * Returns the path parameters found in the specified path using this pattern.
   163      * The return value of this method is undefined, if the patter does not match.
   164      *
   165      * @param path the path
   166      * @return the path parameters, if any, or an empty map
   167      * @see .matches
   168      */
   169     fun obtainPathParameters(path: String): PathParameters {
   170         val params = mutableMapOf<String, String>()
   171         val nodes = parse(path)
   172         for (i in 0 until min(nodes.size, nodePatterns.size)) {
   173             val pattern = nodePatterns[i]
   174             val node = nodes[i]
   175             if (pattern.startsWith("%")) {
   176                 params[pattern.substring(1)] = node
   177             }
   178         }
   179         return params
   180     }
   182     override fun hashCode(): Int {
   183         val str = StringBuilder()
   184         for (node in nodePatterns) {
   185             if (node.startsWith("%")) {
   186                 str.append("/%")
   187             } else {
   188                 str.append('/')
   189                 str.append(node)
   190             }
   191         }
   192         if (collection) str.append('/')
   193         return str.toString().hashCode()
   194     }
   196     override fun equals(other: Any?): Boolean {
   197         if (other is PathPattern) {
   198             if (collection xor other.collection || nodePatterns.size != other.nodePatterns.size) return false
   199             for (i in nodePatterns.indices) {
   200                 val left = nodePatterns[i]
   201                 val right = other.nodePatterns[i]
   202                 if (left.startsWith("%") && right.startsWith("%")) continue
   203                 if (left != right) return false
   204             }
   205             return true
   206         } else {
   207             return false
   208         }
   209     }
   211     init {
   212         nodePatterns = parse(pattern)
   213         collection = pattern.endsWith("/")
   214     }
   215 }

mercurial