Sat, 23 May 2020 13:24:49 +0200
issue and version form now also work if no project is selected in the session
1 /*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3 *
4 * Copyright 2018 Mike Becker. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29 package de.uapcore.lightpit.modules;
32 import de.uapcore.lightpit.*;
33 import de.uapcore.lightpit.dao.DataAccessObjects;
34 import de.uapcore.lightpit.entities.*;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import javax.servlet.annotation.WebServlet;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import javax.servlet.http.HttpSession;
42 import java.io.IOException;
43 import java.sql.Date;
44 import java.sql.SQLException;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.NoSuchElementException;
48 import java.util.Objects;
50 import static de.uapcore.lightpit.Functions.fqn;
52 @LightPITModule(
53 bundleBaseName = "localization.projects",
54 modulePath = "projects",
55 defaultPriority = 20
56 )
57 @WebServlet(
58 name = "ProjectsModule",
59 urlPatterns = "/projects/*"
60 )
61 public final class ProjectsModule extends AbstractLightPITServlet {
63 private static final Logger LOG = LoggerFactory.getLogger(ProjectsModule.class);
65 public static final String SESSION_ATTR_SELECTED_PROJECT = fqn(ProjectsModule.class, "selected-project");
66 public static final String SESSION_ATTR_SELECTED_ISSUE = fqn(ProjectsModule.class, "selected-issue");
67 public static final String SESSION_ATTR_SELECTED_VERSION = fqn(ProjectsModule.class, "selected-version");
69 private class SessionSelection {
70 final HttpSession session;
71 Project project;
72 Version version;
73 Issue issue;
75 SessionSelection(HttpServletRequest req, Project project) {
76 this.session = req.getSession();
77 this.project = project;
78 version = null;
79 issue = null;
80 updateAttributes();
81 }
83 SessionSelection(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
84 this.session = req.getSession();
85 final var issueDao = dao.getIssueDao();
86 final var projectDao = dao.getProjectDao();
87 final var issueSelection = getParameter(req, Integer.class, "issue");
88 if (issueSelection.isPresent()) {
89 issue = issueDao.find(issueSelection.get());
90 } else {
91 final var issue = (Issue) session.getAttribute(SESSION_ATTR_SELECTED_ISSUE);
92 this.issue = issue == null ? null : issueDao.find(issue.getId());
93 }
94 if (issue != null) {
95 version = null; // show the issue globally
96 project = projectDao.find(issue.getProject().getId());
97 }
99 final var projectSelection = getParameter(req, Integer.class, "pid");
100 if (projectSelection.isPresent()) {
101 final var selectedProject = projectDao.find(projectSelection.get());
102 if (!Objects.equals(selectedProject, project)) {
103 // reset version and issue if project changed
104 version = null;
105 issue = null;
106 }
107 project = selectedProject;
108 } else {
109 final var sessionProject = (Project) session.getAttribute(SESSION_ATTR_SELECTED_PROJECT);
110 project = sessionProject == null ? null : projectDao.find(sessionProject.getId());
111 }
112 updateAttributes();
113 }
115 void selectVersion(Version version) {
116 if (!Objects.equals(project, version.getProject())) throw new AssertionError("Nice, you implemented a bug!");
117 this.version = version;
118 this.issue = null;
119 updateAttributes();
120 }
122 void selectIssue(Issue issue) {
123 if (!Objects.equals(issue.getProject(), project)) throw new AssertionError("Nice, you implemented a bug!");
124 this.issue = issue;
125 this.version = null;
126 updateAttributes();
127 }
129 void updateAttributes() {
130 session.setAttribute(SESSION_ATTR_SELECTED_PROJECT, project);
131 session.setAttribute(SESSION_ATTR_SELECTED_VERSION, version);
132 session.setAttribute(SESSION_ATTR_SELECTED_ISSUE, issue);
133 }
134 }
137 /**
138 * Creates the breadcrumb menu.
139 *
140 * @param level the current active level (0: root, 1: project, 2: version, 3: issue)
141 * @param sessionSelection the currently selected objects
142 * @return a dynamic breadcrumb menu trying to display as many levels as possible
143 */
144 private List<MenuEntry> getBreadcrumbs(int level, SessionSelection sessionSelection) {
145 MenuEntry entry;
147 final var breadcrumbs = new ArrayList<MenuEntry>();
148 entry = new MenuEntry(new ResourceKey("localization.projects", "menuLabel"),
149 "projects/", 0);
150 breadcrumbs.add(entry);
151 if (level == 0) entry.setActive(true);
153 if (sessionSelection.project != null) {
154 if (sessionSelection.project.getId() < 0) {
155 entry = new MenuEntry(new ResourceKey("localization.projects", "button.create"),
156 "projects/edit", 1);
157 } else {
158 entry = new MenuEntry(sessionSelection.project.getName(),
159 "projects/view?pid=" + sessionSelection.project.getId(), 1);
160 }
161 if (level == 1) entry.setActive(true);
162 breadcrumbs.add(entry);
163 }
165 if (sessionSelection.version != null) {
166 if (sessionSelection.version.getId() < 0) {
167 entry = new MenuEntry(new ResourceKey("localization.projects", "button.version.create"),
168 "projects/versions/edit", 2);
169 } else {
170 entry = new MenuEntry(sessionSelection.version.getName(),
171 // TODO: change link to issue overview for that version
172 "projects/versions/edit?id=" + sessionSelection.version.getId(), 2);
173 }
174 if (level == 2) entry.setActive(true);
175 breadcrumbs.add(entry);
176 }
178 if (sessionSelection.issue != null) {
179 entry = new MenuEntry(new ResourceKey("localization.projects", "menu.issues"),
180 // TODO: change link to a separate issue view (maybe depending on the selected version)
181 "projects/view?pid=" + sessionSelection.issue.getProject().getId(), 3);
182 breadcrumbs.add(entry);
183 if (sessionSelection.issue.getId() < 0) {
184 entry = new MenuEntry(new ResourceKey("localization.projects", "button.issue.create"),
185 "projects/issues/edit", 2);
186 } else {
187 entry = new MenuEntry("#" + sessionSelection.issue.getId(),
188 // TODO: maybe change link to a view rather than directly opening the editor
189 "projects/issues/edit?id=" + sessionSelection.issue.getId(), 4);
190 }
191 if (level == 3) entry.setActive(true);
192 breadcrumbs.add(entry);
193 }
195 return breadcrumbs;
196 }
198 @RequestMapping(method = HttpMethod.GET)
199 public ResponseType index(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
200 final var sessionSelection = new SessionSelection(req, dao);
201 final var projectList = dao.getProjectDao().list();
202 req.setAttribute("projects", projectList);
203 setContentPage(req, "projects");
204 setStylesheet(req, "projects");
206 setBreadcrumbs(req, getBreadcrumbs(0, sessionSelection));
208 return ResponseType.HTML;
209 }
211 private void configureEditForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
212 req.setAttribute("project", selection.project);
213 req.setAttribute("users", dao.getUserDao().list());
214 setContentPage(req, "project-form");
215 setBreadcrumbs(req, getBreadcrumbs(1, selection));
216 }
218 @RequestMapping(requestPath = "edit", method = HttpMethod.GET)
219 public ResponseType edit(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
220 final var selection = new SessionSelection(req, findByParameter(req, Integer.class, "id",
221 dao.getProjectDao()::find).orElse(new Project(-1)));
223 configureEditForm(req, dao, selection);
225 return ResponseType.HTML;
226 }
228 @RequestMapping(requestPath = "commit", method = HttpMethod.POST)
229 public ResponseType commit(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
231 Project project = new Project(-1);
232 try {
233 project = new Project(getParameter(req, Integer.class, "id").orElseThrow());
234 project.setName(getParameter(req, String.class, "name").orElseThrow());
235 getParameter(req, String.class, "description").ifPresent(project::setDescription);
236 getParameter(req, String.class, "repoUrl").ifPresent(project::setRepoUrl);
237 getParameter(req, Integer.class, "owner").map(
238 ownerId -> ownerId >= 0 ? new User(ownerId) : null
239 ).ifPresent(project::setOwner);
241 dao.getProjectDao().saveOrUpdate(project);
243 setRedirectLocation(req, "./projects/");
244 setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
245 LOG.debug("Successfully updated project {}", project.getName());
246 } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
247 // TODO: set request attribute with error text
248 LOG.warn("Form validation failure: {}", ex.getMessage());
249 LOG.debug("Details:", ex);
250 configureEditForm(req, dao, new SessionSelection(req, project));
251 }
253 return ResponseType.HTML;
254 }
256 @RequestMapping(requestPath = "view", method = HttpMethod.GET)
257 public ResponseType view(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
258 final var sessionSelection = new SessionSelection(req, dao);
260 req.setAttribute("versions", dao.getVersionDao().list(sessionSelection.project));
261 req.setAttribute("issues", dao.getIssueDao().list(sessionSelection.project));
263 setBreadcrumbs(req, getBreadcrumbs(1, sessionSelection));
264 setContentPage(req, "project-details");
266 return ResponseType.HTML;
267 }
269 private void configureEditVersionForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
270 req.setAttribute("projects", dao.getProjectDao().list());
271 req.setAttribute("version", selection.version);
272 req.setAttribute("versionStatusEnum", VersionStatus.values());
274 setContentPage(req, "version-form");
275 setBreadcrumbs(req, getBreadcrumbs(2, selection));
276 }
278 @RequestMapping(requestPath = "versions/edit", method = HttpMethod.GET)
279 public ResponseType editVersion(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
280 final var sessionSelection = new SessionSelection(req, dao);
282 sessionSelection.selectVersion(findByParameter(req, Integer.class, "id", dao.getVersionDao()::find)
283 .orElse(new Version(-1, sessionSelection.project)));
284 configureEditVersionForm(req, dao, sessionSelection);
286 return ResponseType.HTML;
287 }
289 @RequestMapping(requestPath = "versions/commit", method = HttpMethod.POST)
290 public ResponseType commitVersion(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
291 final var sessionSelection = new SessionSelection(req, dao);
293 var version = new Version(-1, sessionSelection.project);
294 try {
295 version = new Version(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
296 version.setName(getParameter(req, String.class, "name").orElseThrow());
297 getParameter(req, Integer.class, "ordinal").ifPresent(version::setOrdinal);
298 version.setStatus(VersionStatus.valueOf(getParameter(req, String.class, "status").orElseThrow()));
299 dao.getVersionDao().saveOrUpdate(version);
301 // specifying the pid parameter will purposely reset the session selected version!
302 setRedirectLocation(req, "./projects/view?pid="+sessionSelection.project.getId());
303 setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
304 LOG.debug("Successfully updated version {} for project {}", version.getName(), sessionSelection.project.getName());
305 } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
306 // TODO: set request attribute with error text
307 LOG.warn("Form validation failure: {}", ex.getMessage());
308 LOG.debug("Details:", ex);
309 sessionSelection.selectVersion(version);
310 configureEditVersionForm(req, dao, sessionSelection);
311 }
313 return ResponseType.HTML;
314 }
316 private void configureEditIssueForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
317 req.setAttribute("projects", dao.getProjectDao().list());
318 req.setAttribute("issue", selection.issue);
319 req.setAttribute("issueStatusEnum", IssueStatus.values());
320 req.setAttribute("issueCategoryEnum", IssueCategory.values());
321 req.setAttribute("users", dao.getUserDao().list());
323 setContentPage(req, "issue-form");
324 setBreadcrumbs(req, getBreadcrumbs(3, selection));
325 }
327 @RequestMapping(requestPath = "issues/edit", method = HttpMethod.GET)
328 public ResponseType editIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
329 final var sessionSelection = new SessionSelection(req, dao);
331 sessionSelection.selectIssue(findByParameter(req, Integer.class, "id",
332 dao.getIssueDao()::find).orElse(new Issue(-1, sessionSelection.project)));
333 configureEditIssueForm(req, dao, sessionSelection);
335 return ResponseType.HTML;
336 }
338 @RequestMapping(requestPath = "issues/commit", method = HttpMethod.POST)
339 public ResponseType commitIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
340 final var sessionSelection = new SessionSelection(req, dao);
342 Issue issue = new Issue(-1, sessionSelection.project);
343 try {
344 issue = new Issue(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
345 getParameter(req, String.class, "category").map(IssueCategory::valueOf).ifPresent(issue::setCategory);
346 getParameter(req, String.class, "status").map(IssueStatus::valueOf).ifPresent(issue::setStatus);
347 issue.setSubject(getParameter(req, String.class, "subject").orElseThrow());
348 getParameter(req, Integer.class, "assignee").map(
349 userid -> userid >= 0 ? new User(userid) : null
350 ).ifPresent(issue::setAssignee);
351 getParameter(req, String.class, "description").ifPresent(issue::setDescription);
352 getParameter(req, Date.class, "eta").ifPresent(issue::setEta);
353 dao.getIssueDao().saveOrUpdate(issue);
355 // TODO: redirect to issue overview
356 // specifying the issue parameter keeps the edited issue as breadcrumb
357 setRedirectLocation(req, "./projects/view?issue="+issue.getId());
358 setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
359 LOG.debug("Successfully updated issue {} for project {}", issue.getId(), sessionSelection.project.getName());
360 } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
361 // TODO: set request attribute with error text
362 LOG.warn("Form validation failure: {}", ex.getMessage());
363 LOG.debug("Details:", ex);
364 sessionSelection.selectIssue(issue);
365 configureEditIssueForm(req, dao, sessionSelection);
366 }
368 return ResponseType.HTML;
369 }
370 }