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

Wed, 15 Dec 2021 19:56:05 +0100

author
Mike Becker <universe@uap-core.de>
date
Wed, 15 Dec 2021 19:56:05 +0100
changeset 247
e71ae69c68c0
parent 242
b7f3e972b13c
child 248
90dc13c78b5d
permissions
-rw-r--r--

remove log4j entirely

     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.boolValidator
    31 import de.uapcore.lightpit.dao.DataAccessObject
    32 import de.uapcore.lightpit.dateOptValidator
    33 import de.uapcore.lightpit.entities.*
    34 import de.uapcore.lightpit.types.IssueCategory
    35 import de.uapcore.lightpit.types.IssueStatus
    36 import de.uapcore.lightpit.types.VersionStatus
    37 import de.uapcore.lightpit.types.WebColor
    38 import de.uapcore.lightpit.util.AllFilter
    39 import de.uapcore.lightpit.util.IssueFilter
    40 import de.uapcore.lightpit.util.IssueSorter.Companion.DEFAULT_ISSUE_SORTER
    41 import de.uapcore.lightpit.util.SpecificFilter
    42 import de.uapcore.lightpit.viewmodel.*
    43 import java.sql.Date
    44 import javax.servlet.annotation.WebServlet
    46 @WebServlet(urlPatterns = ["/projects/*"])
    47 class ProjectServlet : AbstractServlet() {
    49     init {
    50         get("/", this::projects)
    51         get("/%project", this::project)
    52         get("/%project/issues/%version/%component/", this::project)
    53         get("/%project/edit", this::projectForm)
    54         get("/-/create", this::projectForm)
    55         post("/-/commit", this::projectCommit)
    57         get("/%project/versions/", this::versions)
    58         get("/%project/versions/%version/edit", this::versionForm)
    59         get("/%project/versions/-/create", this::versionForm)
    60         post("/%project/versions/-/commit", this::versionCommit)
    62         get("/%project/components/", this::components)
    63         get("/%project/components/%component/edit", this::componentForm)
    64         get("/%project/components/-/create", this::componentForm)
    65         post("/%project/components/-/commit", this::componentCommit)
    67         get("/%project/issues/%version/%component/%issue", this::issue)
    68         get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
    69         post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
    70         get("/%project/issues/%version/%component/-/create", this::issueForm)
    71         post("/%project/issues/%version/%component/-/commit", this::issueCommit)
    72     }
    74     private fun projects(http: HttpRequest, dao: DataAccessObject) {
    75         val projects = dao.listProjects()
    76         val projectInfos = projects.map {
    77             ProjectInfo(
    78                 project = it,
    79                 versions = dao.listVersions(it),
    80                 components = emptyList(), // not required in this view
    81                 issueSummary = dao.collectIssueSummary(it)
    82             )
    83         }
    85         with(http) {
    86             view = ProjectsView(projectInfos)
    87             navigationMenu = projectNavMenu(projects)
    88             styleSheets = listOf("projects")
    89             render("projects")
    90         }
    91     }
    93     private fun activeProjectNavMenu(
    94         projects: List<Project>,
    95         projectInfo: ProjectInfo,
    96         selectedVersion: Version? = null,
    97         selectedComponent: Component? = null
    98     ) =
    99         projectNavMenu(
   100             projects,
   101             projectInfo.versions,
   102             projectInfo.components,
   103             projectInfo.project,
   104             selectedVersion,
   105             selectedComponent
   106         )
   108     private sealed interface LookupResult<T>
   109     private class NotFound<T> : LookupResult<T>
   110     private data class Found<T>(val elem: T?) : LookupResult<T>
   112     private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
   113         val node = pathParams[paramName]
   114         return if (node == null || node == "-") {
   115             Found(null)
   116         } else {
   117             val result = list.find { it.node == node }
   118             if (result == null) {
   119                 NotFound()
   120             } else {
   121                 Found(result)
   122             }
   123         }
   124     }
   126     private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
   127         val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
   129         val versions: List<Version> = dao.listVersions(project)
   130         val components: List<Component> = dao.listComponents(project)
   132         return ProjectInfo(
   133             project,
   134             versions,
   135             components,
   136             dao.collectIssueSummary(project)
   137         )
   138     }
   140     private fun sanitizeNode(name: String): String {
   141         val san = name.replace(Regex("[/\\\\]"), "-")
   142         return if (san.startsWith(".")) {
   143             "v$san"
   144         } else {
   145             san
   146         }
   147     }
   149     private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
   151     private data class PathInfos(
   152         val projectInfo: ProjectInfo,
   153         val version: Version?,
   154         val component: Component?
   155     ) {
   156         val project = projectInfo.project
   157         val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
   158     }
   160     private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
   161         val projectInfo = obtainProjectInfo(http, dao)
   162         if (projectInfo == null) {
   163             http.response.sendError(404)
   164             return null
   165         }
   167         val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
   168             is NotFound -> {
   169                 http.response.sendError(404)
   170                 return null
   171             }
   172             is Found -> {
   173                 result.elem
   174             }
   175         }
   176         val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
   177             is NotFound -> {
   178                 http.response.sendError(404)
   179                 return null
   180             }
   181             is Found -> {
   182                 result.elem
   183             }
   184         }
   186         return PathInfos(projectInfo, version, component)
   187     }
   189     private fun project(http: HttpRequest, dao: DataAccessObject) {
   190         withPathInfo(http, dao)?.run {
   192             val issues = dao.listIssues(IssueFilter(
   193                 project = SpecificFilter(project),
   194                 version = version?.let { SpecificFilter(it) } ?: AllFilter(),
   195                 component = component?.let { SpecificFilter(it) } ?: AllFilter()
   196             )).sortedWith(DEFAULT_ISSUE_SORTER)
   198             with(http) {
   199                 pageTitle = project.name
   200                 view = ProjectDetails(projectInfo, issues, version, component)
   201                 feedPath = feedPath(project)
   202                 navigationMenu = activeProjectNavMenu(
   203                     dao.listProjects(),
   204                     projectInfo,
   205                     version,
   206                     component
   207                 )
   208                 styleSheets = listOf("projects")
   209                 render("project-details")
   210             }
   211         }
   212     }
   214     private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
   215         if (!http.pathParams.containsKey("project")) {
   216             http.view = ProjectEditView(Project(-1), dao.listUsers())
   217             http.navigationMenu = projectNavMenu(dao.listProjects())
   218         } else {
   219             val projectInfo = obtainProjectInfo(http, dao)
   220             if (projectInfo == null) {
   221                 http.response.sendError(404)
   222                 return
   223             }
   224             http.view = ProjectEditView(projectInfo.project, dao.listUsers())
   225             http.navigationMenu = activeProjectNavMenu(
   226                 dao.listProjects(),
   227                 projectInfo
   228             )
   229         }
   230         http.styleSheets = listOf("projects")
   231         http.render("project-form")
   232     }
   234     private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
   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 NotFound -> {
   292                 http.response.sendError(404)
   293                 return
   294             }
   295             is 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 obtainIdAndProject(http: HttpRequest, dao:DataAccessObject): Pair<Int, Project>? {
   314         val id = http.param("id")?.toIntOrNull()
   315         val projectid = http.param("projectid")?.toIntOrNull() ?: -1
   316         val project = dao.findProject(projectid)
   317         return if (id == null || project == null) {
   318             http.response.sendError(400)
   319             null
   320         } else {
   321             Pair(id, project)
   322         }
   323     }
   325     private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
   326         val idParams = obtainIdAndProject(http, dao) ?: return
   327         val (id, project) = idParams
   329         val version = Version(id, project.id).apply {
   330             name = http.param("name") ?: ""
   331             node = http.param("node") ?: ""
   332             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   333             status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
   334             // TODO: process error messages
   335             eol =  http.param("eol", ::dateOptValidator, null, mutableListOf())
   336             release =  http.param("release", ::dateOptValidator, null, mutableListOf())
   337             // intentional defaults
   338             if (node.isBlank()) node = name
   339             // sanitizing
   340             node = sanitizeNode(node)
   341         }
   343         // sanitize eol and release date
   344         if (version.status.isEndOfLife) {
   345             if (version.eol == null) version.eol = Date(System.currentTimeMillis())
   346         } else if (version.status.isReleased) {
   347             if (version.release == null) version.release = Date(System.currentTimeMillis())
   348         }
   350         if (id < 0) {
   351             dao.insertVersion(version)
   352         } else {
   353             dao.updateVersion(version)
   354         }
   356         http.renderCommit("projects/${project.node}/versions/")
   357     }
   359     private fun components(http: HttpRequest, dao: DataAccessObject) {
   360         val projectInfo = obtainProjectInfo(http, dao)
   361         if (projectInfo == null) {
   362             http.response.sendError(404)
   363             return
   364         }
   366         with(http) {
   367             pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
   368             view = ComponentsView(
   369                 projectInfo,
   370                 dao.listComponentSummaries(projectInfo.project)
   371             )
   372             feedPath = feedPath(projectInfo.project)
   373             navigationMenu = activeProjectNavMenu(
   374                 dao.listProjects(),
   375                 projectInfo
   376             )
   377             styleSheets = listOf("projects")
   378             render("components")
   379         }
   380     }
   382     private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
   383         val projectInfo = obtainProjectInfo(http, dao)
   384         if (projectInfo == null) {
   385             http.response.sendError(404)
   386             return
   387         }
   389         val component: Component
   390         when (val result = http.lookupPathParam("component", projectInfo.components)) {
   391             is NotFound -> {
   392                 http.response.sendError(404)
   393                 return
   394             }
   395             is Found -> {
   396                 component = result.elem ?: Component(-1, projectInfo.project.id)
   397             }
   398         }
   400         with(http) {
   401             view = ComponentEditView(projectInfo, component, dao.listUsers())
   402             feedPath = feedPath(projectInfo.project)
   403             navigationMenu = activeProjectNavMenu(
   404                 dao.listProjects(),
   405                 projectInfo,
   406                 selectedComponent = component
   407             )
   408             styleSheets = listOf("projects")
   409             render("component-form")
   410         }
   411     }
   413     private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
   414         val idParams = obtainIdAndProject(http, dao) ?: return
   415         val (id, project) = idParams
   417         val component = Component(id, project.id).apply {
   418             name = http.param("name") ?: ""
   419             node = http.param("node") ?: ""
   420             ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
   421             color = WebColor(http.param("color") ?: "#000000")
   422             description = http.param("description")
   423             // TODO: process error message
   424             active = http.param("active", ::boolValidator, true, mutableListOf())
   425             lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
   426                 if (it < 0) null else dao.findUser(it)
   427             }
   428             // intentional defaults
   429             if (node.isBlank()) node = name
   430             // sanitizing
   431             node = sanitizeNode(node)
   432         }
   434         if (id < 0) {
   435             dao.insertComponent(component)
   436         } else {
   437             dao.updateComponent(component)
   438         }
   440         http.renderCommit("projects/${project.node}/components/")
   441     }
   443     private fun issue(http: HttpRequest, dao: DataAccessObject) {
   444         withPathInfo(http, dao)?.run {
   445             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   446             if (issue == null) {
   447                 http.response.sendError(404)
   448                 return
   449             }
   451             val comments = dao.listComments(issue)
   453             with(http) {
   454                 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
   455                 view = IssueDetailView(issue, comments, project, version, component)
   456                 feedPath = feedPath(projectInfo.project)
   457                 navigationMenu = activeProjectNavMenu(
   458                     dao.listProjects(),
   459                     projectInfo,
   460                     version,
   461                     component
   462                 )
   463                 styleSheets = listOf("projects")
   464                 javascript = "issue-editor"
   465                 render("issue-view")
   466             }
   467         }
   468     }
   470     private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
   471         withPathInfo(http, dao)?.run {
   472             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1) ?: Issue(
   473                 -1,
   474                 project,
   475             )
   477             // for new issues set some defaults
   478             if (issue.id < 0) {
   479                 // pre-select component, if available in the path info
   480                 issue.component = component
   482                 // pre-select version, if available in the path info
   483                 if (version != null) {
   484                     if (version.status.isReleased) {
   485                         issue.affected = version
   486                     } else {
   487                         issue.resolved = version
   488                     }
   489                 }
   490             }
   492             with(http) {
   493                 view = IssueEditView(
   494                     issue,
   495                     projectInfo.versions,
   496                     projectInfo.components,
   497                     dao.listUsers(),
   498                     project,
   499                     version,
   500                     component
   501                 )
   502                 feedPath = feedPath(projectInfo.project)
   503                 navigationMenu = activeProjectNavMenu(
   504                     dao.listProjects(),
   505                     projectInfo,
   506                     version,
   507                     component
   508                 )
   509                 styleSheets = listOf("projects")
   510                 javascript = "issue-editor"
   511                 render("issue-form")
   512             }
   513         }
   514     }
   516     private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
   517         withPathInfo(http, dao)?.run {
   518             val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
   519             if (issue == null) {
   520                 http.response.sendError(404)
   521                 return
   522             }
   524             val commentId = http.param("commentid")?.toIntOrNull() ?: -1
   525             if (commentId > 0) {
   526                 val comment = dao.findComment(commentId)
   527                 if (comment == null) {
   528                     http.response.sendError(404)
   529                     return
   530                 }
   531                 val originalAuthor = comment.author?.username
   532                 if (originalAuthor != null && originalAuthor == http.remoteUser) {
   533                     val newComment = http.param("comment")
   534                     if (!newComment.isNullOrBlank()) {
   535                         comment.comment = newComment
   536                         dao.updateComment(comment)
   537                         dao.insertHistoryEvent(issue, comment)
   538                     } else {
   539                         logger.debug("Not updating comment ${comment.id} because nothing changed.")
   540                     }
   541                 } else {
   542                     http.response.sendError(403)
   543                     return
   544                 }
   545             } else {
   546                 val comment = IssueComment(-1, issue.id).apply {
   547                     author = http.remoteUser?.let { dao.findUserByName(it) }
   548                     comment = http.param("comment") ?: ""
   549                 }
   550                 val newId = dao.insertComment(comment)
   551                 dao.insertHistoryEvent(issue, comment, newId)
   552             }
   554             http.renderCommit("${issuesHref}${issue.id}")
   555         }
   556     }
   558     private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
   559         withPathInfo(http, dao)?.run {
   560             val issue = Issue(
   561                 http.param("id")?.toIntOrNull() ?: -1,
   562                 project
   563             ).apply {
   564                 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
   565                 category = IssueCategory.valueOf(http.param("category") ?: "")
   566                 status = IssueStatus.valueOf(http.param("status") ?: "")
   567                 subject = http.param("subject") ?: ""
   568                 description = http.param("description") ?: ""
   569                 assignee = http.param("assignee")?.toIntOrNull()?.let {
   570                     when (it) {
   571                         -1 -> null
   572                         -2 -> component?.lead
   573                         else -> dao.findUser(it)
   574                     }
   575                 }
   576                 // TODO: process error messages
   577                 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
   579                 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
   580                 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
   581             }
   583             val openId = if (issue.id < 0) {
   584                 val id = dao.insertIssue(issue)
   585                 dao.insertHistoryEvent(issue, id)
   586                 id
   587             } else {
   588                 val reference = dao.findIssue(issue.id)
   589                 if (reference == null) {
   590                     http.response.sendError(404)
   591                     return
   592                 }
   594                 if (issue.hasChanged(reference)) {
   595                     dao.updateIssue(issue)
   596                     dao.insertHistoryEvent(issue)
   597                 } else {
   598                     logger.debug("Not updating issue ${issue.id} because nothing changed.")
   599                 }
   601                 val newComment = http.param("comment")
   602                 if (!newComment.isNullOrBlank()) {
   603                     val comment = IssueComment(-1, issue.id).apply {
   604                         author = http.remoteUser?.let { dao.findUserByName(it) }
   605                         comment = newComment
   606                     }
   607                     val commentid = dao.insertComment(comment)
   608                     dao.insertHistoryEvent(issue, comment, commentid)
   609                 }
   610                 issue.id
   611             }
   613             if (http.param("more") != null) {
   614                 http.renderCommit("${issuesHref}-/create")
   615             } else {
   616                 http.renderCommit("${issuesHref}${openId}")
   617             }
   618         }
   619     }
   620 }

mercurial