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

Sat, 23 May 2020 13:52:04 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 23 May 2020 13:52:04 +0200
changeset 78
bb4c52bf3439
parent 76
82f71fb1758a
child 79
f64255a88d66
permissions
-rw-r--r--

bloat removal 2/3 - moduleInfo

     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     }
   136     @Override
   137     protected String getResourceBundleName() {
   138         return "localization.projects";
   139     }
   141     /**
   142      * Creates the breadcrumb menu.
   143      *
   144      * @param level           the current active level (0: root, 1: project, 2: version, 3: issue)
   145      * @param sessionSelection the currently selected objects
   146      * @return a dynamic breadcrumb menu trying to display as many levels as possible
   147      */
   148     private List<MenuEntry> getBreadcrumbs(int level, SessionSelection sessionSelection) {
   149         MenuEntry entry;
   151         final var breadcrumbs = new ArrayList<MenuEntry>();
   152         entry = new MenuEntry(new ResourceKey("localization.projects", "menuLabel"),
   153                 "projects/", 0);
   154         breadcrumbs.add(entry);
   155         if (level == 0) entry.setActive(true);
   157         if (sessionSelection.project != null) {
   158             if (sessionSelection.project.getId() < 0) {
   159                 entry = new MenuEntry(new ResourceKey("localization.projects", "button.create"),
   160                         "projects/edit", 1);
   161             } else {
   162                 entry = new MenuEntry(sessionSelection.project.getName(),
   163                         "projects/view?pid=" + sessionSelection.project.getId(), 1);
   164             }
   165             if (level == 1) entry.setActive(true);
   166             breadcrumbs.add(entry);
   167         }
   169         if (sessionSelection.version != null) {
   170             if (sessionSelection.version.getId() < 0) {
   171                 entry = new MenuEntry(new ResourceKey("localization.projects", "button.version.create"),
   172                         "projects/versions/edit", 2);
   173             } else {
   174                 entry = new MenuEntry(sessionSelection.version.getName(),
   175                         // TODO: change link to issue overview for that version
   176                         "projects/versions/edit?id=" + sessionSelection.version.getId(), 2);
   177             }
   178             if (level == 2) entry.setActive(true);
   179             breadcrumbs.add(entry);
   180         }
   182         if (sessionSelection.issue != null) {
   183             entry = new MenuEntry(new ResourceKey("localization.projects", "menu.issues"),
   184                     // TODO: change link to a separate issue view (maybe depending on the selected version)
   185                     "projects/view?pid=" + sessionSelection.issue.getProject().getId(), 3);
   186             breadcrumbs.add(entry);
   187             if (sessionSelection.issue.getId() < 0) {
   188                 entry = new MenuEntry(new ResourceKey("localization.projects", "button.issue.create"),
   189                         "projects/issues/edit", 2);
   190             } else {
   191                 entry = new MenuEntry("#" + sessionSelection.issue.getId(),
   192                         // TODO: maybe change link to a view rather than directly opening the editor
   193                         "projects/issues/edit?id=" + sessionSelection.issue.getId(), 4);
   194             }
   195             if (level == 3) entry.setActive(true);
   196             breadcrumbs.add(entry);
   197         }
   199         return breadcrumbs;
   200     }
   202     @RequestMapping(method = HttpMethod.GET)
   203     public ResponseType index(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
   204         final var sessionSelection = new SessionSelection(req, dao);
   205         final var projectList = dao.getProjectDao().list();
   206         req.setAttribute("projects", projectList);
   207         setContentPage(req, "projects");
   208         setStylesheet(req, "projects");
   210         setBreadcrumbs(req, getBreadcrumbs(0, sessionSelection));
   212         return ResponseType.HTML;
   213     }
   215     private void configureEditForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
   216         req.setAttribute("project", selection.project);
   217         req.setAttribute("users", dao.getUserDao().list());
   218         setContentPage(req, "project-form");
   219         setBreadcrumbs(req, getBreadcrumbs(1, selection));
   220     }
   222     @RequestMapping(requestPath = "edit", method = HttpMethod.GET)
   223     public ResponseType edit(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
   224         final var selection = new SessionSelection(req, findByParameter(req, Integer.class, "id",
   225                 dao.getProjectDao()::find).orElse(new Project(-1)));
   227         configureEditForm(req, dao, selection);
   229         return ResponseType.HTML;
   230     }
   232     @RequestMapping(requestPath = "commit", method = HttpMethod.POST)
   233     public ResponseType commit(HttpServletRequest req, DataAccessObjects dao) throws SQLException {
   235         Project project = new Project(-1);
   236         try {
   237             project = new Project(getParameter(req, Integer.class, "id").orElseThrow());
   238             project.setName(getParameter(req, String.class, "name").orElseThrow());
   239             getParameter(req, String.class, "description").ifPresent(project::setDescription);
   240             getParameter(req, String.class, "repoUrl").ifPresent(project::setRepoUrl);
   241             getParameter(req, Integer.class, "owner").map(
   242                     ownerId -> ownerId >= 0 ? new User(ownerId) : null
   243             ).ifPresent(project::setOwner);
   245             dao.getProjectDao().saveOrUpdate(project);
   247             setRedirectLocation(req, "./projects/");
   248             setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
   249             LOG.debug("Successfully updated project {}", project.getName());
   250         } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
   251             // TODO: set request attribute with error text
   252             LOG.warn("Form validation failure: {}", ex.getMessage());
   253             LOG.debug("Details:", ex);
   254             configureEditForm(req, dao, new SessionSelection(req, project));
   255         }
   257         return ResponseType.HTML;
   258     }
   260     @RequestMapping(requestPath = "view", method = HttpMethod.GET)
   261     public ResponseType view(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   262         final var sessionSelection = new SessionSelection(req, dao);
   264         req.setAttribute("versions", dao.getVersionDao().list(sessionSelection.project));
   265         req.setAttribute("issues", dao.getIssueDao().list(sessionSelection.project));
   267         setBreadcrumbs(req, getBreadcrumbs(1, sessionSelection));
   268         setContentPage(req, "project-details");
   270         return ResponseType.HTML;
   271     }
   273     private void configureEditVersionForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
   274         req.setAttribute("projects", dao.getProjectDao().list());
   275         req.setAttribute("version", selection.version);
   276         req.setAttribute("versionStatusEnum", VersionStatus.values());
   278         setContentPage(req, "version-form");
   279         setBreadcrumbs(req, getBreadcrumbs(2, selection));
   280     }
   282     @RequestMapping(requestPath = "versions/edit", method = HttpMethod.GET)
   283     public ResponseType editVersion(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   284         final var sessionSelection = new SessionSelection(req, dao);
   286         sessionSelection.selectVersion(findByParameter(req, Integer.class, "id", dao.getVersionDao()::find)
   287                 .orElse(new Version(-1, sessionSelection.project)));
   288         configureEditVersionForm(req, dao, 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);
   297         var version = new Version(-1, sessionSelection.project);
   298         try {
   299             version = new Version(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
   300             version.setName(getParameter(req, String.class, "name").orElseThrow());
   301             getParameter(req, Integer.class, "ordinal").ifPresent(version::setOrdinal);
   302             version.setStatus(VersionStatus.valueOf(getParameter(req, String.class, "status").orElseThrow()));
   303             dao.getVersionDao().saveOrUpdate(version);
   305             // specifying the pid parameter will purposely reset the session selected version!
   306             setRedirectLocation(req, "./projects/view?pid="+sessionSelection.project.getId());
   307             setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
   308             LOG.debug("Successfully updated version {} for project {}", version.getName(), sessionSelection.project.getName());
   309         } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
   310             // TODO: set request attribute with error text
   311             LOG.warn("Form validation failure: {}", ex.getMessage());
   312             LOG.debug("Details:", ex);
   313             sessionSelection.selectVersion(version);
   314             configureEditVersionForm(req, dao, sessionSelection);
   315         }
   317         return ResponseType.HTML;
   318     }
   320     private void configureEditIssueForm(HttpServletRequest req, DataAccessObjects dao, SessionSelection selection) throws SQLException {
   321         req.setAttribute("projects", dao.getProjectDao().list());
   322         req.setAttribute("issue", selection.issue);
   323         req.setAttribute("issueStatusEnum", IssueStatus.values());
   324         req.setAttribute("issueCategoryEnum", IssueCategory.values());
   325         req.setAttribute("users", dao.getUserDao().list());
   327         setContentPage(req, "issue-form");
   328         setBreadcrumbs(req, getBreadcrumbs(3, selection));
   329     }
   331     @RequestMapping(requestPath = "issues/edit", method = HttpMethod.GET)
   332     public ResponseType editIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   333         final var sessionSelection = new SessionSelection(req, dao);
   335         sessionSelection.selectIssue(findByParameter(req, Integer.class, "id",
   336                 dao.getIssueDao()::find).orElse(new Issue(-1, sessionSelection.project)));
   337         configureEditIssueForm(req, dao, sessionSelection);
   339         return ResponseType.HTML;
   340     }
   342     @RequestMapping(requestPath = "issues/commit", method = HttpMethod.POST)
   343     public ResponseType commitIssue(HttpServletRequest req, HttpServletResponse resp, DataAccessObjects dao) throws IOException, SQLException {
   344         final var sessionSelection = new SessionSelection(req, dao);
   346         Issue issue = new Issue(-1, sessionSelection.project);
   347         try {
   348             issue = new Issue(getParameter(req, Integer.class, "id").orElseThrow(), sessionSelection.project);
   349             getParameter(req, String.class, "category").map(IssueCategory::valueOf).ifPresent(issue::setCategory);
   350             getParameter(req, String.class, "status").map(IssueStatus::valueOf).ifPresent(issue::setStatus);
   351             issue.setSubject(getParameter(req, String.class, "subject").orElseThrow());
   352             getParameter(req, Integer.class, "assignee").map(
   353                     userid -> userid >= 0 ? new User(userid) : null
   354             ).ifPresent(issue::setAssignee);
   355             getParameter(req, String.class, "description").ifPresent(issue::setDescription);
   356             getParameter(req, Date.class, "eta").ifPresent(issue::setEta);
   357             dao.getIssueDao().saveOrUpdate(issue);
   359             // TODO: redirect to issue overview
   360             // specifying the issue parameter keeps the edited issue as breadcrumb
   361             setRedirectLocation(req, "./projects/view?issue="+issue.getId());
   362             setContentPage(req, Constants.JSP_COMMIT_SUCCESSFUL);
   363             LOG.debug("Successfully updated issue {} for project {}", issue.getId(), sessionSelection.project.getName());
   364         } catch (NoSuchElementException | IllegalArgumentException | SQLException ex) {
   365             // TODO: set request attribute with error text
   366             LOG.warn("Form validation failure: {}", ex.getMessage());
   367             LOG.debug("Details:", ex);
   368             sessionSelection.selectIssue(issue);
   369             configureEditIssueForm(req, dao, sessionSelection);
   370         }
   372         return ResponseType.HTML;
   373     }
   374 }

mercurial