Sat, 04 Jun 2022 18:29:58 +0200
move IssueSorter to viewmodel package
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.viewmodel.*
39 import java.sql.Date
40 import javax.servlet.annotation.WebServlet
42 @WebServlet(urlPatterns = ["/projects/*"])
43 class ProjectServlet : AbstractServlet() {
45 init {
46 get("/", this::projects)
47 get("/%project", this::project)
48 get("/%project/issues/%version/%component/", this::project)
49 get("/%project/edit", this::projectForm)
50 get("/-/create", this::projectForm)
51 post("/-/commit", this::projectCommit)
53 get("/%project/versions/", this::versions)
54 get("/%project/versions/%version/edit", this::versionForm)
55 get("/%project/versions/-/create", this::versionForm)
56 post("/%project/versions/-/commit", this::versionCommit)
58 get("/%project/components/", this::components)
59 get("/%project/components/%component/edit", this::componentForm)
60 get("/%project/components/-/create", this::componentForm)
61 post("/%project/components/-/commit", this::componentCommit)
63 get("/%project/issues/%version/%component/%issue", this::issue)
64 get("/%project/issues/%version/%component/%issue/edit", this::issueForm)
65 post("/%project/issues/%version/%component/%issue/comment", this::issueComment)
66 get("/%project/issues/%version/%component/-/create", this::issueForm)
67 post("/%project/issues/%version/%component/-/commit", this::issueCommit)
68 }
70 private fun projects(http: HttpRequest, dao: DataAccessObject) {
71 val projects = dao.listProjects()
72 val projectInfos = projects.map {
73 ProjectInfo(
74 project = it,
75 versions = dao.listVersions(it),
76 components = emptyList(), // not required in this view
77 issueSummary = dao.collectIssueSummary(it)
78 )
79 }
81 with(http) {
82 view = ProjectsView(projectInfos)
83 navigationMenu = projectNavMenu(projects)
84 styleSheets = listOf("projects")
85 render("projects")
86 }
87 }
89 private fun activeProjectNavMenu(
90 projects: List<Project>,
91 projectInfo: ProjectInfo,
92 selectedVersion: Version? = null,
93 selectedComponent: Component? = null
94 ) =
95 projectNavMenu(
96 projects,
97 projectInfo.versions,
98 projectInfo.components,
99 projectInfo.project,
100 selectedVersion,
101 selectedComponent
102 )
104 private sealed interface LookupResult<T>
105 private class NotFound<T> : LookupResult<T>
106 private data class Found<T>(val elem: T?) : LookupResult<T>
108 private fun <T : HasNode> HttpRequest.lookupPathParam(paramName: String, list: List<T>): LookupResult<T> {
109 val node = pathParams[paramName]
110 return if (node == null || node == "-") {
111 Found(null)
112 } else {
113 val result = list.find { it.node == node }
114 if (result == null) {
115 NotFound()
116 } else {
117 Found(result)
118 }
119 }
120 }
122 private fun obtainProjectInfo(http: HttpRequest, dao: DataAccessObject): ProjectInfo? {
123 val project = dao.findProjectByNode(http.pathParams["project"] ?: "") ?: return null
125 val versions: List<Version> = dao.listVersions(project)
126 val components: List<Component> = dao.listComponents(project)
128 return ProjectInfo(
129 project,
130 versions,
131 components,
132 dao.collectIssueSummary(project)
133 )
134 }
136 private fun sanitizeNode(name: String): String {
137 val san = name.replace(Regex("[/\\\\]"), "-")
138 return if (san.startsWith(".")) {
139 "v$san"
140 } else {
141 san
142 }
143 }
145 private fun feedPath(project: Project) = "feed/${project.node}/issues.rss"
147 private data class PathInfos(
148 val projectInfo: ProjectInfo,
149 val version: Version?,
150 val component: Component?
151 ) {
152 val project = projectInfo.project
153 val issuesHref by lazyOf("projects/${project.node}/issues/${version?.node ?: "-"}/${component?.node ?: "-"}/")
154 }
156 private fun withPathInfo(http: HttpRequest, dao: DataAccessObject): PathInfos? {
157 val projectInfo = obtainProjectInfo(http, dao)
158 if (projectInfo == null) {
159 http.response.sendError(404)
160 return null
161 }
163 val version = when (val result = http.lookupPathParam("version", projectInfo.versions)) {
164 is NotFound -> {
165 http.response.sendError(404)
166 return null
167 }
168 is Found -> {
169 result.elem
170 }
171 }
172 val component = when (val result = http.lookupPathParam("component", projectInfo.components)) {
173 is NotFound -> {
174 http.response.sendError(404)
175 return null
176 }
177 is Found -> {
178 result.elem
179 }
180 }
182 return PathInfos(projectInfo, version, component)
183 }
185 private fun project(http: HttpRequest, dao: DataAccessObject) {
186 withPathInfo(http, dao)?.run {
188 val issues = dao.listIssues(project, version, component)
189 .sortedWith(
190 IssueSorter(
191 IssueSorter.Criteria(IssueSorter.Field.DONE),
192 IssueSorter.Criteria(IssueSorter.Field.ETA),
193 IssueSorter.Criteria(IssueSorter.Field.UPDATED, false)
194 )
195 )
197 with(http) {
198 pageTitle = project.name
199 view = ProjectDetails(projectInfo, issues, version, component)
200 feedPath = feedPath(project)
201 navigationMenu = activeProjectNavMenu(
202 dao.listProjects(),
203 projectInfo,
204 version,
205 component
206 )
207 styleSheets = listOf("projects")
208 render("project-details")
209 }
210 }
211 }
213 private fun projectForm(http: HttpRequest, dao: DataAccessObject) {
214 if (!http.pathParams.containsKey("project")) {
215 http.view = ProjectEditView(Project(-1), dao.listUsers())
216 http.navigationMenu = projectNavMenu(dao.listProjects())
217 } else {
218 val projectInfo = obtainProjectInfo(http, dao)
219 if (projectInfo == null) {
220 http.response.sendError(404)
221 return
222 }
223 http.view = ProjectEditView(projectInfo.project, dao.listUsers())
224 http.navigationMenu = activeProjectNavMenu(
225 dao.listProjects(),
226 projectInfo
227 )
228 }
229 http.styleSheets = listOf("projects")
230 http.render("project-form")
231 }
233 private fun projectCommit(http: HttpRequest, dao: DataAccessObject) {
234 val project = Project(http.param("id")?.toIntOrNull() ?: -1).apply {
235 name = http.param("name") ?: ""
236 node = http.param("node") ?: ""
237 description = http.param("description") ?: ""
238 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
239 repoUrl = http.param("repoUrl") ?: ""
240 owner = (http.param("owner")?.toIntOrNull() ?: -1).let {
241 if (it < 0) null else dao.findUser(it)
242 }
243 // intentional defaults
244 if (node.isBlank()) node = name
245 // sanitizing
246 node = sanitizeNode(node)
247 }
249 if (project.id < 0) {
250 dao.insertProject(project)
251 } else {
252 dao.updateProject(project)
253 }
255 http.renderCommit("projects/${project.node}")
256 }
258 private fun versions(http: HttpRequest, dao: DataAccessObject) {
259 val projectInfo = obtainProjectInfo(http, dao)
260 if (projectInfo == null) {
261 http.response.sendError(404)
262 return
263 }
265 with(http) {
266 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.versions")}"
267 view = VersionsView(
268 projectInfo,
269 dao.listVersionSummaries(projectInfo.project)
270 )
271 feedPath = feedPath(projectInfo.project)
272 navigationMenu = activeProjectNavMenu(
273 dao.listProjects(),
274 projectInfo
275 )
276 styleSheets = listOf("projects")
277 render("versions")
278 }
279 }
281 private fun versionForm(http: HttpRequest, dao: DataAccessObject) {
282 val projectInfo = obtainProjectInfo(http, dao)
283 if (projectInfo == null) {
284 http.response.sendError(404)
285 return
286 }
288 val version: Version
289 when (val result = http.lookupPathParam("version", projectInfo.versions)) {
290 is NotFound -> {
291 http.response.sendError(404)
292 return
293 }
294 is Found -> {
295 version = result.elem ?: Version(-1, projectInfo.project.id)
296 }
297 }
299 with(http) {
300 view = VersionEditView(projectInfo, version)
301 feedPath = feedPath(projectInfo.project)
302 navigationMenu = activeProjectNavMenu(
303 dao.listProjects(),
304 projectInfo,
305 selectedVersion = version
306 )
307 styleSheets = listOf("projects")
308 render("version-form")
309 }
310 }
312 private fun obtainIdAndProject(http: HttpRequest, dao: DataAccessObject): Pair<Int, Project>? {
313 val id = http.param("id")?.toIntOrNull()
314 val projectid = http.param("projectid")?.toIntOrNull() ?: -1
315 val project = dao.findProject(projectid)
316 return if (id == null || project == null) {
317 http.response.sendError(400)
318 null
319 } else {
320 Pair(id, project)
321 }
322 }
324 private fun versionCommit(http: HttpRequest, dao: DataAccessObject) {
325 val idParams = obtainIdAndProject(http, dao) ?: return
326 val (id, project) = idParams
328 val version = Version(id, project.id).apply {
329 name = http.param("name") ?: ""
330 node = http.param("node") ?: ""
331 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
332 status = http.param("status")?.let(VersionStatus::valueOf) ?: VersionStatus.Future
333 // TODO: process error messages
334 eol = http.param("eol", ::dateOptValidator, null, mutableListOf())
335 release = http.param("release", ::dateOptValidator, null, mutableListOf())
336 // intentional defaults
337 if (node.isBlank()) node = name
338 // sanitizing
339 node = sanitizeNode(node)
340 }
342 // sanitize eol and release date
343 if (version.status.isEndOfLife) {
344 if (version.eol == null) version.eol = Date(System.currentTimeMillis())
345 } else if (version.status.isReleased) {
346 if (version.release == null) version.release = Date(System.currentTimeMillis())
347 }
349 if (id < 0) {
350 dao.insertVersion(version)
351 } else {
352 dao.updateVersion(version)
353 }
355 http.renderCommit("projects/${project.node}/versions/")
356 }
358 private fun components(http: HttpRequest, dao: DataAccessObject) {
359 val projectInfo = obtainProjectInfo(http, dao)
360 if (projectInfo == null) {
361 http.response.sendError(404)
362 return
363 }
365 with(http) {
366 pageTitle = "${projectInfo.project.name} - ${i18n("navmenu.components")}"
367 view = ComponentsView(
368 projectInfo,
369 dao.listComponentSummaries(projectInfo.project)
370 )
371 feedPath = feedPath(projectInfo.project)
372 navigationMenu = activeProjectNavMenu(
373 dao.listProjects(),
374 projectInfo
375 )
376 styleSheets = listOf("projects")
377 render("components")
378 }
379 }
381 private fun componentForm(http: HttpRequest, dao: DataAccessObject) {
382 val projectInfo = obtainProjectInfo(http, dao)
383 if (projectInfo == null) {
384 http.response.sendError(404)
385 return
386 }
388 val component: Component
389 when (val result = http.lookupPathParam("component", projectInfo.components)) {
390 is NotFound -> {
391 http.response.sendError(404)
392 return
393 }
394 is Found -> {
395 component = result.elem ?: Component(-1, projectInfo.project.id)
396 }
397 }
399 with(http) {
400 view = ComponentEditView(projectInfo, component, dao.listUsers())
401 feedPath = feedPath(projectInfo.project)
402 navigationMenu = activeProjectNavMenu(
403 dao.listProjects(),
404 projectInfo,
405 selectedComponent = component
406 )
407 styleSheets = listOf("projects")
408 render("component-form")
409 }
410 }
412 private fun componentCommit(http: HttpRequest, dao: DataAccessObject) {
413 val idParams = obtainIdAndProject(http, dao) ?: return
414 val (id, project) = idParams
416 val component = Component(id, project.id).apply {
417 name = http.param("name") ?: ""
418 node = http.param("node") ?: ""
419 ordinal = http.param("ordinal")?.toIntOrNull() ?: 0
420 color = WebColor(http.param("color") ?: "#000000")
421 description = http.param("description")
422 // TODO: process error message
423 active = http.param("active", ::boolValidator, true, mutableListOf())
424 lead = (http.param("lead")?.toIntOrNull() ?: -1).let {
425 if (it < 0) null else dao.findUser(it)
426 }
427 // intentional defaults
428 if (node.isBlank()) node = name
429 // sanitizing
430 node = sanitizeNode(node)
431 }
433 if (id < 0) {
434 dao.insertComponent(component)
435 } else {
436 dao.updateComponent(component)
437 }
439 http.renderCommit("projects/${project.node}/components/")
440 }
442 private fun issue(http: HttpRequest, dao: DataAccessObject) {
443 withPathInfo(http, dao)?.run {
444 val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
445 if (issue == null) {
446 http.response.sendError(404)
447 return
448 }
450 val comments = dao.listComments(issue)
452 with(http) {
453 pageTitle = "${projectInfo.project.name}: #${issue.id} ${issue.subject}"
454 view = IssueDetailView(issue, comments, project, version, component)
455 feedPath = feedPath(projectInfo.project)
456 navigationMenu = activeProjectNavMenu(
457 dao.listProjects(),
458 projectInfo,
459 version,
460 component
461 )
462 styleSheets = listOf("projects")
463 javascript = "issue-editor"
464 render("issue-view")
465 }
466 }
467 }
469 private fun issueForm(http: HttpRequest, dao: DataAccessObject) {
470 withPathInfo(http, dao)?.run {
471 val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1) ?: Issue(
472 -1,
473 project,
474 )
476 // for new issues set some defaults
477 if (issue.id < 0) {
478 // pre-select component, if available in the path info
479 issue.component = component
481 // pre-select version, if available in the path info
482 if (version != null) {
483 if (version.status.isReleased) {
484 issue.affected = version
485 } else {
486 issue.resolved = version
487 }
488 }
489 }
491 with(http) {
492 view = IssueEditView(
493 issue,
494 projectInfo.versions,
495 projectInfo.components,
496 dao.listUsers(),
497 project,
498 version,
499 component
500 )
501 feedPath = feedPath(projectInfo.project)
502 navigationMenu = activeProjectNavMenu(
503 dao.listProjects(),
504 projectInfo,
505 version,
506 component
507 )
508 styleSheets = listOf("projects")
509 javascript = "issue-editor"
510 render("issue-form")
511 }
512 }
513 }
515 private fun issueComment(http: HttpRequest, dao: DataAccessObject) {
516 withPathInfo(http, dao)?.run {
517 val issue = dao.findIssue(http.pathParams["issue"]?.toIntOrNull() ?: -1)
518 if (issue == null) {
519 http.response.sendError(404)
520 return
521 }
523 val commentId = http.param("commentid")?.toIntOrNull() ?: -1
524 if (commentId > 0) {
525 val comment = dao.findComment(commentId)
526 if (comment == null) {
527 http.response.sendError(404)
528 return
529 }
530 val originalAuthor = comment.author?.username
531 if (originalAuthor != null && originalAuthor == http.remoteUser) {
532 val newComment = http.param("comment")
533 if (!newComment.isNullOrBlank()) {
534 comment.comment = newComment
535 dao.updateComment(comment)
536 dao.insertHistoryEvent(issue, comment)
537 } else {
538 logger.debug("Not updating comment ${comment.id} because nothing changed.")
539 }
540 } else {
541 http.response.sendError(403)
542 return
543 }
544 } else {
545 val comment = IssueComment(-1, issue.id).apply {
546 author = http.remoteUser?.let { dao.findUserByName(it) }
547 comment = http.param("comment") ?: ""
548 }
549 val newId = dao.insertComment(comment)
550 dao.insertHistoryEvent(issue, comment, newId)
551 }
553 http.renderCommit("${issuesHref}${issue.id}")
554 }
555 }
557 private fun issueCommit(http: HttpRequest, dao: DataAccessObject) {
558 withPathInfo(http, dao)?.run {
559 val issue = Issue(
560 http.param("id")?.toIntOrNull() ?: -1,
561 project
562 ).apply {
563 component = dao.findComponent(http.param("component")?.toIntOrNull() ?: -1)
564 category = IssueCategory.valueOf(http.param("category") ?: "")
565 status = IssueStatus.valueOf(http.param("status") ?: "")
566 subject = http.param("subject") ?: ""
567 description = http.param("description") ?: ""
568 assignee = http.param("assignee")?.toIntOrNull()?.let {
569 when (it) {
570 -1 -> null
571 -2 -> component?.lead
572 else -> dao.findUser(it)
573 }
574 }
575 // TODO: process error messages
576 eta = http.param("eta", ::dateOptValidator, null, mutableListOf())
578 affected = http.param("affected")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
579 resolved = http.param("resolved")?.toIntOrNull()?.takeIf { it > 0 }?.let { Version(it, project.id) }
580 }
582 val openId = if (issue.id < 0) {
583 val id = dao.insertIssue(issue)
584 dao.insertHistoryEvent(issue, id)
585 id
586 } else {
587 val reference = dao.findIssue(issue.id)
588 if (reference == null) {
589 http.response.sendError(404)
590 return
591 }
593 if (issue.hasChanged(reference)) {
594 dao.updateIssue(issue)
595 dao.insertHistoryEvent(issue)
596 } else {
597 logger.debug("Not updating issue ${issue.id} because nothing changed.")
598 }
600 val newComment = http.param("comment")
601 if (!newComment.isNullOrBlank()) {
602 val comment = IssueComment(-1, issue.id).apply {
603 author = http.remoteUser?.let { dao.findUserByName(it) }
604 comment = newComment
605 }
606 val commentid = dao.insertComment(comment)
607 dao.insertHistoryEvent(issue, comment, commentid)
608 }
609 issue.id
610 }
612 if (http.param("more") != null) {
613 http.renderCommit("${issuesHref}-/create")
614 } else {
615 http.renderCommit("${issuesHref}${openId}")
616 }
617 }
618 }
619 }