src/main/java/de/uapcore/lightpit/modules/ProjectsModule.java

Fri, 22 May 2020 21:23:57 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 22 May 2020 21:23:57 +0200
changeset 75
33b6843fdf8a
parent 74
91d1fc2a3a14
child 76
82f71fb1758a
permissions
-rw-r--r--

adds the ability to create and edit issues

     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 (!version.getProject().equals(project)) 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 (!issue.getProject().equals(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, SessionSelection selection) {
   270         req.setAttribute("version", selection.version);
   271         req.setAttribute("versionStatusEnum", VersionStatus.values());
   273         setContentPage(req, "version-form");
   274         setBreadcrumbs(req, getBreadcrumbs(2, selection));
   275     }
   277     @RequestMapping(requestPath = "versions/edit", method = HttpMethod.GET)
   278     public ResponseType editVersion(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   279         final var sessionSelection = new SessionSelection(req, dao);
   280         if (sessionSelection.project == null) {
   281             // TODO: remove this bullshit and only retrieve the object from session if we are creating a fresh version
   282             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
   283             return ResponseType.NONE;
   284         }
   286         sessionSelection.selectVersion(findByParameter(req, Integer.class, "id", dao.getVersionDao()::find)
   287                 .orElse(new Version(-1, sessionSelection.project)));
   288         configureEditVersionForm(req, sessionSelection);
   290         return ResponseType.HTML;
   291     }
   293     @RequestMapping(requestPath = "versions/commit", method = HttpMethod.POST)
   294     public ResponseType commitVersion(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   295         final var sessionSelection = new SessionSelection(req, dao);
   296         if (sessionSelection.project == null) {
   297             // TODO: remove this bullshit and retrieve project id from hidden field
   298             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
   299             return ResponseType.NONE;
   300         }
   302         var version = new Version(-1, sessionSelection.project);
   303         try {
   304             version = new Version(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
   305             version.setName(getParameter(req, String.class, "name").orElseThrow());
   306             getParameter(req, Integer.class, "ordinal").ifPresent(version::setOrdinal);
   307             version.setStatus(VersionStatus.valueOf(getParameter(req, String.class, "status").orElseThrow()));
   308             dao.getVersionDao().saveOrUpdate(version);
   310             // specifying the pid parameter will purposely reset the session selected version!
   311             setRedirectLocation(req, "./projects/view?pid="+sessionSelection.project.getId());
   312             setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
   313             LOG.debug("Successfully updated version {} for project {}", version.getName(), sessionSelection.project.getName());
   314         } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
   315             // TODO: set request attribute with error text
   316             LOG.warn("Form validation failure: {}", ex.getMessage());
   317             LOG.debug("Details:", ex);
   318             sessionSelection.selectVersion(version);
   319             configureEditVersionForm(req, sessionSelection);
   320         }
   322         return ResponseType.HTML;
   323     }
   325     private void configureEditIssueForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
   326         req.setAttribute("issue", selection.issue);
   327         req.setAttribute("issueStatusEnum", IssueStatus.values());
   328         req.setAttribute("issueCategoryEnum", IssueCategory.values());
   329         req.setAttribute("versions", dao.getVersionDao().list(selection.project));
   330         req.setAttribute("users", dao.getUserDao().list());
   332         setContentPage(req, "issue-form");
   333         setBreadcrumbs(req, getBreadcrumbs(3, selection));
   334     }
   336     @RequestMapping(requestPath = "issues/edit", method = HttpMethod.GET)
   337     public ResponseType editIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   338         final var sessionSelection = new SessionSelection(req, dao);
   339         if (sessionSelection.project == null) {
   340             // TODO: remove this bullshit and only retrieve the object from session if we are creating a fresh issue
   341             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
   342             return ResponseType.NONE;
   343         }
   345         sessionSelection.selectIssue(findByParameter(req, Integer.class, "id",
   346                 dao.getIssueDao()::find).orElse(new Issue(-1, sessionSelection.project)));
   347         configureEditIssueForm(req, dao, sessionSelection);
   349         return ResponseType.HTML;
   350     }
   352     @RequestMapping(requestPath = "issues/commit", method = HttpMethod.POST)
   353     public ResponseType commitIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   354         // TODO: remove this bullshit and store the project ID as hidden field
   355         final var sessionSelection = new SessionSelection(req, dao);
   356         if (sessionSelection.project == null) {
   357             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
   358             return ResponseType.NONE;
   359         }
   361         Issue issue = new Issue(-1, sessionSelection.project);
   362         try {
   363             issue = new Issue(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
   364             getParameter(req, String.class, "category").map(IssueCategory::valueOf).ifPresent(issue::setCategory);
   365             getParameter(req, String.class, "status").map(IssueStatus::valueOf).ifPresent(issue::setStatus);
   366             issue.setSubject(getParameter(req, String.class, "subject").orElseThrow());
   367             getParameter(req, Integer.class, "assignee").map(
   368                     userid -> userid >= 0 ? new User(userid) : null
   369             ).ifPresent(issue::setAssignee);
   370             getParameter(req, String.class, "description").ifPresent(issue::setDescription);
   371             getParameter(req, Date.class, "eta").ifPresent(issue::setEta);
   372             dao.getIssueDao().saveOrUpdate(issue);
   374             // TODO: redirect to issue overview
   375             // specifying the issue parameter keeps the edited issue as breadcrumb
   376             setRedirectLocation(req, "./projects/view?issue="+issue.getId());
   377             setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
   378             LOG.debug("Successfully updated issue {} for project {}", issue.getId(), sessionSelection.project.getName());
   379         } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
   380             // TODO: set request attribute with error text
   381             LOG.warn("Form validation failure: {}", ex.getMessage());
   382             LOG.debug("Details:", ex);
   383             sessionSelection.selectIssue(issue);
   384             configureEditIssueForm(req, dao, sessionSelection);
   385         }
   387         return ResponseType.HTML;
   388     }
   389 }

mercurial