Fri, 30 Dec 2022 19:04:34 +0100
#29 add possibility to relate issues
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 issues = dao.listIssues(project, version, component)
188 .sortedWith(
189 IssueSorter(
190 IssueSorter.Criteria(IssueSorter.Field.PHASE),
191 IssueSorter.Criteria(IssueSorter.Field.ETA),
192 IssueSorter.Criteria(IssueSorter.Field.UPDATED, false)
193 )
194 )
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 // TODO: process error messages
333 eol = http.param("eol", ::dateOptValidator, null, mutableListOf())
334 release = http.param("release", ::dateOptValidator, null, mutableListOf())
335 // intentional defaults
336 if (node.isBlank()) node = name
337 // sanitizing
338 node = sanitizeNode(node)
339 }
341 // sanitize eol and release date
342 if (version.status.isEndOfLife) {
343 if (version.eol == null) version.eol = Date(System.currentTimeMillis())
344 } else if (version.status.isReleased) {
345 if (version.release == null) version.release = Date(System.currentTimeMillis())
346 }
348 if (id < 0) {
349 dao.insertVersion(version)
350 } else {
351 dao.updateVersion(version)
352 }
354 http.renderCommit("projects/${project.node}/versions/")
355 }
357 private fun components(http: HttpRequest, dao: DataAccessObject) {
358 val projectInfo = obtainProjectInfo(http, dao)
359 if (projectInfo == null) {
360 http.response.sendError(404)
361 return
362 }
364 with(http) {
365 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
366 view = ComponentsView(
367 projectInfo,
368 dao.listComponentSummaries(projectInfo.project)
369 )
370 feedPath = feedPath(projectInfo.project)
371 navigationMenu = activeProjectNavMenu(
372 dao.listProjects(),
373 projectInfo
374 )
375 styleSheets = listOf("projects")
376 render("components")
377 }
378 }
380 private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
381 val projectInfo = obtainProjectInfo(http, dao)
382 if (projectInfo == null) {
383 http.response.sendError(404)
384 return
385 }
387 val component: Component
388 when (val result = http.lookupPathParam("component", projectInfo.components)) {
389 is NotFound -> {
390 http.response.sendError(404)
391 return
392 }
393 is Found -> {
394 component = result.elem ?: Component(-1, projectInfo.project.id)
395 }
396 }
398 with(http) {
399 view = ComponentEditView(projectInfo, component, dao.listUsers())
400 feedPath = feedPath(projectInfo.project)
401 navigationMenu = activeProjectNavMenu(
402 dao.listProjects(),
403 projectInfo,
404 selectedComponent = component
405 )
406 styleSheets = listOf("projects")
407 render("component-form")
408 }
409 }
411 private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
412 val idParams = obtainIdAndProject(http, dao) ?: return
413 val (id, project) = idParams
415 val component = Component(id, project.id).apply {
416 name = http.param("name") ?: ""
417 node = http.param("node") ?: ""
418 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
419 color = WebColor(http.param("color") ?: "#000000")
420 description = http.param("description")
421 // TODO: process error message
422 active = http.param("active", ::boolValidator, true, mutableListOf())
423 lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
424 if (it < 0) null else dao.findUser(it)
425 }
426 // intentional defaults
427 if (node.isBlank()) node = name
428 // sanitizing
429 node = sanitizeNode(node)
430 }
432 if (id < 0) {
433 dao.insertComponent(component)
434 } else {
435 dao.updateComponent(component)
436 }
438 http.renderCommit("projects/${project.node}/components/")
439 }
441 private fun issue(http: HttpRequest, dao: DataAccessObject) {
442 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
443 if (issue == null) {
444 http.response.sendError(404)
445 return
446 }
447 renderIssueView(http, dao, issue)
448 }
450 private fun renderIssueView(
451 http: HttpRequest,
452 dao: DataAccessObject,
453 issue: Issue,
454 relationError: String? = null
455 ) {
456 withPathInfo(http, dao)?.run {
457 val comments = dao.listComments(issue)
459 with(http) {
460 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
461 view = IssueDetailView(
462 issue,
463 comments,
464 project,
465 version,
466 component,
467 dao.listIssues(project),
468 dao.listIssueRelations(issue),
469 relationError
470 )
471 feedPath = feedPath(projectInfo.project)
472 navigationMenu = activeProjectNavMenu(
473 dao.listProjects(),
474 projectInfo,
475 version,
476 component
477 )
478 styleSheets = listOf("projects")
479 javascript = "issue-editor"
480 render("issue-view")
481 }
482 }
483 }
485 private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
486 withPathInfo(http, dao)?.run {
487 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue) ?: Issue(
488 -1,
489 project,
490 )
492 // for new issues set some defaults
493 if (issue.id < 0) {
494 // pre-select component, if available in the path info
495 issue.component = component
497 // pre-select version, if available in the path info
498 if (version != null) {
499 if (version.status.isReleased) {
500 issue.affected = version
501 } else {
502 issue.resolved = version
503 }
504 }
505 }
507 with(http) {
508 view = IssueEditView(
509 issue,
510 projectInfo.versions,
511 projectInfo.components,
512 dao.listUsers(),
513 project,
514 version,
515 component
516 )
517 feedPath = feedPath(projectInfo.project)
518 navigationMenu = activeProjectNavMenu(
519 dao.listProjects(),
520 projectInfo,
521 version,
522 component
523 )
524 styleSheets = listOf("projects")
525 javascript = "issue-editor"
526 render("issue-form")
527 }
528 }
529 }
531 private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
532 withPathInfo(http, dao)?.run {
533 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
534 if (issue == null) {
535 http.response.sendError(404)
536 return
537 }
539 val commentId = http.param("commentid")?.toIntOrNull() ?: -1
540 if (commentId > 0) {
541 val comment = dao.findComment(commentId)
542 if (comment == null) {
543 http.response.sendError(404)
544 return
545 }
546 val originalAuthor = comment.author?.username
547 if (originalAuthor != null && originalAuthor == http.remoteUser) {
548 val newComment = http.param("comment")
549 if (!newComment.isNullOrBlank()) {
550 comment.comment = newComment
551 dao.updateComment(comment)
552 dao.insertHistoryEvent(issue, comment)
553 } else {
554 logger.debug("Not updating comment ${comment.id} because nothing changed.")
555 }
556 } else {
557 http.response.sendError(403)
558 return
559 }
560 } else {
561 val comment = IssueComment(-1, issue.id).apply {
562 author = http.remoteUser?.let { dao.findUserByName(it) }
563 comment = http.param("comment") ?: ""
564 }
565 val newId = dao.insertComment(comment)
566 dao.insertHistoryEvent(issue, comment, newId)
567 }
569 http.renderCommit("${issuesHref}${issue.id}")
570 }
571 }
573 private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
574 withPathInfo(http, dao)?.run {
575 val issue = Issue(
576 http.param("id")?.toIntOrNull() ?: -1,
577 project
578 ).apply {
579 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
580 category = IssueCategory.valueOf(http.param("category") ?: "")
581 status = IssueStatus.valueOf(http.param("status") ?: "")
582 subject = http.param("subject") ?: ""
583 description = http.param("description") ?: ""
584 assignee = http.param("assignee")?.toIntOrNull()?.let {
585 when (it) {
586 -1 -> null
587 -2 -> component?.lead
588 else -> dao.findUser(it)
589 }
590 }
591 // TODO: process error messages
592 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
594 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
595 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
596 }
598 val openId = if (issue.id < 0) {
599 val id = dao.insertIssue(issue)
600 dao.insertHistoryEvent(issue, id)
601 id
602 } else {
603 val reference = dao.findIssue(issue.id)
604 if (reference == null) {
605 http.response.sendError(404)
606 return
607 }
609 if (issue.hasChanged(reference)) {
610 dao.updateIssue(issue)
611 dao.insertHistoryEvent(issue)
612 } else {
613 logger.debug("Not updating issue ${issue.id} because nothing changed.")
614 }
616 val newComment = http.param("comment")
617 if (!newComment.isNullOrBlank()) {
618 val comment = IssueComment(-1, issue.id).apply {
619 author = http.remoteUser?.let { dao.findUserByName(it) }
620 comment = newComment
621 }
622 val commentid = dao.insertComment(comment)
623 dao.insertHistoryEvent(issue, comment, commentid)
624 }
625 issue.id
626 }
628 if (http.param("more") != null) {
629 http.renderCommit("${issuesHref}-/create")
630 } else {
631 http.renderCommit("${issuesHref}${openId}")
632 }
633 }
634 }
636 private fun issueRelation(http: HttpRequest, dao: DataAccessObject) {
637 withPathInfo(http, dao)?.run {
638 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
639 if (issue == null) {
640 http.response.sendError(404)
641 return
642 }
644 // determine the relation type
645 val type: Pair<RelationType, Boolean>? = http.param("type")?.let {
646 try {
647 if (it.startsWith("!")) {
648 Pair(RelationType.valueOf(it.substring(1)), true)
649 } else {
650 Pair(RelationType.valueOf(it), false)
651 }
652 } catch (_: IllegalArgumentException) {
653 null
654 }
655 }
657 // if the relation type was invalid, send HTTP 500
658 if (type == null) {
659 http.response.sendError(500)
660 return
661 }
663 // determine the target issue
664 val targetIssue: Issue? = http.param("issue")?.let {
665 if (it.startsWith("#") && it.length > 1) {
666 it.substring(1).split(" ", limit = 2)[0].toIntOrNull()
667 ?.let(dao::findIssue)
668 ?.takeIf { target -> target.project.id == issue.project.id }
669 } else {
670 null
671 }
672 }
674 // check if the target issue is valid
675 if (targetIssue == null) {
676 renderIssueView(http, dao, issue, "issue.relations.target.invalid")
677 return
678 }
680 // commit the result
681 dao.insertIssueRelation(IssueRelation(issue, targetIssue, type.first, type.second))
682 http.renderCommit("${issuesHref}${issue.id}")
683 }
684 }
686 private fun issueRemoveRelation(http: HttpRequest, dao: DataAccessObject) {
687 withPathInfo(http, dao)?.run {
688 val issue = http.pathParams["issue"]?.toIntOrNull()?.let(dao::findIssue)
689 if (issue == null) {
690 http.response.sendError(404)
691 return
692 }
694 // determine relation
695 val type = http.param("type")?.let {
696 try {RelationType.valueOf(it)}
697 catch (_:IllegalArgumentException) {null}
698 }
699 if (type == null) {
700 http.response.sendError(500)
701 return
702 }
703 val rel = http.param("to")?.toIntOrNull()?.let(dao::findIssue)?.let {
704 IssueRelation(
705 issue,
706 it,
707 type,
708 http.param("reverse")?.toBoolean() ?: false
709 )
710 }
712 // execute removal, if there is something to remove
713 rel?.run(dao::deleteIssueRelation)
715 // always pretend that the operation was successful - if there was nothing to remove, it's okay
716 http.renderCommit("${issuesHref}${issue.id}")
717 }
718 }
719 }