src/main/kotlin/de/uapcore/lightpit/servlet/ProjectServlet.kt

Mon, 09 Aug 2021 16:25:50 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 09 Aug 2021 16:25:50 +0200
changeset 215
028792eda9b7
parent 214
69647ddb57f2
child 225
87328572e36f
permissions
-rw-r--r--

#156 fixes auto-selection overriding issue data

     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     private sealed interface LookupResult<T>
   107     private class NotFound<T> : LookupResult<T>
   108     private data class Found<T>(val elem: T?) : LookupResult<T>
   110     private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
   111         val node = pathParams[paramName]
   112         return if (node == null || node == "-") {
   113             Found(null)
   114         } else {
   115             val result = list.find { it.node == node }
   116             if (result == null) {
   117                 NotFound()
   118             } else {
   119                 Found(result)
   120             }
   121         }
   122     }
   124     private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
   125         val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
   127         val versions: List<Version> = dao.listVersions(project)
   128         val components: List<Component> = dao.listComponents(project)
   130         return ProjectInfo(
   131             project,
   132             versions,
   133             components,
   134             dao.collectIssueSummary(project)
   135         )
   136     }
   138     private fun sanitizeNode(name: String): String {
   139         val san = name.replace(Regex("[/\\\\]"), "-")
   140         return if (san.startsWith(".")) {
   141             "v$san"
   142         } else {
   143             san
   144         }
   145     }
   147     private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
   149     private data class PathInfos(
   150         val projectInfo: ProjectInfo,
   151         val version: Version?,
   152         val component: Component?
   153     ) {
   154         val project = projectInfo.project
   155         val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
   156     }
   158     private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
   159         val projectInfo = obtainProjectInfo(http, dao)
   160         if (projectInfo == null) {
   161             http.response.sendError(404)
   162             return null
   163         }
   165         val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   166             is NotFound -> {
   167                 http.response.sendError(404)
   168                 return null
   169             }
   170             is Found -> {
   171                 result.elem
   172             }
   173         }
   174         val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
   175             is NotFound -> {
   176                 http.response.sendError(404)
   177                 return null
   178             }
   179             is Found -> {
   180                 result.elem
   181             }
   182         }
   184         return PathInfos(projectInfo, version, component)
   185     }
   187     private fun project(http: HttpRequest, dao: DataAccessObject) {
   188         withPathInfo(http, dao)?.run {
   190             val issues = dao.listIssues(IssueFilter(
   191                 project = SpecificFilter(project),
   192                 version = version?.let { SpecificFilter(it) } ?: AllFilter(),
   193                 component = component?.let { SpecificFilter(it) } ?: AllFilter()
   194             )).sortedWith(DEFAULT_ISSUE_SORTER)
   196             with(http) {
   197                 pageTitle = project.name
   198                 view = ProjectDetails(projectInfo, issues, version, component)
   199                 feedPath = feedPath(project)
   200                 navigationMenu = activeProjectNavMenu(
   201                     dao.listProjects(),
   202                     projectInfo,
   203                     version,
   204                     component
   205                 )
   206                 styleSheets = listOf("projects")
   207                 render("project-details")
   208             }
   209         }
   210     }
   212     private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
   213         if (!http.pathParams.containsKey("project")) {
   214             http.view = ProjectEditView(Project(-1), dao.listUsers())
   215             http.navigationMenu = projectNavMenu(dao.listProjects())
   216         } else {
   217             val projectInfo = obtainProjectInfo(http, dao)
   218             if (projectInfo == null) {
   219                 http.response.sendError(404)
   220                 return
   221             }
   222             http.view = ProjectEditView(projectInfo.project, dao.listUsers())
   223             http.navigationMenu = activeProjectNavMenu(
   224                 dao.listProjects(),
   225                 projectInfo
   226             )
   227         }
   228         http.styleSheets = listOf("projects")
   229         http.render("project-form")
   230     }
   232     private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
   233         val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
   234             name = http.param("name") ?: ""
   235             node = http.param("node") ?: ""
   236             description = http.param("description") ?: ""
   237             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   238             repoUrl = http.param("repoUrl") ?: ""
   239             owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
   240                 if (it < 0) null else dao.findUser(it)
   241             }
   242             // intentional defaults
   243             if (node.isBlank()) node = name
   244             // sanitizing
   245             node = sanitizeNode(node)
   246         }
   248         if (project.id < 0) {
   249             dao.insertProject(project)
   250         } else {
   251             dao.updateProject(project)
   252         }
   254         http.renderCommit("projects/${project.node}")
   255     }
   257     private fun versions(http: HttpRequest, dao: DataAccessObject) {
   258         val projectInfo = obtainProjectInfo(http, dao)
   259         if (projectInfo == null) {
   260             http.response.sendError(404)
   261             return
   262         }
   264         with(http) {
   265             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
   266             view = VersionsView(
   267                 projectInfo,
   268                 dao.listVersionSummaries(projectInfo.project)
   269             )
   270             feedPath = feedPath(projectInfo.project)
   271             navigationMenu = activeProjectNavMenu(
   272                 dao.listProjects(),
   273                 projectInfo
   274             )
   275             styleSheets = listOf("projects")
   276             render("versions")
   277         }
   278     }
   280     private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
   281         val projectInfo = obtainProjectInfo(http, dao)
   282         if (projectInfo == null) {
   283             http.response.sendError(404)
   284             return
   285         }
   287         val version: Version
   288         when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   289             is NotFound -> {
   290                 http.response.sendError(404)
   291                 return
   292             }
   293             is Found -> {
   294                 version = result.elem ?: Version(-1, projectInfo.project.id)
   295             }
   296         }
   298         with(http) {
   299             view = VersionEditView(projectInfo, version)
   300             feedPath = feedPath(projectInfo.project)
   301             navigationMenu = activeProjectNavMenu(
   302                 dao.listProjects(),
   303                 projectInfo,
   304                 selectedVersion = version
   305             )
   306             styleSheets = listOf("projects")
   307             render("version-form")
   308         }
   309     }
   311     private fun obtainIdAndProject(http: HttpRequest, dao:DataAccessObject): Pair<Int, Project>? {
   312         val id = http.param("id")?.toIntOrNull()
   313         val projectid = http.param("projectid")?.toIntOrNull() ?: -1
   314         val project = dao.findProject(projectid)
   315         return if (id == null || project == null) {
   316             http.response.sendError(400)
   317             null
   318         } else {
   319             Pair(id, project)
   320         }
   321     }
   323     private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
   324         val idParams = obtainIdAndProject(http, dao) ?: return
   325         val (id, project) = idParams
   327         val version = Version(id, project.id).apply {
   328             name = http.param("name") ?: ""
   329             node = http.param("node") ?: ""
   330             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   331             status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
   332             // intentional defaults
   333             if (node.isBlank()) node = name
   334             // sanitizing
   335             node = sanitizeNode(node)
   336         }
   338         if (id < 0) {
   339             dao.insertVersion(version)
   340         } else {
   341             dao.updateVersion(version)
   342         }
   344         http.renderCommit("projects/${project.node}/versions/")
   345     }
   347     private fun components(http: HttpRequest, dao: DataAccessObject) {
   348         val projectInfo = obtainProjectInfo(http, dao)
   349         if (projectInfo == null) {
   350             http.response.sendError(404)
   351             return
   352         }
   354         with(http) {
   355             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
   356             view = ComponentsView(
   357                 projectInfo,
   358                 dao.listComponentSummaries(projectInfo.project)
   359             )
   360             feedPath = feedPath(projectInfo.project)
   361             navigationMenu = activeProjectNavMenu(
   362                 dao.listProjects(),
   363                 projectInfo
   364             )
   365             styleSheets = listOf("projects")
   366             render("components")
   367         }
   368     }
   370     private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
   371         val projectInfo = obtainProjectInfo(http, dao)
   372         if (projectInfo == null) {
   373             http.response.sendError(404)
   374             return
   375         }
   377         val component: Component
   378         when (val result = http.lookupPathParam("component", projectInfo.components)) {
   379             is NotFound -> {
   380                 http.response.sendError(404)
   381                 return
   382             }
   383             is Found -> {
   384                 component = result.elem ?: Component(-1, projectInfo.project.id)
   385             }
   386         }
   388         with(http) {
   389             view = ComponentEditView(projectInfo, component, dao.listUsers())
   390             feedPath = feedPath(projectInfo.project)
   391             navigationMenu = activeProjectNavMenu(
   392                 dao.listProjects(),
   393                 projectInfo,
   394                 selectedComponent = component
   395             )
   396             styleSheets = listOf("projects")
   397             render("component-form")
   398         }
   399     }
   401     private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
   402         val idParams = obtainIdAndProject(http, dao) ?: return
   403         val (id, project) = idParams
   405         val component = Component(id, project.id).apply {
   406             name = http.param("name") ?: ""
   407             node = http.param("node") ?: ""
   408             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   409             color = WebColor(http.param("color") ?: "#000000")
   410             description = http.param("description")
   411             lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
   412                 if (it < 0) null else dao.findUser(it)
   413             }
   414             // intentional defaults
   415             if (node.isBlank()) node = name
   416             // sanitizing
   417             node = sanitizeNode(node)
   418         }
   420         if (id < 0) {
   421             dao.insertComponent(component)
   422         } else {
   423             dao.updateComponent(component)
   424         }
   426         http.renderCommit("projects/${project.node}/components/")
   427     }
   429     private fun issue(http: HttpRequest, dao: DataAccessObject) {
   430         withPathInfo(http, dao)?.run {
   431             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   432             if (issue == null) {
   433                 http.response.sendError(404)
   434                 return
   435             }
   437             val comments = dao.listComments(issue)
   439             with(http) {
   440                 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
   441                 view = IssueDetailView(issue, comments, project, version, component)
   442                 feedPath = feedPath(projectInfo.project)
   443                 navigationMenu = activeProjectNavMenu(
   444                     dao.listProjects(),
   445                     projectInfo,
   446                     version,
   447                     component
   448                 )
   449                 styleSheets = listOf("projects")
   450                 javascript = "issue-editor"
   451                 render("issue-view")
   452             }
   453         }
   454     }
   456     private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
   457         withPathInfo(http, dao)?.run {
   458             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1) ?: Issue(
   459                 -1,
   460                 project,
   461             )
   463             // for new issues set some defaults
   464             if (issue.id < 0) {
   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                 }
   476             }
   478             with(http) {
   479                 view = IssueEditView(
   480                     issue,
   481                     projectInfo.versions,
   482                     projectInfo.components,
   483                     dao.listUsers(),
   484                     project,
   485                     version,
   486                     component
   487                 )
   488                 feedPath = feedPath(projectInfo.project)
   489                 navigationMenu = activeProjectNavMenu(
   490                     dao.listProjects(),
   491                     projectInfo,
   492                     version,
   493                     component
   494                 )
   495                 styleSheets = listOf("projects")
   496                 javascript = "issue-editor"
   497                 render("issue-form")
   498             }
   499         }
   500     }
   502     private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
   503         withPathInfo(http, dao)?.run {
   504             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   505             if (issue == null) {
   506                 http.response.sendError(404)
   507                 return
   508             }
   510             val commentId = http.param("commentid")?.toIntOrNull() ?: -1
   511             if (commentId > 0) {
   512                 val comment = dao.findComment(commentId)
   513                 val originalAuthor = comment?.author?.username
   514                 if (originalAuthor != null && originalAuthor == http.remoteUser) {
   515                     comment.comment = http.param("comment") ?: ""
   516                     dao.updateComment(comment)
   517                 } else {
   518                     http.response.sendError(403)
   519                     return
   520                 }
   521             } else {
   522                 val comment = IssueComment(-1, issue.id).apply {
   523                     author = http.remoteUser?.let { dao.findUserByName(it) }
   524                     comment = http.param("comment") ?: ""
   525                 }
   526                 dao.insertComment(comment)
   527             }
   529             http.renderCommit("${issuesHref}${issue.id}")
   530         }
   531     }
   533     private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
   534         withPathInfo(http, dao)?.run {
   535             val issue = Issue(
   536                 http.param("id")?.toIntOrNull() ?: -1,
   537                 project
   538             ).apply {
   539                 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
   540                 category = IssueCategory.valueOf(http.param("category") ?: "")
   541                 status = IssueStatus.valueOf(http.param("status") ?: "")
   542                 subject = http.param("subject") ?: ""
   543                 description = http.param("description") ?: ""
   544                 assignee = http.param("assignee")?.toIntOrNull()?.let {
   545                     when (it) {
   546                         -1 -> null
   547                         -2 -> component?.lead
   548                         else -> dao.findUser(it)
   549                     }
   550                 }
   551                 eta = http.param("eta")?.let { if (it.isBlank()) null else Date.valueOf(it) }
   553                 affectedVersions = http.paramArray("affected")
   554                     .mapNotNull { param -> param.toIntOrNull()?.let { Version(it, project.id) } }
   555                 resolvedVersions = http.paramArray("resolved")
   556                     .mapNotNull { param -> param.toIntOrNull()?.let { Version(it, project.id) } }
   557             }
   559             val openId = if (issue.id < 0) {
   560                 dao.insertIssue(issue)
   561             } else {
   562                 dao.updateIssue(issue)
   563                 val newComment = http.param("comment")
   564                 if (!newComment.isNullOrBlank()) {
   565                     dao.insertComment(IssueComment(-1, issue.id).apply {
   566                         author = http.remoteUser?.let { dao.findUserByName(it) }
   567                         comment = newComment
   568                     })
   569                 }
   570                 issue.id
   571             }
   573             if (http.param("more") != null) {
   574                 http.renderCommit("${issuesHref}-/create")
   575             } else {
   576                 http.renderCommit("${issuesHref}${openId}")
   577             }
   578         }
   579     }
   580 }

mercurial