Sun, 08 Jan 2023 17:07:26 +0100
#15 add issue filters
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.*
35 import de.uapcore.lightpit.viewmodel.*
36 import jakarta.servlet.annotation.WebServlet
37 import java.sql.Date
39 @WebServlet(urlPatterns = ["/projects/*"])
40 class ProjectServlet : AbstractServlet() {
42 init {
43 get("/", this::projects)
44 get("/%project", this::project)
45 get("/%project/issues/%version/%component/", this::project)
46 get("/%project/edit", this::projectForm)
47 get("/-/create", this::projectForm)
48 post("/-/commit", this::projectCommit)
50 get("/%project/versions/", this::versions)
51 get("/%project/versions/%version/edit", this::versionForm)
52 get("/%project/versions/-/create", this::versionForm)
53 post("/%project/versions/-/commit", this::versionCommit)
55 get("/%project/components/", this::components)
56 get("/%project/components/%component/edit", this::componentForm)
57 get("/%project/components/-/create", this::componentForm)
58 post("/%project/components/-/commit", this::componentCommit)
60 get("/%project/issues/%version/%component/%issue", this::issue)
61 get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
62 post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
63 post("/%project/issues/%version/%component/%issue/relation", this::issueRelation)
64 get("/%project/issues/%version/%component/%issue/removeRelation", this::issueRemoveRelation)
65 get("/%project/issues/%version/%component/-/create", this::issueForm)
66 post("/%project/issues/%version/%component/-/commit", this::issueCommit)
67 }
69 private fun projects(http: HttpRequest, dao: DataAccessObject) {
70 val projects = dao.listProjects()
71 val projectInfos = projects.map {
72 ProjectInfo(
73 project = it,
74 versions = dao.listVersions(it),
75 components = emptyList(), // not required in this view
76 issueSummary = dao.collectIssueSummary(it)
77 )
78 }
80 with(http) {
81 view = ProjectsView(projectInfos)
82 navigationMenu = projectNavMenu(projects)
83 styleSheets = listOf("projects")
84 render("projects")
85 }
86 }
88 private fun activeProjectNavMenu(
89 projects: List<Project>,
90 projectInfo: ProjectInfo,
91 selectedVersion: Version? = null,
92 selectedComponent: Component? = null
93 ) =
94 projectNavMenu(
95 projects,
96 projectInfo.versions,
97 projectInfo.components,
98 projectInfo.project,
99 selectedVersion,
100 selectedComponent
101 )
103 private sealed interface LookupResult<T>
104 private class NotFound<T> : LookupResult<T>
105 private data class Found<T>(val elem: T?) : LookupResult<T>
107 private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
108 val node = pathParams[paramName]
109 return if (node == null || node == "-") {
110 Found(null)
111 } else {
112 val result = list.find { it.node == node }
113 if (result == null) {
114 NotFound()
115 } else {
116 Found(result)
117 }
118 }
119 }
121 private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
122 val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
124 val versions: List<Version> = dao.listVersions(project)
125 val components: List<Component> = dao.listComponents(project)
127 return ProjectInfo(
128 project,
129 versions,
130 components,
131 dao.collectIssueSummary(project)
132 )
133 }
135 private fun sanitizeNode(name: String): String {
136 val san = name.replace(Regex("[/\\\\]"), "-")
137 return if (san.startsWith(".")) {
138 "v$san"
139 } else {
140 san
141 }
142 }
144 private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
146 private data class PathInfos(
147 val projectInfo: ProjectInfo,
148 val version: Version?,
149 val component: Component?
150 ) {
151 val project = projectInfo.project
152 val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
153 }
155 private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
156 val projectInfo = obtainProjectInfo(http, dao)
157 if (projectInfo == null) {
158 http.response.sendError(404)
159 return null
160 }
162 val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
163 is NotFound -> {
164 http.response.sendError(404)
165 return null
166 }
167 is Found -> {
168 result.elem
169 }
170 }
171 val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
172 is NotFound -> {
173 http.response.sendError(404)
174 return null
175 }
176 is Found -> {
177 result.elem
178 }
179 }
181 return PathInfos(projectInfo, version, component)
182 }
184 private fun project(http: HttpRequest, dao: DataAccessObject) {
185 withPathInfo(http, dao)?.run {
187 val filter = IssueFilter(http)
189 val needRelationsMap = filter.onlyBlocker
191 val relationsMap = if (needRelationsMap) dao.getIssueRelationMap(project, filter.includeDone) else emptyMap()
193 val issues = dao.listIssues(project, filter.includeDone, version, component)
194 .sortedWith(
195 IssueSorter(
196 IssueSorter.Criteria(IssueSorter.Field.DONE),
197 IssueSorter.Criteria(IssueSorter.Field.ETA),
198 IssueSorter.Criteria(IssueSorter.Field.UPDATED, false)
199 )
200 )
201 .filter {
202 (!filter.onlyMine || (it.assignee?.username ?: "") == (http.remoteUser ?: "<Anonymous>")) &&
203 (!filter.onlyBlocker || (relationsMap[it.id]?.any { (_,type) -> type.blocking }?:false)) &&
204 (filter.status.isEmpty() || filter.status.contains(it.status)) &&
205 (filter.category.isEmpty() || filter.category.contains(it.category))
206 }
208 with(http) {
209 pageTitle = project.name
210 view = ProjectDetails(projectInfo, issues, filter, version, component)
211 feedPath = feedPath(project)
212 navigationMenu = activeProjectNavMenu(
213 dao.listProjects(),
214 projectInfo,
215 version,
216 component
217 )
218 styleSheets = listOf("projects")
219 javascript = "project-details"
220 render("project-details")
221 }
222 }
223 }
225 private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
226 if (!http.pathParams.containsKey("project")) {
227 http.view = ProjectEditView(Project(-1), dao.listUsers())
228 http.navigationMenu = projectNavMenu(dao.listProjects())
229 } else {
230 val projectInfo = obtainProjectInfo(http, dao)
231 if (projectInfo == null) {
232 http.response.sendError(404)
233 return
234 }
235 http.view = ProjectEditView(projectInfo.project, dao.listUsers())
236 http.navigationMenu = activeProjectNavMenu(
237 dao.listProjects(),
238 projectInfo
239 )
240 }
241 http.styleSheets = listOf("projects")
242 http.render("project-form")
243 }
245 private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
246 val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
247 name = http.param("name") ?: ""
248 node = http.param("node") ?: ""
249 description = http.param("description") ?: ""
250 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
251 repoUrl = http.param("repoUrl") ?: ""
252 owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
253 if (it < 0) null else dao.findUser(it)
254 }
255 // intentional defaults
256 if (node.isBlank()) node = name
257 // sanitizing
258 node = sanitizeNode(node)
259 }
261 if (project.id < 0) {
262 dao.insertProject(project)
263 } else {
264 dao.updateProject(project)
265 }
267 http.renderCommit("projects/${project.node}")
268 }
270 private fun versions(http: HttpRequest, dao: DataAccessObject) {
271 val projectInfo = obtainProjectInfo(http, dao)
272 if (projectInfo == null) {
273 http.response.sendError(404)
274 return
275 }
277 with(http) {
278 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
279 view = VersionsView(
280 projectInfo,
281 dao.listVersionSummaries(projectInfo.project)
282 )
283 feedPath = feedPath(projectInfo.project)
284 navigationMenu = activeProjectNavMenu(
285 dao.listProjects(),
286 projectInfo
287 )
288 styleSheets = listOf("projects")
289 javascript = "project-details"
290 render("versions")
291 }
292 }
294 private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
295 val projectInfo = obtainProjectInfo(http, dao)
296 if (projectInfo == null) {
297 http.response.sendError(404)
298 return
299 }
301 val version: Version
302 when (val result = http.lookupPathParam("version", projectInfo.versions)) {
303 is NotFound -> {
304 http.response.sendError(404)
305 return
306 }
307 is Found -> {
308 version = result.elem ?: Version(-1, projectInfo.project.id)
309 }
310 }
312 with(http) {
313 view = VersionEditView(projectInfo, version)
314 feedPath = feedPath(projectInfo.project)
315 navigationMenu = activeProjectNavMenu(
316 dao.listProjects(),
317 projectInfo,
318 selectedVersion = version
319 )
320 styleSheets = listOf("projects")
321 render("version-form")
322 }
323 }
325 private fun obtainIdAndProject(http: HttpRequest, dao: DataAccessObject): Pair<Int, Project>? {
326 val id = http.param("id")?.toIntOrNull()
327 val projectid = http.param("projectid")?.toIntOrNull() ?: -1
328 val project = dao.findProject(projectid)
329 return if (id == null || project == null) {
330 http.response.sendError(400)
331 null
332 } else {
333 Pair(id, project)
334 }
335 }
337 private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
338 val idParams = obtainIdAndProject(http, dao) ?: return
339 val (id, project) = idParams
341 val version = Version(id, project.id).apply {
342 name = http.param("name") ?: ""
343 node = http.param("node") ?: ""
344 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
345 status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
346 // TODO: process error messages
347 eol = http.param("eol", ::dateOptValidator, null, mutableListOf())
348 release = http.param("release", ::dateOptValidator, null, mutableListOf())
349 // intentional defaults
350 if (node.isBlank()) node = name
351 // sanitizing
352 node = sanitizeNode(node)
353 }
355 // sanitize eol and release date
356 if (version.status.isEndOfLife) {
357 if (version.eol == null) version.eol = Date(System.currentTimeMillis())
358 } else if (version.status.isReleased) {
359 if (version.release == null) version.release = Date(System.currentTimeMillis())
360 }
362 if (id < 0) {
363 dao.insertVersion(version)
364 } else {
365 dao.updateVersion(version)
366 }
368 http.renderCommit("projects/${project.node}/versions/")
369 }
371 private fun components(http: HttpRequest, dao: DataAccessObject) {
372 val projectInfo = obtainProjectInfo(http, dao)
373 if (projectInfo == null) {
374 http.response.sendError(404)
375 return
376 }
378 with(http) {
379 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
380 view = ComponentsView(
381 projectInfo,
382 dao.listComponentSummaries(projectInfo.project)
383 )
384 feedPath = feedPath(projectInfo.project)
385 navigationMenu = activeProjectNavMenu(
386 dao.listProjects(),
387 projectInfo
388 )
389 styleSheets = listOf("projects")
390 javascript = "project-details"
391 render("components")
392 }
393 }
395 private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
396 val projectInfo = obtainProjectInfo(http, dao)
397 if (projectInfo == null) {
398 http.response.sendError(404)
399 return
400 }
402 val component: Component
403 when (val result = http.lookupPathParam("component", projectInfo.components)) {
404 is NotFound -> {
405 http.response.sendError(404)
406 return
407 }
408 is Found -> {
409 component = result.elem ?: Component(-1, projectInfo.project.id)
410 }
411 }
413 with(http) {
414 view = ComponentEditView(projectInfo, component, dao.listUsers())
415 feedPath = feedPath(projectInfo.project)
416 navigationMenu = activeProjectNavMenu(
417 dao.listProjects(),
418 projectInfo,
419 selectedComponent = component
420 )
421 styleSheets = listOf("projects")
422 render("component-form")
423 }
424 }
426 private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
427 val idParams = obtainIdAndProject(http, dao) ?: return
428 val (id, project) = idParams
430 val component = Component(id, project.id).apply {
431 name = http.param("name") ?: ""
432 node = http.param("node") ?: ""
433 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
434 color = WebColor(http.param("color") ?: "#000000")
435 description = http.param("description")
436 // TODO: process error message
437 active = http.param("active", ::boolValidator, true, mutableListOf())
438 lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
439 if (it < 0) null else dao.findUser(it)
440 }
441 // intentional defaults
442 if (node.isBlank()) node = name
443 // sanitizing
444 node = sanitizeNode(node)
445 }
447 if (id < 0) {
448 dao.insertComponent(component)
449 } else {
450 dao.updateComponent(component)
451 }
453 http.renderCommit("projects/${project.node}/components/")
454 }
456 private fun issue(http: HttpRequest, dao: DataAccessObject) {
457 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
458 if (issue == null) {
459 http.response.sendError(404)
460 return
461 }
462 renderIssueView(http, dao, issue)
463 }
465 private fun renderIssueView(
466 http: HttpRequest,
467 dao: DataAccessObject,
468 issue: Issue,
469 relationError: String? = null
470 ) {
471 withPathInfo(http, dao)?.run {
472 val comments = dao.listComments(issue)
474 with(http) {
475 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
476 view = IssueDetailView(
477 issue,
478 comments,
479 project,
480 version,
481 component,
482 dao.listIssues(project, true),
483 dao.listIssueRelations(issue),
484 relationError
485 )
486 feedPath = feedPath(projectInfo.project)
487 navigationMenu = activeProjectNavMenu(
488 dao.listProjects(),
489 projectInfo,
490 version,
491 component
492 )
493 styleSheets = listOf("projects")
494 javascript = "issue-editor"
495 render("issue-view")
496 }
497 }
498 }
500 private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
501 withPathInfo(http, dao)?.run {
502 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue) ?: Issue(
503 -1,
504 project,
505 )
507 // for new issues set some defaults
508 if (issue.id < 0) {
509 // pre-select component, if available in the path info
510 issue.component = component
512 // pre-select version, if available in the path info
513 if (version != null) {
514 if (version.status.isReleased) {
515 issue.affected = version
516 } else {
517 issue.resolved = version
518 }
519 }
520 }
522 with(http) {
523 view = IssueEditView(
524 issue,
525 projectInfo.versions,
526 projectInfo.components,
527 dao.listUsers(),
528 project,
529 version,
530 component
531 )
532 feedPath = feedPath(projectInfo.project)
533 navigationMenu = activeProjectNavMenu(
534 dao.listProjects(),
535 projectInfo,
536 version,
537 component
538 )
539 styleSheets = listOf("projects")
540 javascript = "issue-editor"
541 render("issue-form")
542 }
543 }
544 }
546 private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
547 withPathInfo(http, dao)?.run {
548 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
549 if (issue == null) {
550 http.response.sendError(404)
551 return
552 }
554 val commentId = http.param("commentid")?.toIntOrNull() ?: -1
555 if (commentId > 0) {
556 val comment = dao.findComment(commentId)
557 if (comment == null) {
558 http.response.sendError(404)
559 return
560 }
561 val originalAuthor = comment.author?.username
562 if (originalAuthor != null && originalAuthor == http.remoteUser) {
563 val newComment = http.param("comment")
564 if (!newComment.isNullOrBlank()) {
565 comment.comment = newComment
566 dao.updateComment(comment)
567 dao.insertHistoryEvent(issue, comment)
568 } else {
569 logger.debug("Not updating comment ${comment.id} because nothing changed.")
570 }
571 } else {
572 http.response.sendError(403)
573 return
574 }
575 } else {
576 val comment = IssueComment(-1, issue.id).apply {
577 author = http.remoteUser?.let { dao.findUserByName(it) }
578 comment = http.param("comment") ?: ""
579 }
580 val newId = dao.insertComment(comment)
581 dao.insertHistoryEvent(issue, comment, newId)
582 }
584 http.renderCommit("${issuesHref}${issue.id}")
585 }
586 }
588 private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
589 withPathInfo(http, dao)?.run {
590 val issue = Issue(
591 http.param("id")?.toIntOrNull() ?: -1,
592 project
593 ).apply {
594 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
595 category = IssueCategory.valueOf(http.param("category") ?: "")
596 status = IssueStatus.valueOf(http.param("status") ?: "")
597 subject = http.param("subject") ?: ""
598 description = http.param("description") ?: ""
599 assignee = http.param("assignee")?.toIntOrNull()?.let {
600 when (it) {
601 -1 -> null
602 -2 -> component?.lead
603 else -> dao.findUser(it)
604 }
605 }
606 // TODO: process error messages
607 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
609 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
610 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
611 }
613 val openId = if (issue.id < 0) {
614 val id = dao.insertIssue(issue)
615 dao.insertHistoryEvent(issue, id)
616 id
617 } else {
618 val reference = dao.findIssue(issue.id)
619 if (reference == null) {
620 http.response.sendError(404)
621 return
622 }
624 if (issue.hasChanged(reference)) {
625 dao.updateIssue(issue)
626 dao.insertHistoryEvent(issue)
627 } else {
628 logger.debug("Not updating issue ${issue.id} because nothing changed.")
629 }
631 val newComment = http.param("comment")
632 if (!newComment.isNullOrBlank()) {
633 val comment = IssueComment(-1, issue.id).apply {
634 author = http.remoteUser?.let { dao.findUserByName(it) }
635 comment = newComment
636 }
637 val commentid = dao.insertComment(comment)
638 dao.insertHistoryEvent(issue, comment, commentid)
639 }
640 issue.id
641 }
643 if (http.param("more") != null) {
644 http.renderCommit("${issuesHref}-/create")
645 } else {
646 http.renderCommit("${issuesHref}${openId}")
647 }
648 }
649 }
651 private fun issueRelation(http: HttpRequest, dao: DataAccessObject) {
652 withPathInfo(http, dao)?.run {
653 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
654 if (issue == null) {
655 http.response.sendError(404)
656 return
657 }
659 // determine the relation type
660 val type: Pair<RelationType, Boolean>? = http.param("type")?.let {
661 try {
662 if (it.startsWith("!")) {
663 Pair(RelationType.valueOf(it.substring(1)), true)
664 } else {
665 Pair(RelationType.valueOf(it), false)
666 }
667 } catch (_: IllegalArgumentException) {
668 null
669 }
670 }
672 // if the relation type was invalid, send HTTP 500
673 if (type == null) {
674 http.response.sendError(500)
675 return
676 }
678 // determine the target issue
679 val targetIssue: Issue? = http.param("issue")?.let {
680 if (it.startsWith("#") && it.length > 1) {
681 it.substring(1).split(" ", limit = 2)[0].toIntOrNull()
682 ?.let(dao::findIssue)
683 ?.takeIf { target -> target.project.id == issue.project.id }
684 } else {
685 null
686 }
687 }
689 // check if the target issue is valid
690 if (targetIssue == null) {
691 renderIssueView(http, dao, issue, "issue.relations.target.invalid")
692 return
693 }
695 // commit the result
696 dao.insertIssueRelation(IssueRelation(issue, targetIssue, type.first, type.second))
697 http.renderCommit("${issuesHref}${issue.id}")
698 }
699 }
701 private fun issueRemoveRelation(http: HttpRequest, dao: DataAccessObject) {
702 withPathInfo(http, dao)?.run {
703 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
704 if (issue == null) {
705 http.response.sendError(404)
706 return
707 }
709 // determine relation
710 val type = http.param("type")?.let {
711 try {RelationType.valueOf(it)}
712 catch (_:IllegalArgumentException) {null}
713 }
714 if (type == null) {
715 http.response.sendError(500)
716 return
717 }
718 val rel = http.param("to")?.toIntOrNull()?.let(dao::findIssue)?.let {
719 IssueRelation(
720 issue,
721 it,
722 type,
723 http.param("reverse")?.toBoolean() ?: false
724 )
725 }
727 // execute removal, if there is something to remove
728 rel?.run(dao::deleteIssueRelation)
730 // always pretend that the operation was successful - if there was nothing to remove, it's okay
731 http.renderCommit("${issuesHref}${issue.id}")
732 }
733 }
734 }