src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.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 200
a5ddfaf6b469
child 207
479dd7993ef9
permissions
-rw-r--r--

#115 adds custom page titles

     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.servlet
    28 import de.uapcore.lightpit.AbstractServlet
    29 import de.uapcore.lightpit.HttpRequest
    30 import de.uapcore.lightpit.dao.DataAccessObject
    31 import de.uapcore.lightpit.entities.*
    32 import de.uapcore.lightpit.types.IssueCategory
    33 import de.uapcore.lightpit.types.IssueStatus
    34 import de.uapcore.lightpit.types.VersionStatus
    35 import de.uapcore.lightpit.types.WebColor
    36 import de.uapcore.lightpit.util.AllFilter
    37 import de.uapcore.lightpit.util.IssueFilter
    38 import de.uapcore.lightpit.util.IssueSorter.Companion.DEFAULT_ISSUE_SORTER
    39 import de.uapcore.lightpit.util.SpecificFilter
    40 import de.uapcore.lightpit.viewmodel.*
    41 import java.sql.Date
    42 import javax.servlet.annotation.WebServlet
    44 @WebServlet(urlPatterns = ["/projects/*"])
    45 class ProjectServlet : AbstractServlet() {
    47     init {
    48         get("/", this::projects)
    49         get("/%project", this::project)
    50         get("/%project/issues/%version/%component/", this::project)
    51         get("/%project/edit", this::projectForm)
    52         get("/-/create", this::projectForm)
    53         post("/-/commit", this::projectCommit)
    55         get("/%project/versions/", this::versions)
    56         get("/%project/versions/%version/edit", this::versionForm)
    57         get("/%project/versions/-/create", this::versionForm)
    58         post("/%project/versions/-/commit", this::versionCommit)
    60         get("/%project/components/", this::components)
    61         get("/%project/components/%component/edit", this::componentForm)
    62         get("/%project/components/-/create", this::componentForm)
    63         post("/%project/components/-/commit", this::componentCommit)
    65         get("/%project/issues/%version/%component/%issue", this::issue)
    66         get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
    67         post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
    68         get("/%project/issues/%version/%component/-/create", this::issueForm)
    69         post("/%project/issues/%version/%component/-/commit", this::issueCommit)
    70     }
    72     private fun projects(http: HttpRequest, dao: DataAccessObject) {
    73         val projects = dao.listProjects()
    74         val projectInfos = projects.map {
    75             ProjectInfo(
    76                 project = it,
    77                 versions = dao.listVersions(it),
    78                 components = emptyList(), // not required in this view
    79                 issueSummary = dao.collectIssueSummary(it)
    80             )
    81         }
    83         with(http) {
    84             view = ProjectsView(projectInfos)
    85             navigationMenu = projectNavMenu(projects)
    86             styleSheets = listOf("projects")
    87             render("projects")
    88         }
    89     }
    91     private fun activeProjectNavMenu(
    92         projects: List<Project>,
    93         projectInfo: ProjectInfo,
    94         selectedVersion: Version? = null,
    95         selectedComponent: Component? = null
    96     ) =
    97         projectNavMenu(
    98             projects,
    99             projectInfo.versions,
   100             projectInfo.components,
   101             projectInfo.project,
   102             selectedVersion,
   103             selectedComponent
   104         )
   106     sealed class LookupResult<T> {
   107         class NotFound<T> : LookupResult<T>()
   108         data class Found<T>(val elem: T?) : LookupResult<T>()
   109     }
   111     private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
   112         val node = pathParams[paramName]
   113         return if (node == null || node == "-") {
   114             LookupResult.Found(null)
   115         } else {
   116             val result = list.find { it.node == node }
   117             if (result == null) {
   118                 LookupResult.NotFound()
   119             } else {
   120                 LookupResult.Found(result)
   121             }
   122         }
   123     }
   125     private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
   126         val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
   128         val versions: List<Version> = dao.listVersions(project)
   129         val components: List<Component> = dao.listComponents(project)
   131         return ProjectInfo(
   132             project,
   133             versions,
   134             components,
   135             dao.collectIssueSummary(project)
   136         )
   137     }
   139     private fun sanitizeNode(name: String): String {
   140         val san = name.replace(Regex("[/\\\\]"), "-")
   141         return if (san.startsWith(".")) {
   142             "v$san"
   143         } else {
   144             san
   145         }
   146     }
   148     private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
   150     data class PathInfos(
   151         val projectInfo: ProjectInfo,
   152         val version: Version?,
   153         val component: Component?
   154     ) {
   155         val project = projectInfo.project
   156         val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
   157     }
   159     private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
   160         val projectInfo = obtainProjectInfo(http, dao)
   161         if (projectInfo == null) {
   162             http.response.sendError(404)
   163             return null
   164         }
   166         val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   167             is LookupResult.NotFound -> {
   168                 http.response.sendError(404)
   169                 return null
   170             }
   171             is LookupResult.Found -> {
   172                 result.elem
   173             }
   174         }
   175         val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
   176             is LookupResult.NotFound -> {
   177                 http.response.sendError(404)
   178                 return null
   179             }
   180             is LookupResult.Found -> {
   181                 result.elem
   182             }
   183         }
   185         return PathInfos(projectInfo, version, component)
   186     }
   188     private fun project(http: HttpRequest, dao: DataAccessObject) {
   189         withPathInfo(http, dao)?.run {
   191             val issues = dao.listIssues(IssueFilter(
   192                 project = SpecificFilter(project),
   193                 version = version?.let { SpecificFilter(it) } ?: AllFilter(),
   194                 component = component?.let { SpecificFilter(it) } ?: AllFilter()
   195             )).sortedWith(DEFAULT_ISSUE_SORTER)
   197             with(http) {
   198                 pageTitle = project.name
   199                 view = ProjectDetails(projectInfo, issues, version, component)
   200                 feedPath = feedPath(project)
   201                 navigationMenu = activeProjectNavMenu(
   202                     dao.listProjects(),
   203                     projectInfo,
   204                     version,
   205                     component
   206                 )
   207                 styleSheets = listOf("projects")
   208                 render("project-details")
   209             }
   210         }
   211     }
   213     private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
   214         if (!http.pathParams.containsKey("project")) {
   215             http.view = ProjectEditView(Project(-1), dao.listUsers())
   216             http.navigationMenu = projectNavMenu(dao.listProjects())
   217         } else {
   218             val projectInfo = obtainProjectInfo(http, dao)
   219             if (projectInfo == null) {
   220                 http.response.sendError(404)
   221                 return
   222             }
   223             http.view = ProjectEditView(projectInfo.project, dao.listUsers())
   224             http.navigationMenu = activeProjectNavMenu(
   225                 dao.listProjects(),
   226                 projectInfo
   227             )
   228         }
   229         http.styleSheets = listOf("projects")
   230         http.render("project-form")
   231     }
   233     private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
   234         // TODO: replace defaults with throwing validator exceptions
   235         val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
   236             name = http.param("name") ?: ""
   237             node = http.param("node") ?: ""
   238             description = http.param("description") ?: ""
   239             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   240             repoUrl = http.param("repoUrl") ?: ""
   241             owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
   242                 if (it < 0) null else dao.findUser(it)
   243             }
   244             // intentional defaults
   245             if (node.isBlank()) node = name
   246             // sanitizing
   247             node = sanitizeNode(node)
   248         }
   250         if (project.id < 0) {
   251             dao.insertProject(project)
   252         } else {
   253             dao.updateProject(project)
   254         }
   256         http.renderCommit("projects/${project.node}")
   257     }
   259     private fun versions(http: HttpRequest, dao: DataAccessObject) {
   260         val projectInfo = obtainProjectInfo(http, dao)
   261         if (projectInfo == null) {
   262             http.response.sendError(404)
   263             return
   264         }
   266         with(http) {
   267             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
   268             view = VersionsView(
   269                 projectInfo,
   270                 dao.listVersionSummaries(projectInfo.project)
   271             )
   272             feedPath = feedPath(projectInfo.project)
   273             navigationMenu = activeProjectNavMenu(
   274                 dao.listProjects(),
   275                 projectInfo
   276             )
   277             styleSheets = listOf("projects")
   278             render("versions")
   279         }
   280     }
   282     private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
   283         val projectInfo = obtainProjectInfo(http, dao)
   284         if (projectInfo == null) {
   285             http.response.sendError(404)
   286             return
   287         }
   289         val version: Version
   290         when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   291             is LookupResult.NotFound -> {
   292                 http.response.sendError(404)
   293                 return
   294             }
   295             is LookupResult.Found -> {
   296                 version = result.elem ?: Version(-1, projectInfo.project.id)
   297             }
   298         }
   300         with(http) {
   301             view = VersionEditView(projectInfo, version)
   302             feedPath = feedPath(projectInfo.project)
   303             navigationMenu = activeProjectNavMenu(
   304                 dao.listProjects(),
   305                 projectInfo,
   306                 selectedVersion = version
   307             )
   308             styleSheets = listOf("projects")
   309             render("version-form")
   310         }
   311     }
   313     private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
   314         val id = http.param("id")?.toIntOrNull()
   315         val projectid = http.param("projectid")?.toIntOrNull() ?: -1
   316         val project = dao.findProject(projectid)
   317         if (id == null || project == null) {
   318             http.response.sendError(400)
   319             return
   320         }
   322         // TODO: replace defaults with throwing validator exceptions
   323         val version = Version(id, projectid).apply {
   324             name = http.param("name") ?: ""
   325             node = http.param("node") ?: ""
   326             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   327             status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
   328             // intentional defaults
   329             if (node.isBlank()) node = name
   330             // sanitizing
   331             node = sanitizeNode(node)
   332         }
   334         if (id < 0) {
   335             dao.insertVersion(version)
   336         } else {
   337             dao.updateVersion(version)
   338         }
   340         http.renderCommit("projects/${project.node}/versions/")
   341     }
   343     private fun components(http: HttpRequest, dao: DataAccessObject) {
   344         val projectInfo = obtainProjectInfo(http, dao)
   345         if (projectInfo == null) {
   346             http.response.sendError(404)
   347             return
   348         }
   350         with(http) {
   351             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
   352             view = ComponentsView(
   353                 projectInfo,
   354                 dao.listComponentSummaries(projectInfo.project)
   355             )
   356             feedPath = feedPath(projectInfo.project)
   357             navigationMenu = activeProjectNavMenu(
   358                 dao.listProjects(),
   359                 projectInfo
   360             )
   361             styleSheets = listOf("projects")
   362             render("components")
   363         }
   364     }
   366     private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
   367         val projectInfo = obtainProjectInfo(http, dao)
   368         if (projectInfo == null) {
   369             http.response.sendError(404)
   370             return
   371         }
   373         val component: Component
   374         when (val result = http.lookupPathParam("component", projectInfo.components)) {
   375             is LookupResult.NotFound -> {
   376                 http.response.sendError(404)
   377                 return
   378             }
   379             is LookupResult.Found -> {
   380                 component = result.elem ?: Component(-1, projectInfo.project.id)
   381             }
   382         }
   384         with(http) {
   385             view = ComponentEditView(projectInfo, component, dao.listUsers())
   386             feedPath = feedPath(projectInfo.project)
   387             navigationMenu = activeProjectNavMenu(
   388                 dao.listProjects(),
   389                 projectInfo,
   390                 selectedComponent = component
   391             )
   392             styleSheets = listOf("projects")
   393             render("component-form")
   394         }
   395     }
   397     private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
   398         val id = http.param("id")?.toIntOrNull()
   399         val projectid = http.param("projectid")?.toIntOrNull() ?: -1
   400         val project = dao.findProject(projectid)
   401         if (id == null || project == null) {
   402             http.response.sendError(400)
   403             return
   404         }
   406         // TODO: replace defaults with throwing validator exceptions
   407         val component = Component(id, projectid).apply {
   408             name = http.param("name") ?: ""
   409             node = http.param("node") ?: ""
   410             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   411             color = WebColor(http.param("color") ?: "#000000")
   412             description = http.param("description")
   413             lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
   414                 if (it < 0) null else dao.findUser(it)
   415             }
   416             // intentional defaults
   417             if (node.isBlank()) node = name
   418             // sanitizing
   419             node = sanitizeNode(node)
   420         }
   422         if (id < 0) {
   423             dao.insertComponent(component)
   424         } else {
   425             dao.updateComponent(component)
   426         }
   428         http.renderCommit("projects/${project.node}/components/")
   429     }
   431     private fun issue(http: HttpRequest, dao: DataAccessObject) {
   432         withPathInfo(http, dao)?.run {
   433             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   434             if (issue == null) {
   435                 http.response.sendError(404)
   436                 return
   437             }
   439             val comments = dao.listComments(issue)
   441             with(http) {
   442                 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
   443                 view = IssueDetailView(issue, comments, project, version, component)
   444                 // TODO: feed path for this particular issue
   445                 feedPath = feedPath(projectInfo.project)
   446                 navigationMenu = activeProjectNavMenu(
   447                     dao.listProjects(),
   448                     projectInfo,
   449                     version,
   450                     component
   451                 )
   452                 styleSheets = listOf("projects")
   453                 render("issue-view")
   454             }
   455         }
   456     }
   458     private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
   459         withPathInfo(http, dao)?.run {
   460             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1) ?: Issue(
   461                 -1,
   462                 project,
   463             )
   465             // pre-select component, if available in the path info
   466             issue.component = component
   468             // pre-select version, if available in the path info
   469             if (version != null) {
   470                 if (version.status.isReleased) {
   471                     issue.affectedVersions = listOf(version)
   472                 } else {
   473                     issue.resolvedVersions = listOf(version)
   474                 }
   475             }
   477             with(http) {
   478                 view = IssueEditView(
   479                     issue,
   480                     projectInfo.versions,
   481                     projectInfo.components,
   482                     dao.listUsers(),
   483                     project,
   484                     version,
   485                     component
   486                 )
   487                 feedPath = feedPath(projectInfo.project)
   488                 navigationMenu = activeProjectNavMenu(
   489                     dao.listProjects(),
   490                     projectInfo,
   491                     version,
   492                     component
   493                 )
   494                 styleSheets = listOf("projects")
   495                 render("issue-form")
   496             }
   497         }
   498     }
   500     private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
   501         withPathInfo(http, dao)?.run {
   502             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   503             if (issue == null) {
   504                 http.response.sendError(404)
   505                 return
   506             }
   508             // TODO: throw validator exception instead of using a default
   509             val comment = IssueComment(-1, issue.id).apply {
   510                 author = http.remoteUser?.let { dao.findUserByName(it) }
   511                 comment = http.param("comment") ?: ""
   512             }
   514             dao.insertComment(comment)
   516             http.renderCommit("${issuesHref}${issue.id}")
   517         }
   518     }
   520     private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
   521         withPathInfo(http, dao)?.run {
   522             // TODO: throw validator exception instead of using defaults
   523             val issue = Issue(
   524                 http.param("id")?.toIntOrNull() ?: -1,
   525                 project
   526             ).apply {
   527                 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
   528                 category = IssueCategory.valueOf(http.param("category") ?: "")
   529                 status = IssueStatus.valueOf(http.param("status") ?: "")
   530                 subject = http.param("subject") ?: ""
   531                 description = http.param("description") ?: ""
   532                 assignee = http.param("assignee")?.toIntOrNull()?.let {
   533                     when (it) {
   534                         -1 -> null
   535                         -2 -> component?.lead
   536                         else -> dao.findUser(it)
   537                     }
   538                 }
   539                 eta = http.param("eta")?.let { if (it.isBlank()) null else Date.valueOf(it) }
   541                 affectedVersions = http.paramArray("affected")
   542                     .mapNotNull { param -> param.toIntOrNull()?.let { Version(it, project.id) } }
   543                 resolvedVersions = http.paramArray("resolved")
   544                     .mapNotNull { param -> param.toIntOrNull()?.let { Version(it, project.id) } }
   545             }
   547             val openId = if (issue.id < 0) {
   548                 dao.insertIssue(issue)
   549             } else {
   550                 dao.updateIssue(issue)
   551                 issue.id
   552             }
   554             if (http.param("more") != null) {
   555                 http.renderCommit("${issuesHref}-/create")
   556             } else {
   557                 http.renderCommit("${issuesHref}${openId}")
   558             }
   559         }
   560     }
   561 }

mercurial