From 8fbce550286d4dcd6ba02dce5104690653f8cdfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Wed, 17 Apr 2019 11:04:35 +0300 Subject: [PATCH 01/37] #86 projects main page --- .../project/controller/ProjectController.java | 39 +++++++++++++++++++ .../ulstu/project/service/ProjectService.java | 9 +++++ src/main/resources/templates/index.html | 2 +- .../templates/projects/dashboard.html | 24 ++++++++++++ .../fragments/projectNavigationFragment.html | 26 +++++++++++++ .../templates/projects/projects.html | 33 ++++++++++++++++ 6 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 src/main/java/ru/ulstu/project/controller/ProjectController.java create mode 100644 src/main/resources/templates/projects/dashboard.html create mode 100644 src/main/resources/templates/projects/fragments/projectNavigationFragment.html create mode 100644 src/main/resources/templates/projects/projects.html diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java new file mode 100644 index 0000000..5b5eb4a --- /dev/null +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -0,0 +1,39 @@ +package ru.ulstu.project.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.validation.Errors; +import org.springframework.web.bind.annotation.*; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.project.model.Project; +import ru.ulstu.project.model.ProjectDto; +import ru.ulstu.project.service.ProjectService; +import springfox.documentation.annotations.ApiIgnore; + +import javax.validation.Valid; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +import static liquibase.util.StringUtils.isEmpty; + +@Controller() +@RequestMapping(value = "/projects") +@ApiIgnore +public class ProjectController { + private final ProjectService projectService; + + public ProjectController(ProjectService projectService) { + this.projectService = projectService; + } + + @GetMapping("/dashboard") + public void getDashboard(ModelMap modelMap) { + modelMap.put("projects", projectService.findAllDto()); + } + + @GetMapping("/projects") + public void getProjects(ModelMap modelMap) { + modelMap.put("projects", projectService.findAllDto()); + } +} diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index b54a60a..78a9d3c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -2,6 +2,7 @@ package ru.ulstu.project.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; @@ -10,9 +11,11 @@ import ru.ulstu.project.repository.ProjectRepository; import java.util.List; import static org.springframework.util.ObjectUtils.isEmpty; +import static ru.ulstu.core.util.StreamApiUtils.convert; @Service public class ProjectService { + private final static int MAX_DISPLAY_SIZE = 40; private final ProjectRepository projectRepository; private final DeadlineService deadlineService; @@ -27,6 +30,12 @@ public class ProjectService { return projectRepository.findAll(); } + public List findAllDto() { + List projects = convert(findAll(), ProjectDto::new); + projects.forEach(projectDto -> projectDto.setTitle(StringUtils.abbreviate(projectDto.getTitle(), MAX_DISPLAY_SIZE))); + return projects; + } + @Transactional public Project create(ProjectDto projectDto) { Project newProject = copyFromDto(new Project(), projectDto); diff --git a/src/main/resources/templates/index.html b/src/main/resources/templates/index.html index 2d86945..6ca1c12 100644 --- a/src/main/resources/templates/index.html +++ b/src/main/resources/templates/index.html @@ -46,7 +46,7 @@
- +
diff --git a/src/main/resources/templates/projects/dashboard.html b/src/main/resources/templates/projects/dashboard.html new file mode 100644 index 0000000..882c202 --- /dev/null +++ b/src/main/resources/templates/projects/dashboard.html @@ -0,0 +1,24 @@ + + + + + +
+
+
+
+

Проекты

+
+
+
+ +
+ +
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectNavigationFragment.html b/src/main/resources/templates/projects/fragments/projectNavigationFragment.html new file mode 100644 index 0000000..c26d8b8 --- /dev/null +++ b/src/main/resources/templates/projects/fragments/projectNavigationFragment.html @@ -0,0 +1,26 @@ + + + + + + +
+ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/projects.html b/src/main/resources/templates/projects/projects.html new file mode 100644 index 0000000..0336770 --- /dev/null +++ b/src/main/resources/templates/projects/projects.html @@ -0,0 +1,33 @@ + + + + + +
+
+ +
+
+
+
+

Проекты

+
+
+
+
+
+ +
+ +
+
+
+
+
+
+
+
+ + From ee55e08feee4ea20dfa52403996f0659cd42f1d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 6 May 2019 17:43:20 +0300 Subject: [PATCH 02/37] #98 project tasks deadline edited --- .../conference/service/ConferenceService.java | 3 +- .../ru/ulstu/deadline/model/Deadline.java | 35 ++++++++++++++++--- .../ru/ulstu/grant/service/GrantService.java | 2 +- .../ru/ulstu/paper/service/PaperService.java | 2 +- .../project/controller/ProjectController.java | 7 ++++ .../ru/ulstu/project/model/ProjectDto.java | 9 +++++ .../ulstu/project/service/ProjectService.java | 7 ++++ .../db/changelog-20190506_000000-schema.xml | 13 +++++++ src/main/resources/db/changelog-master.xml | 1 + .../resources/templates/projects/project.html | 8 +++-- 10 files changed, 78 insertions(+), 9 deletions(-) create mode 100644 src/main/resources/db/changelog-20190506_000000-schema.xml diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38de435..b42f981 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -267,7 +267,8 @@ public class ConferenceService { } public Deadline copyDeadline(Deadline oldDeadline) { - Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); + Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription(), + oldDeadline.getExecutor(), oldDeadline.getDone()); newDeadline.setId(oldDeadline.getId()); return newDeadline; } diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 148697c..9ab9acd 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -20,21 +20,30 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; + private String executor; + private Boolean done; + public Deadline() { } - public Deadline(Date deadlineDate, String description) { + public Deadline(Date deadlineDate, String description, String executor, Boolean done) { this.date = deadlineDate; this.description = description; + this.executor = executor; + this.done = done; } @JsonCreator public Deadline(@JsonProperty("id") Integer id, @JsonProperty("description") String description, - @JsonProperty("date") Date date) { + @JsonProperty("date") Date date, + @JsonProperty("executor") String executor, + @JsonProperty("done") Boolean done) { this.setId(id); this.description = description; this.date = date; + this.executor = executor; + this.done = done; } public String getDescription() { @@ -53,6 +62,22 @@ public class Deadline extends BaseEntity { this.date = date; } + public String getExecutor() { + return executor; + } + + public void setExecutor(String executor) { + this.executor = executor; + } + + public Boolean getDone() { + return done; + } + + public void setDone(Boolean done) { + this.done = done; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -67,11 +92,13 @@ public class Deadline extends BaseEntity { Deadline deadline = (Deadline) o; return getId().equals(deadline.getId()) && description.equals(deadline.description) && - date.equals(deadline.date); + date.equals(deadline.date) && + executor.equals(deadline.executor) && + done.equals(deadline.done); } @Override public int hashCode() { - return Objects.hash(super.hashCode(), description, date); + return Objects.hash(super.hashCode(), description, date, executor, done); } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 9cff4b6..0837b49 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -141,7 +141,7 @@ public class GrantService { grant.setComment("Комментарий к гранту 1"); grant.setProject(projectId); grant.setStatus(APPLICATION); - grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); + grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); grant.getAuthors().add(user); grant.setLeader(user); grant.getPapers().add(paper); diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index f98997d..1188c28 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -173,7 +173,7 @@ public class PaperService { Paper paper = new Paper(); paper.setTitle(title); paper.getAuthors().add(user); - paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); + paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); paper.setCreateDate(new Date()); paper.setUpdateDate(new Date()); paper.setStatus(DRAFT); diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java index ae09658..14b8736 100644 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -79,6 +79,13 @@ public class ProjectController { return "/projects/project"; } + @PostMapping(value = "/project", params = "removeDeadline") + public String removeDeadline(ProjectDto projectDto, + @RequestParam(value = "removeDeadline") Integer deadlineId) { + projectService.removeDeadline(projectDto, deadlineId); + return "/projects/project"; + } + @GetMapping("/delete/{project-id}") public String delete(@PathVariable("project-id") Integer projectId) throws IOException { projectService.delete(projectId); diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 4e03365..319609c 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -20,6 +20,7 @@ public class ProjectDto { private GrantDto grant; private String repository; private String applicationFileName; + private List removedDeadlineIds = new ArrayList<>(); public ProjectDto() { } @@ -121,4 +122,12 @@ public class ProjectDto { public void setApplicationFileName(String applicationFileName) { this.applicationFileName = applicationFileName; } + + public List getRemovedDeadlineIds() { + return removedDeadlineIds; + } + + public void setRemovedDeadlineIds(List removedDeadlineIds) { + this.removedDeadlineIds = removedDeadlineIds; + } } diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 247624d..4a79e6c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -104,6 +104,13 @@ public class ProjectService { } } + public void removeDeadline(ProjectDto projectDto, Integer deadlineId) { + if (projectDto.getDeadlines().get(deadlineId).getId() != null) { + projectDto.getRemovedDeadlineIds().add(projectDto.getDeadlines().get(deadlineId).getId()); + } + projectDto.getDeadlines().remove((int) deadlineId); + } + public Project findById(Integer id) { return projectRepository.findOne(id); } diff --git a/src/main/resources/db/changelog-20190506_000000-schema.xml b/src/main/resources/db/changelog-20190506_000000-schema.xml new file mode 100644 index 0000000..cd5a59b --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000000-schema.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 83ff280..3b455a8 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -38,4 +38,5 @@ + \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index dc3fa6d..cd49319 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -73,14 +73,18 @@
-
+
-
+
+
+ +
-
+
-
+
-
+
-
- -
+
+
+
+ +
+
+
From 4025aa67ca1720d75cdda18dcf4221868470f162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 6 May 2019 21:51:58 +0300 Subject: [PATCH 04/37] #98 project completion added --- .../java/ru/ulstu/project/model/Project.java | 16 ++++++++ .../ru/ulstu/project/model/ProjectDto.java | 41 ++++++++++++++++++- .../db/changelog-20190506_000001-schema.xml | 17 ++++++++ src/main/resources/db/changelog-master.xml | 1 + src/main/resources/public/css/project.css | 5 +++ .../resources/templates/projects/project.html | 15 +++---- 6 files changed, 87 insertions(+), 8 deletions(-) create mode 100644 src/main/resources/db/changelog-20190506_000001-schema.xml create mode 100644 src/main/resources/public/css/project.css diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index c971c4b..acf0d0f 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -5,17 +5,22 @@ import ru.ulstu.core.model.BaseEntity; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; import ru.ulstu.grant.model.Grant; +import ru.ulstu.user.model.User; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.FetchType; import javax.persistence.JoinColumn; +import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.constraints.NotNull; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Entity public class Project extends BaseEntity { @@ -62,6 +67,9 @@ public class Project extends BaseEntity { @JoinColumn(name = "file_id") private FileData application; + @ManyToMany(fetch = FetchType.EAGER) + private Set executors = new HashSet<>(); + public String getTitle() { return title; } @@ -117,4 +125,12 @@ public class Project extends BaseEntity { public void setApplication(FileData application) { this.application = application; } + + public Set getExecutors() { + return executors; + } + + public void setExecutors(Set executors) { + this.executors = executors; + } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 319609c..0f86e1a 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -3,11 +3,17 @@ package ru.ulstu.project.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; +import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.model.UserDto; import java.util.ArrayList; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static ru.ulstu.core.util.StreamApiUtils.convert; public class ProjectDto { private Integer id; @@ -21,6 +27,10 @@ public class ProjectDto { private String repository; private String applicationFileName; private List removedDeadlineIds = new ArrayList<>(); + private Set executorIds; + private Set executors; + + private final static int MAX_EXECUTORS_LENGTH = 40; public ProjectDto() { } @@ -36,7 +46,9 @@ public class ProjectDto { @JsonProperty("description") String description, @JsonProperty("grant") GrantDto grant, @JsonProperty("repository") String repository, - @JsonProperty("deadlines") List deadlines) { + @JsonProperty("deadlines") List deadlines, + @JsonProperty("executorIds") Set executorIds, + @JsonProperty("executors") Set executors) { this.id = id; this.title = title; this.status = status; @@ -45,6 +57,8 @@ public class ProjectDto { this.repository = repository; this.deadlines = deadlines; this.applicationFileName = null; + this.executorIds = executorIds; + this.executors = executors; } @@ -57,6 +71,8 @@ public class ProjectDto { this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.repository = project.getRepository(); this.deadlines = project.getDeadlines(); + this.executorIds = convert(project.getExecutors(), user -> user.getId()); + this.executors = convert(project.getExecutors(), UserDto::new); } public Integer getId() { @@ -130,4 +146,27 @@ public class ProjectDto { public void setRemovedDeadlineIds(List removedDeadlineIds) { this.removedDeadlineIds = removedDeadlineIds; } + + public Set getExecutorIds() { + return executorIds; + } + + public void setExecutorIds(Set executorIds) { + this.executorIds = executorIds; + } + + public Set getExecutors() { + return executors; + } + + public void setExecutors(Set executors) { + this.executors = executors; + } + + public String getExecutorsString() { + return StringUtils.abbreviate(executors + .stream() + .map(executor -> executor.getLastName()) + .collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH); + } } diff --git a/src/main/resources/db/changelog-20190506_000001-schema.xml b/src/main/resources/db/changelog-20190506_000001-schema.xml new file mode 100644 index 0000000..e28d009 --- /dev/null +++ b/src/main/resources/db/changelog-20190506_000001-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 3b455a8..051c953 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -39,4 +39,5 @@ + \ No newline at end of file diff --git a/src/main/resources/public/css/project.css b/src/main/resources/public/css/project.css new file mode 100644 index 0000000..24e12ea --- /dev/null +++ b/src/main/resources/public/css/project.css @@ -0,0 +1,5 @@ +.div-deadline-done { + width: 60%; + height: 100%; + float: right; +} \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index 2a0b7cf..8385694 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -3,7 +3,7 @@ xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> - + @@ -90,17 +90,18 @@ aria-hidden="true">
-
-

Incorrect title

-
-
-
+
+
+ +
+

Incorrect title

Date: Mon, 6 May 2019 22:10:40 +0300 Subject: [PATCH 05/37] #98 deadline edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 5a05ea1..9ab9acd 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -66,7 +66,9 @@ public class Deadline extends BaseEntity { return executor; } - public void setExecutor(String executor) { this.executor = executor; } + public void setExecutor(String executor) { + this.executor = executor; + } public Boolean getDone() { return done; From f960d4de1b78cd9a8cd01ea43bdd6304fcc7d844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Fri, 17 May 2019 11:30:26 +0300 Subject: [PATCH 06/37] #98 deadline model edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 5 +++++ src/main/java/ru/ulstu/grant/service/GrantService.java | 2 +- src/main/java/ru/ulstu/paper/service/PaperService.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 9ab9acd..5ab9f47 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -26,6 +26,11 @@ public class Deadline extends BaseEntity { public Deadline() { } + public Deadline(Date deadlineDate, String description) { + this.date = deadlineDate; + this.description = description; + } + public Deadline(Date deadlineDate, String description, String executor, Boolean done) { this.date = deadlineDate; this.description = description; diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index c06a71c..45f9b2f 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -164,7 +164,7 @@ public class GrantService { grant.setComment("Комментарий к гранту 1"); grant.setProject(projectId); grant.setStatus(APPLICATION); - grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); + grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); grant.getAuthors().add(user); grant.setLeader(user); grant.getPapers().add(paper); diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index 0a60c92..db810f5 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -173,7 +173,7 @@ public class PaperService { Paper paper = new Paper(); paper.setTitle(title); paper.getAuthors().add(user); - paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн", "", false)); + paper.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн")); paper.setCreateDate(new Date()); paper.setUpdateDate(new Date()); paper.setStatus(DRAFT); From 1823c1ba50c959dde3197fbfa64a516e9ffa1b3c Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 18:37:24 +0400 Subject: [PATCH 07/37] #120 create kias page --- src/test/java/grant/KiasPage.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/test/java/grant/KiasPage.java diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java new file mode 100644 index 0000000..49b40d9 --- /dev/null +++ b/src/test/java/grant/KiasPage.java @@ -0,0 +1,28 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class KiasPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h1")).getText(); + } + + public List getGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + return listContest.findElements(By.cssSelector("tr.tr")); + + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public String getFirstDeadline(WebElement grant) { + return grant.findElement(By.xpath("./td[5]")).getText(); + } +} From c0e66e81a2e50d85a0859d1f779572a7e1065f1a Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 20:47:10 +0400 Subject: [PATCH 08/37] #120 drop unnecessary table column --- .../resources/db/changelog-20190520_000000-schema.xml | 8 ++++++++ src/main/resources/db/changelog-master.xml | 1 + 2 files changed, 9 insertions(+) create mode 100644 src/main/resources/db/changelog-20190520_000000-schema.xml diff --git a/src/main/resources/db/changelog-20190520_000000-schema.xml b/src/main/resources/db/changelog-20190520_000000-schema.xml new file mode 100644 index 0000000..69cdad0 --- /dev/null +++ b/src/main/resources/db/changelog-20190520_000000-schema.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 18bd645..d2ccbca 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -42,4 +42,5 @@ + \ No newline at end of file From bb9f412480fc9948e41680a5a4c009a0c26f60b6 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Mon, 20 May 2019 20:49:03 +0400 Subject: [PATCH 09/37] #120 check unique grant name --- .../grant/controller/GrantController.java | 20 +--------- .../java/ru/ulstu/grant/model/GrantDto.java | 3 +- .../grant/repository/GrantRepository.java | 9 ++++- .../ru/ulstu/grant/service/GrantService.java | 37 ++++++++++++++++++- 4 files changed, 47 insertions(+), 22 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java index ad5e992..91b0f91 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -20,9 +20,7 @@ import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.io.IOException; import java.util.List; -import java.util.stream.Collectors; -import static org.springframework.util.StringUtils.isEmpty; import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; @@ -62,17 +60,9 @@ public class GrantController { @PostMapping(value = "/grant", params = "save") public String save(@Valid GrantDto grantDto, Errors errors) throws IOException { - filterEmptyDeadlines(grantDto); - if (grantDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); - } - if (grantDto.getLeaderId().equals(-1)) { - errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); - } - if (errors.hasErrors()) { + if (!grantService.save(grantDto, errors)) { return GRANT_PAGE; } - grantService.save(grantDto); return String.format(REDIRECT_TO, GRANTS_PAGE); } @@ -89,7 +79,7 @@ public class GrantController { @PostMapping(value = "/grant", params = "addDeadline") public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - filterEmptyDeadlines(grantDto); + grantService.filterEmptyDeadlines(grantDto); if (errors.hasErrors()) { return GRANT_PAGE; } @@ -133,10 +123,4 @@ public class GrantController { public List getAllPapers() { return grantService.getAllUncompletedPapers(); } - - private void filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } } diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index 203d306..5a561b1 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -6,6 +6,7 @@ import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileDataDto; +import ru.ulstu.name.NameContainer; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; @@ -17,7 +18,7 @@ import java.util.stream.Collectors; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class GrantDto { +public class GrantDto extends NameContainer { private final static int MAX_AUTHORS_LENGTH = 60; private Integer id; diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 44c2cc0..26face4 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -1,11 +1,18 @@ package ru.ulstu.grant.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.grant.model.Grant; +import ru.ulstu.name.BaseRepository; import java.util.List; -public interface GrantRepository extends JpaRepository { +public interface GrantRepository extends JpaRepository, BaseRepository { List findByStatus(Grant.GrantStatus status); + + @Override + @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 45f9b2f..4972b6c 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -3,6 +3,7 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; @@ -10,6 +11,7 @@ import ru.ulstu.file.service.FileService; import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; +import ru.ulstu.name.BaseService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.service.PaperService; @@ -27,6 +29,7 @@ import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static org.springframework.util.ObjectUtils.isEmpty; @@ -34,7 +37,7 @@ import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service -public class GrantService { +public class GrantService extends BaseService { private final static int MAX_DISPLAY_SIZE = 50; private final GrantRepository grantRepository; @@ -55,6 +58,7 @@ public class GrantService { EventService eventService, GrantNotificationService grantNotificationService) { this.grantRepository = grantRepository; + this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; this.projectService = projectService; @@ -176,12 +180,35 @@ public class GrantService { return grant; } - public void save(GrantDto grantDto) throws IOException { + public boolean save(GrantDto grantDto, Errors errors) throws IOException { + grantDto.setName(grantDto.getTitle()); + filterEmptyDeadlines(grantDto); + checkEmptyDeadlines(grantDto, errors); + checkEmptyLeader(grantDto, errors); + checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); + if (errors.hasErrors()) { + return false; + } + if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } + + return true; + } + + private void checkEmptyLeader(GrantDto grantDto, Errors errors) { + if (grantDto.getLeaderId().equals(-1)) { + errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); + } + } + + private void checkEmptyDeadlines(GrantDto grantDto, Errors errors) { + if (grantDto.getDeadlines().isEmpty()) { + errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); + } } public List getGrantAuthors(GrantDto grantDto) { @@ -261,4 +288,10 @@ public class GrantService { .filter(author -> Collections.frequency(authors, author) > 3) .collect(toList()); } + + public void filterEmptyDeadlines(GrantDto grantDto) { + grantDto.setDeadlines(grantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + } } From d7c4e6b22264bbd76b35fae997fb8fbfeb328d1c Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Tue, 21 May 2019 02:09:07 +0400 Subject: [PATCH 10/37] #91 base users dashboard --- .../repository/ConferenceRepository.java | 4 + .../conference/service/ConferenceService.java | 4 + .../service/ConferenceUserService.java | 2 - .../user/controller/UserMvcController.java | 5 + .../java/ru/ulstu/user/model/UserInfoNow.java | 50 ++++++++++ .../repository/UserSessionRepository.java | 3 + .../ru/ulstu/user/service/UserService.java | 37 ++++++- .../user/service/UserSessionService.java | 6 ++ .../utils/timetable/TimetableService.java | 97 +++++++++++++++++++ .../ru/ulstu/utils/timetable/model/Day.java | 27 ++++++ .../ulstu/utils/timetable/model/Lesson.java | 27 ++++++ .../ulstu/utils/timetable/model/Response.java | 16 +++ .../timetable/model/TimetableResponse.java | 22 +++++ .../ru/ulstu/utils/timetable/model/Week.java | 16 +++ .../resources/templates/users/dashboard.html | 24 +++++ .../fragments/userDashboardFragment.html | 18 ++++ 16 files changed, 355 insertions(+), 3 deletions(-) create mode 100644 src/main/java/ru/ulstu/user/model/UserInfoNow.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/TimetableService.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Day.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Lesson.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Response.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java create mode 100644 src/main/java/ru/ulstu/utils/timetable/model/Week.java create mode 100644 src/main/resources/templates/users/dashboard.html create mode 100644 src/main/resources/templates/users/fragments/userDashboardFragment.html diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java index 2b0a428..8f9e05f 100644 --- a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java +++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java @@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository @Override @Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " + + "AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)") + Conference findActiveByUser(@Param("user") User user); } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 38ce659..1a5db52 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -306,4 +306,8 @@ public class ConferenceService extends BaseService { .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .collect(Collectors.toList())); } + + public Conference getActiveConferenceByUser(User user) { + return conferenceRepository.findActiveByUser(user); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java index f771b2a..16842c1 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java @@ -43,6 +43,4 @@ public class ConferenceUserService { newUser = conferenceUserRepository.save(newUser); return newUser; } - - } diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java index 5bcbd13..d283a21 100644 --- a/src/main/java/ru/ulstu/user/controller/UserMvcController.java +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -48,4 +48,9 @@ public class UserMvcController extends OdinController { User user = userSessionService.getUserBySessionId(sessionId); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); } + + @GetMapping("/dashboard") + public void getUsersDashboard(ModelMap modelMap) { + modelMap.addAttribute("users", userService.getUsersInfo()); + } } diff --git a/src/main/java/ru/ulstu/user/model/UserInfoNow.java b/src/main/java/ru/ulstu/user/model/UserInfoNow.java new file mode 100644 index 0000000..7d69c56 --- /dev/null +++ b/src/main/java/ru/ulstu/user/model/UserInfoNow.java @@ -0,0 +1,50 @@ +package ru.ulstu.user.model; + +import ru.ulstu.conference.model.Conference; +import ru.ulstu.utils.timetable.model.Lesson; + +public class UserInfoNow { + private Lesson lesson; + private Conference conference; + private User user; + private boolean isOnline; + + public UserInfoNow(Lesson lesson, Conference conference, User user, boolean isOnline) { + this.lesson = lesson; + this.conference = conference; + this.user = user; + this.isOnline = isOnline; + } + + public Lesson getLesson() { + return lesson; + } + + public void setLesson(Lesson lesson) { + this.lesson = lesson; + } + + public Conference getConference() { + return conference; + } + + public void setConference(Conference conference) { + this.conference = conference; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public boolean isOnline() { + return isOnline; + } + + public void setOnline(boolean online) { + isOnline = online; + } +} diff --git a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java index b922e4f..5319245 100644 --- a/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java +++ b/src/main/java/ru/ulstu/user/repository/UserSessionRepository.java @@ -1,6 +1,7 @@ package ru.ulstu.user.repository; import org.springframework.data.jpa.repository.JpaRepository; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserSession; import java.util.Date; @@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); + + List findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date); } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c889caa..334fbf5 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -3,6 +3,7 @@ package ru.ulstu.user.service; import com.google.common.collect.ImmutableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.Page; import org.springframework.data.domain.Sort; import org.springframework.mail.MailException; @@ -13,6 +14,7 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; +import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.core.error.EntityIdIsNullException; import ru.ulstu.core.jpa.OffsetablePageRequest; @@ -30,6 +32,7 @@ import ru.ulstu.user.error.UserResetKeyError; import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserInfoNow; import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserResetPasswordDto; import ru.ulstu.user.model.UserRole; @@ -38,8 +41,13 @@ import ru.ulstu.user.model.UserRoleDto; import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.util.UserUtils; +import ru.ulstu.utils.timetable.TimetableService; +import ru.ulstu.utils.timetable.model.Lesson; import javax.mail.MessagingException; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -62,19 +70,27 @@ public class UserService implements UserDetailsService { private final UserMapper userMapper; private final MailService mailService; private final ApplicationProperties applicationProperties; + private final TimetableService timetableService; + private final ConferenceService conferenceService; + private final UserSessionService userSessionService; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserRoleRepository userRoleRepository, UserMapper userMapper, MailService mailService, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties, + @Lazy ConferenceService conferenceRepository, + @Lazy UserSessionService userSessionService) throws ParseException { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.userRoleRepository = userRoleRepository; this.userMapper = userMapper; this.mailService = mailService; this.applicationProperties = applicationProperties; + this.conferenceService = conferenceRepository; + this.timetableService = new TimetableService(); + this.userSessionService = userSessionService; } private User getUserByEmail(String email) { @@ -341,4 +357,23 @@ public class UserService implements UserDetailsService { throw new UserSendingMailException(email); } } + + public List getUsersInfo() { + List usersInfoNow = new ArrayList<>(); + for (User user : userRepository.findAll()) { + Lesson lesson = null; + try { + lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); + } catch (IOException e) { + e.printStackTrace(); + } + usersInfoNow.add(new UserInfoNow( + lesson, + conferenceService.getActiveConferenceByUser(user), + user, + userSessionService.isOnline(user)) + ); + } + return usersInfoNow; + } } diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java index ae289d0..17a7f5b 100644 --- a/src/main/java/ru/ulstu/user/service/UserSessionService.java +++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java @@ -14,6 +14,8 @@ import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.repository.UserSessionRepository; +import java.util.Date; + import static ru.ulstu.core.util.StreamApiUtils.convert; @Service @@ -58,4 +60,8 @@ public class UserSessionService { public User getUserBySessionId(String sessionId) { return userSessionRepository.findOneBySessionId(sessionId).getUser(); } + + public boolean isOnline(User user) { + return !userSessionRepository.findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(user, new Date()).isEmpty(); + } } diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java new file mode 100644 index 0000000..f17ea86 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -0,0 +1,97 @@ +package ru.ulstu.utils.timetable; + +import com.fasterxml.jackson.databind.ObjectMapper; +import ru.ulstu.utils.timetable.model.Lesson; +import ru.ulstu.utils.timetable.model.TimetableResponse; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class TimetableService { + private static final String TIMETABLE_URL = "http://timetable.athene.tech"; + private SimpleDateFormat lessonTimeFormat = new SimpleDateFormat("hh:mm"); + + private long[] lessonsStarts = new long[]{ + lessonTimeFormat.parse("8:00:00").getTime(), + lessonTimeFormat.parse("9:40:00").getTime(), + lessonTimeFormat.parse("11:30:00").getTime(), + lessonTimeFormat.parse("13:10:00").getTime(), + lessonTimeFormat.parse("14:50:00").getTime(), + lessonTimeFormat.parse("16:30:00").getTime(), + lessonTimeFormat.parse("18:10:00").getTime(), + }; + + public TimetableService() throws ParseException { } + + private int getCurrentDay() { + Calendar calendar = Calendar.getInstance(); + int day = calendar.get(Calendar.DAY_OF_WEEK); + return (day + 5) % 7; + } + + private int getCurrentLessonNumber() { + long lessonDuration = 90 * 60000; + Date now = new Date(); + long timeNow = now.getTime() % (24 * 60 * 60 * 1000L); + for (int i = 0; i < lessonsStarts.length; i++) { + if (timeNow > lessonsStarts[i] && timeNow < lessonsStarts[i] + lessonDuration) { + return i; + } + } + return -1; + } + + private int getCurrentWeek() { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + return (cal.get(Calendar.WEEK_OF_YEAR) + 1) % 2; + } + + private TimetableResponse getTimetableForUser(String userFIO) throws IOException { + URL url = new URL(TIMETABLE_URL + "/api/1.0/timetable?filter=" + URLEncoder.encode(userFIO, "UTF-8")); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + + BufferedReader in = new BufferedReader( + new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuilder content = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + } + in.close(); + + return new ObjectMapper().readValue(content.toString(), TimetableResponse.class); + } + + public Lesson getCurrentLesson(String userFio) throws IOException { + TimetableResponse response = getTimetableForUser(userFio); + int lessonNumber = getCurrentLessonNumber(); + if (lessonNumber < 0) { + return null; + } + + List lessons = response + .getResponse() + .getWeeks() + .get(getCurrentWeek()) + .getDays() + .get(getCurrentDay()) + .getLessons() + .get(lessonNumber); + + if (lessons.size() == 0) { + return null; + } + return new ObjectMapper().convertValue(lessons.get(0), Lesson.class); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/utils/timetable/model/Day.java new file mode 100644 index 0000000..f548462 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Day.java @@ -0,0 +1,27 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + + +public class Day { + + private Integer day; + private List> lessons = null; + + public Integer getDay() { + return day; + } + + public void setDay(Integer day) { + this.day = day; + } + + public List> getLessons() { + return lessons; + } + + public void setLessons(List> lessons) { + this.lessons = lessons; + } +} + diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java new file mode 100644 index 0000000..e651e1a --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java @@ -0,0 +1,27 @@ +package ru.ulstu.utils.timetable.model; + +public class Lesson { + private String group; + private String nameOfLesson; + private String teacher; + private String room; + + public Lesson() { + } + + public String getGroup() { + return group; + } + + public String getNameOfLesson() { + return nameOfLesson; + } + + public String getTeacher() { + return teacher; + } + + public String getRoom() { + return room; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/utils/timetable/model/Response.java new file mode 100644 index 0000000..b5b9e97 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Response.java @@ -0,0 +1,16 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + +public class Response { + + private List weeks = null; + + public List getWeeks() { + return weeks; + } + + public void setWeeks(List weeks) { + this.weeks = weeks; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java new file mode 100644 index 0000000..118c979 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java @@ -0,0 +1,22 @@ +package ru.ulstu.utils.timetable.model; + +public class TimetableResponse { + private Response response; + private String error; + + public Response getResponse() { + return response; + } + + public void setResponse(Response response) { + this.response = response; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/utils/timetable/model/Week.java new file mode 100644 index 0000000..19f3c50 --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/model/Week.java @@ -0,0 +1,16 @@ +package ru.ulstu.utils.timetable.model; + +import java.util.List; + +public class Week { + + private List days = null; + + public List getDays() { + return days; + } + + public void setDays(List days) { + this.days = days; + } +} diff --git a/src/main/resources/templates/users/dashboard.html b/src/main/resources/templates/users/dashboard.html new file mode 100644 index 0000000..8236734 --- /dev/null +++ b/src/main/resources/templates/users/dashboard.html @@ -0,0 +1,24 @@ + + + + + + +
+
+
+
+

Пользователи

+
+
+ +
+ +
+
+
+
+ + \ No newline at end of file diff --git a/src/main/resources/templates/users/fragments/userDashboardFragment.html b/src/main/resources/templates/users/fragments/userDashboardFragment.html new file mode 100644 index 0000000..267bbf8 --- /dev/null +++ b/src/main/resources/templates/users/fragments/userDashboardFragment.html @@ -0,0 +1,18 @@ + + + + + + +
+
+
+

+

+

+

Онлайн

+
+
+
+ + \ No newline at end of file From bab621677eb65e10da2a75ba66e8c016da6389c9 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:10:51 +0400 Subject: [PATCH 11/37] #120 add methods for checking unique title and date of grant --- .../ru/ulstu/deadline/repository/DeadlineRepository.java | 7 +++++++ .../java/ru/ulstu/deadline/service/DeadlineService.java | 5 +++++ .../java/ru/ulstu/grant/repository/GrantRepository.java | 2 ++ src/main/java/ru/ulstu/name/BaseService.java | 7 +++++++ 4 files changed, 21 insertions(+) diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index f26c572..5b434b9 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import ru.ulstu.deadline.model.Deadline; +import java.util.Date; + public interface DeadlineRepository extends JpaRepository { + @Query( + value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", + nativeQuery = true) + Date findByGrantIdAndDate(Integer grant_id, Date date); } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java index 0ef8a4f..e82211d 100644 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java @@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.repository.DeadlineRepository; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -46,4 +47,8 @@ public class DeadlineService { public void remove(Integer deadlineId) { deadlineRepository.delete(deadlineId); } + + public Date findByGrantIdAndDate(Integer id, Date date) { + return deadlineRepository.findByGrantIdAndDate(id, date); + } } diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 26face4..ae9fcc8 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -12,6 +12,8 @@ public interface GrantRepository extends JpaRepository, BaseRepo List findByStatus(Grant.GrantStatus status); + Grant findByTitle(String title); + @Override @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); diff --git a/src/main/java/ru/ulstu/name/BaseService.java b/src/main/java/ru/ulstu/name/BaseService.java index 6619385..fd63cbf 100644 --- a/src/main/java/ru/ulstu/name/BaseService.java +++ b/src/main/java/ru/ulstu/name/BaseService.java @@ -13,4 +13,11 @@ public abstract class BaseService { errors.rejectValue(checkField, "errorCode", errorMessage); } } + + public String checkUniqueName(NameContainer nameContainer, Integer id) { + if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { + return baseRepository.findByNameAndNotId(nameContainer.getName(), id); + } + return null; + } } From c21739bfc627b1aad3de8edbec7e4ad7d5d8a0dc Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:12:45 +0400 Subject: [PATCH 12/37] #120 parse kias page --- src/test/java/IndexKiasTest.java | 67 +++++++++++++++++++++++++++++++ src/test/java/grant/KiasPage.java | 26 +++++++++++- 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/test/java/IndexKiasTest.java diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java new file mode 100644 index 0000000..73dc646 --- /dev/null +++ b/src/test/java/IndexKiasTest.java @@ -0,0 +1,67 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import grant.KiasPage; +import org.junit.runner.RunWith; +import org.openqa.selenium.WebElement; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.repository.UserRepository; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class IndexKiasTest extends TestTemplate { + private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; + private final static String CONTEST_STATUS_ID = "1"; + private final static String CONTEST_TYPE = "-1"; + private final static String CONTEST_YEAR = "2019"; + + private final Map> navigationHolder = ImmutableMap.of( + new KiasPage(), Arrays.asList("Поиск по конкурсам", + String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)) + ); + + @Autowired + UserRepository userRepository; + + public List getNewGrantsDto() throws ParseException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + getContext().goTo(page.getValue().get(1)); + KiasPage kiasPage = (KiasPage) getContext().initPage(page.getKey()); + List kiasGrants = new ArrayList<>(); + List newGrants = new ArrayList<>(); + do { + kiasGrants.addAll(kiasPage.getPageOfGrants()); + for (WebElement grant : kiasGrants) { + GrantDto grantDto = new GrantDto(); + grantDto.setTitle(kiasPage.getGrantTitle(grant)); + String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + Date date = formatter.parse(deadlineDate); + Deadline deadline = new Deadline(date, "Окончание приёма заявок"); + grantDto.setDeadlines(Arrays.asList(deadline)); + grantDto.setLeaderId(userRepository.findOneByLoginIgnoreCase("admin").getId()); + grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); + newGrants.add(grantDto); + } + kiasGrants.clear(); + } + while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами + + return newGrants; + } +} diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java index 49b40d9..7723b01 100644 --- a/src/test/java/grant/KiasPage.java +++ b/src/test/java/grant/KiasPage.java @@ -4,7 +4,9 @@ import core.PageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; +import java.util.ArrayList; import java.util.List; +import java.util.NoSuchElementException; public class KiasPage extends PageObject { @Override @@ -13,9 +15,31 @@ public class KiasPage extends PageObject { } public List getGrants() { + List grants = new ArrayList<>(); + do { + grants.addAll(getPageOfGrants()); + } + while (checkPagination()); + + return grants; + } + + public List getPageOfGrants() { WebElement listContest = driver.findElement(By.tagName("tBody")); - return listContest.findElements(By.cssSelector("tr.tr")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + public boolean checkPagination() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } catch (NoSuchElementException e) { + return false; + } + return false; } public String getGrantTitle(WebElement grant) { From 5f214620bff80e208fc4b382be55d5070057cdd6 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:16:20 +0400 Subject: [PATCH 13/37] #120 use loading from kias --- .../ulstu/grant/service/GrantScheduler.java | 22 +++++++++++++++ .../ru/ulstu/grant/service/GrantService.java | 27 +++++++++++++++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index 1c38c4a..efe1e41 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -27,4 +27,26 @@ public class GrantScheduler { grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); } + + @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara") + public void loadGrantsFromKias() { + log.debug("GrantScheduler.loadGrantsFromKias started"); + // + // Метод для сохранения загруженных грантов + // + +// List grants = IndexKiasTest.getNewGrantsDto(); +// grants.forEach(grantDto -> { +// try { +// if (grantService.saveFromKias(grantDto)) { +// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); +// } else { +// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); +// } +// } catch (IOException e) { +// e.printStackTrace(); +// } +// }); + log.debug("GrantScheduler.loadGrantsFromKias finished"); + } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 4972b6c..38c16c3 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -189,16 +189,31 @@ public class GrantService extends BaseService { if (errors.hasErrors()) { return false; } - if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } - return true; } + public boolean saveFromKias(GrantDto grantDto) throws IOException { + grantDto.setName(grantDto.getTitle()); + String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени + if (title != null) { + Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд + if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают + return false; + } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать + create(grantDto); + return true; + } + } else { //иначе такого гранта ещё нет, поэтому надо создать + create(grantDto); + return true; + } + } + private void checkEmptyLeader(GrantDto grantDto, Errors errors) { if (grantDto.getLeaderId().equals(-1)) { errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); @@ -211,6 +226,14 @@ public class GrantService extends BaseService { } } + private boolean checkSameDeadline(GrantDto grantDto, Integer id) { + Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас + if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой + return true; + } + return false; + } + public List getGrantAuthors(GrantDto grantDto) { List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree()); if (grantDto.isWasLeader()) { From 457f1da98525439184bddad051aafbce2a710325 Mon Sep 17 00:00:00 2001 From: T-Midnight Date: Wed, 22 May 2019 15:45:23 +0400 Subject: [PATCH 14/37] #120 fix checkRun and checkStyle --- .../java/ru/ulstu/deadline/repository/DeadlineRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index 5b434b9..3f237e4 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -12,5 +12,5 @@ public interface DeadlineRepository extends JpaRepository { @Query( value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", nativeQuery = true) - Date findByGrantIdAndDate(Integer grant_id, Date date); + Date findByGrantIdAndDate(Integer grantId, Date date); } From c303d65c8d8c02fc0d86c4ec332067e334cfe7ec Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Thu, 23 May 2019 16:02:44 +0400 Subject: [PATCH 15/37] #120 move to services --- build.gradle | 2 +- .../java/ru/ulstu/grant/page/KiasPage.java | 52 ++ .../ulstu/grant/service/GrantScheduler.java | 24 +- .../ru/ulstu/grant/service/GrantService.java | 20 +- .../ru/ulstu/grant/service/KiasService.java | 83 +++ .../ru/ulstu/user/service/UserService.java | 693 +++++++++--------- src/main/resources/drivers/chromedriver | Bin src/main/resources/drivers/geckodriver | Bin 8 files changed, 512 insertions(+), 362 deletions(-) create mode 100644 src/main/java/ru/ulstu/grant/page/KiasPage.java create mode 100644 src/main/java/ru/ulstu/grant/service/KiasService.java mode change 100644 => 100755 src/main/resources/drivers/chromedriver mode change 100644 => 100755 src/main/resources/drivers/geckodriver diff --git a/build.gradle b/build.gradle index 38de2c7..71c9977 100644 --- a/build.gradle +++ b/build.gradle @@ -126,6 +126,6 @@ dependencies { compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test' - testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' + compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' } \ No newline at end of file diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java new file mode 100644 index 0000000..4353684 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -0,0 +1,52 @@ +package ru.ulstu.grant.page; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.util.ArrayList; +import java.util.List; +import java.util.NoSuchElementException; + +public class KiasPage { + private WebDriver driver; + public KiasPage(WebDriver webDriver) { + this.driver = webDriver; + } + + public List getGrants() { + List grants = new ArrayList<>(); + do { + grants.addAll(getPageOfGrants()); + } + while (checkPagination()); + + return grants; + } + + public List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + public boolean checkPagination() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } catch (NoSuchElementException e) { + return false; + } + return false; + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public String getFirstDeadline(WebElement grant) { + return grant.findElement(By.xpath("./td[5]")).getText(); + } +} diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index efe1e41..fb236af 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.text.ParseException; + @Service public class GrantScheduler { private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; @@ -31,22 +34,11 @@ public class GrantScheduler { @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara") public void loadGrantsFromKias() { log.debug("GrantScheduler.loadGrantsFromKias started"); - // - // Метод для сохранения загруженных грантов - // - -// List grants = IndexKiasTest.getNewGrantsDto(); -// grants.forEach(grantDto -> { -// try { -// if (grantService.saveFromKias(grantDto)) { -// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); -// } else { -// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// } -// }); + try { + grantService.createFromKias(); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } log.debug("GrantScheduler.loadGrantsFromKias finished"); } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 38c16c3..8d65da7 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -1,6 +1,8 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; @@ -23,6 +25,7 @@ import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; +import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.Date; @@ -39,6 +42,7 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service public class GrantService extends BaseService { private final static int MAX_DISPLAY_SIZE = 50; + private final Logger log = LoggerFactory.getLogger(GrantService.class); private final GrantRepository grantRepository; private final ProjectService projectService; @@ -48,6 +52,7 @@ public class GrantService extends BaseService { private final PaperService paperService; private final EventService eventService; private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; public GrantService(GrantRepository grantRepository, FileService fileService, @@ -56,8 +61,10 @@ public class GrantService extends BaseService { UserService userService, PaperService paperService, EventService eventService, - GrantNotificationService grantNotificationService) { + GrantNotificationService grantNotificationService, + KiasService kiasService) { this.grantRepository = grantRepository; + this.kiasService = kiasService; this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; @@ -317,4 +324,15 @@ public class GrantService extends BaseService { .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .collect(Collectors.toList())); } + + @Transactional + public void createFromKias() throws IOException, ParseException { + for (GrantDto grantDto : kiasService.getNewGrantsDto()) { + if (saveFromKias(grantDto)) { + log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); + } else { + log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); + } + } + } } diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java new file mode 100644 index 0000000..6ff0bd9 --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -0,0 +1,83 @@ +package ru.ulstu.grant.service; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.springframework.stereotype.Service; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.grant.model.Grant; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.page.KiasPage; +import ru.ulstu.user.service.UserService; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +@Service +public class KiasService { + private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; + private final static String CONTEST_STATUS_ID = "1"; + private final static String CONTEST_TYPE = "-1"; + private final static int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR); + + private final static String DRIVER_LOCATION = "drivers/%s"; + private final static String WINDOWS_DRIVER = "chromedriver.exe"; + private final static String LINUX_DRIVER = "chromedriver"; + private final static String DRIVER_TYPE = "webdriver.chrome.driver"; + + private final UserService userService; + private WebDriver webDriver; + + public KiasService(UserService userService) { + System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); + this.userService = userService; + final ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.addArguments("--headless"); + webDriver = new ChromeDriver(chromeOptions); + } + + public List getNewGrantsDto() throws ParseException { + webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)); + KiasPage kiasPage = new KiasPage(webDriver); + List kiasGrants = new ArrayList<>(); + List newGrants = new ArrayList<>(); + do { + kiasGrants.addAll(kiasPage.getPageOfGrants()); + for (WebElement grant : kiasGrants) { + GrantDto grantDto = new GrantDto(); + grantDto.setTitle(kiasPage.getGrantTitle(grant)); + String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + Date date = formatter.parse(deadlineDate); + Deadline deadline = new Deadline(date, "Окончание приёма заявок"); + grantDto.setDeadlines(Arrays.asList(deadline)); + grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId()); + grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); + newGrants.add(grantDto); + } + kiasGrants.clear(); + } + while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами + + return newGrants; + } + + private String getDriverExecutablePath() { + return KiasService.class.getClassLoader().getResource( + String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile(); + } + + private String getDriverExecutable(boolean isWindows) { + return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER; + } + + private boolean isWindows() { + return System.getProperty("os.name").toLowerCase().contains("windows"); + } +} diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c889caa..30eeb19 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -1,344 +1,349 @@ -package ru.ulstu.user.service; - -import com.google.common.collect.ImmutableMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Sort; -import org.springframework.mail.MailException; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; -import ru.ulstu.configuration.ApplicationProperties; -import ru.ulstu.core.error.EntityIdIsNullException; -import ru.ulstu.core.jpa.OffsetablePageRequest; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.response.PageableItems; -import ru.ulstu.user.error.UserActivationError; -import ru.ulstu.user.error.UserEmailExistsException; -import ru.ulstu.user.error.UserIdExistsException; -import ru.ulstu.user.error.UserIsUndeadException; -import ru.ulstu.user.error.UserLoginExistsException; -import ru.ulstu.user.error.UserNotActivatedException; -import ru.ulstu.user.error.UserNotFoundException; -import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; -import ru.ulstu.user.error.UserResetKeyError; -import ru.ulstu.user.error.UserSendingMailException; -import ru.ulstu.user.model.User; -import ru.ulstu.user.model.UserDto; -import ru.ulstu.user.model.UserListDto; -import ru.ulstu.user.model.UserResetPasswordDto; -import ru.ulstu.user.model.UserRole; -import ru.ulstu.user.model.UserRoleConstants; -import ru.ulstu.user.model.UserRoleDto; -import ru.ulstu.user.repository.UserRepository; -import ru.ulstu.user.repository.UserRoleRepository; -import ru.ulstu.user.util.UserUtils; - -import javax.mail.MessagingException; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@Transactional -public class UserService implements UserDetailsService { - private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; - - private final Logger log = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; - private final UserRoleRepository userRoleRepository; - private final UserMapper userMapper; - private final MailService mailService; - private final ApplicationProperties applicationProperties; - - public UserService(UserRepository userRepository, - PasswordEncoder passwordEncoder, - UserRoleRepository userRoleRepository, - UserMapper userMapper, - MailService mailService, - ApplicationProperties applicationProperties) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - this.userRoleRepository = userRoleRepository; - this.userMapper = userMapper; - this.mailService = mailService; - this.applicationProperties = applicationProperties; - } - - private User getUserByEmail(String email) { - return userRepository.findOneByEmailIgnoreCase(email); - } - - private User getUserByActivationKey(String activationKey) { - return userRepository.findOneByActivationKey(activationKey); - } - - public User getUserByLogin(String login) { - return userRepository.findOneByLoginIgnoreCase(login); - } - - @Transactional(readOnly = true) - public UserDto getUserWithRolesById(Integer userId) { - final User userEntity = userRepository.findOneWithRolesById(userId); - if (userEntity == null) { - throw new UserNotFoundException(userId.toString()); - } - return userMapper.userEntityToUserDto(userEntity); - } - - @Transactional(readOnly = true) - public PageableItems getAllUsers(int offset, int count) { - final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); - return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); - } - - // TODO: read only active users - public List findAll() { - return userRepository.findAll(); - } - - @Transactional(readOnly = true) - public PageableItems getUserRoles() { - final List roles = userRoleRepository.findAll().stream() - .map(UserRoleDto::new) - .sorted(Comparator.comparing(UserRoleDto::getViewValue)) - .collect(Collectors.toList()); - return new PageableItems<>(roles.size(), roles); - } - - public UserDto createUser(UserDto userDto) { - if (userDto.getId() != null) { - throw new UserIdExistsException(); - } - if (getUserByLogin(userDto.getLogin()) != null) { - throw new UserLoginExistsException(userDto.getLogin()); - } - if (getUserByEmail(userDto.getEmail()) != null) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!userDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - User user = userMapper.userDtoToUserEntity(userDto); - user.setActivated(false); - user.setActivationKey(UserUtils.generateActivationKey()); - user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - user = userRepository.save(user); - mailService.sendActivationEmail(user); - log.debug("Created Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto activateUser(String activationKey) { - final User user = getUserByActivationKey(activationKey); - if (user == null) { - throw new UserActivationError(activationKey); - } - user.setActivated(true); - user.setActivationKey(null); - user.setActivationDate(null); - log.debug("Activated user: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); - } - - public UserDto updateUser(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!Objects.equals( - Optional.ofNullable(getUserByLogin(userDto.getLogin())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserLoginExistsException(userDto.getLogin()); - } - User user = userRepository.findOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - userDto.setLogin(applicationProperties.getUndeadUserLogin()); - userDto.setActivated(true); - userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); - } - user.setLogin(userDto.getLogin()); - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); - if (userDto.isActivated() != user.getActivated()) { - if (userDto.isActivated()) { - user.setActivationKey(null); - user.setActivationDate(null); - } else { - user.setActivationKey(UserUtils.generateActivationKey()); - user.setActivationDate(new Date()); - } - } - user.setActivated(userDto.isActivated()); - final Set roles = userMapper.rolesFromDto(userDto.getRoles()); - user.setRoles(roles.isEmpty() - ? Collections.singleton(new UserRole(UserRoleConstants.USER)) - : roles); - if (!StringUtils.isEmpty(userDto.getOldPassword())) { - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - log.debug("Changed password for User: {}", user.getLogin()); - } - user = userRepository.save(user); - log.debug("Changed Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto updateUserInformation(User user, UserDto updateUser) { - user.setFirstName(updateUser.getFirstName()); - user.setLastName(updateUser.getLastName()); - user.setEmail(updateUser.getEmail()); - user.setLogin(updateUser.getLogin()); - user = userRepository.save(user); - log.debug("Updated Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public void changeUserPassword(User user, Map payload) { - if (!payload.get("password").equals(payload.get("confirmPassword"))) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); - } - user.setPassword(passwordEncoder.encode(payload.get("password"))); - log.debug("Changed password for User: {}", user.getLogin()); - userRepository.save(user); - - mailService.sendChangePasswordMail(user); - } - - public boolean requestUserPasswordReset(String email) { - User user = userRepository.findOneByEmailIgnoreCase(email); - if (user == null) { - throw new UserNotFoundException(email); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - user.setResetKey(UserUtils.generateResetKey()); - user.setResetDate(new Date()); - user = userRepository.save(user); - mailService.sendPasswordResetMail(user); - log.debug("Created Reset Password Request for User: {}", user.getLogin()); - return true; - } - - public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { - if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(""); - } - User user = userRepository.findOneByResetKey(key); - if (user == null) { - throw new UserResetKeyError(key); - } - user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); - user.setResetKey(null); - user.setResetDate(null); - user = userRepository.save(user); - log.debug("Reset Password for User: {}", user.getLogin()); - return true; - } - - public UserDto deleteUser(Integer userId) { - final User user = userRepository.findOne(userId); - if (user == null) { - throw new UserNotFoundException(userId.toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - throw new UserIsUndeadException(user.getLogin()); - } - userRepository.delete(user); - log.debug("Deleted User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - @Override - public UserDetails loadUserByUsername(String username) { - final User user = userRepository.findOneByLoginIgnoreCase(username); - if (user == null) { - throw new UserNotFoundException(username); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() - .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList())); - } - - public List findByIds(List ids) { - return userRepository.findAll(ids); - } - - public User findById(Integer id) { - return userRepository.findOne(id); - } - - public User getCurrentUser() { - String login = UserUtils.getCurrentUserLogin(); - User user = userRepository.findOneByLoginIgnoreCase(login); - if (user == null) { - throw new UserNotFoundException(login); - } - return user; - } - - public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { - return userRepository.filterByAgeAndDegree(hasDegree, hasAge); - } - - public void inviteUser(String email) throws UserSendingMailException { - if (userRepository.findOneByEmailIgnoreCase(email) != null) { - throw new UserEmailExistsException(email); - } - - String password = UserUtils.generatePassword(); - - User user = new User(); - user.setPassword(passwordEncoder.encode(password)); - user.setLogin(email); - user.setEmail(email); - user.setFirstName("user"); - user.setLastName("user"); - user.setActivated(true); - userRepository.save(user); - - Map variables = ImmutableMap.of("password", password, "email", email); - try { - mailService.sendInviteMail(variables, email); - } catch (MessagingException | MailException e) { - throw new UserSendingMailException(email); - } - } -} +package ru.ulstu.user.service; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.mail.MailException; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import ru.ulstu.configuration.ApplicationProperties; +import ru.ulstu.core.error.EntityIdIsNullException; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.error.UserActivationError; +import ru.ulstu.user.error.UserEmailExistsException; +import ru.ulstu.user.error.UserIdExistsException; +import ru.ulstu.user.error.UserIsUndeadException; +import ru.ulstu.user.error.UserLoginExistsException; +import ru.ulstu.user.error.UserNotActivatedException; +import ru.ulstu.user.error.UserNotFoundException; +import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; +import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.model.UserResetPasswordDto; +import ru.ulstu.user.model.UserRole; +import ru.ulstu.user.model.UserRoleConstants; +import ru.ulstu.user.model.UserRoleDto; +import ru.ulstu.user.repository.UserRepository; +import ru.ulstu.user.repository.UserRoleRepository; +import ru.ulstu.user.util.UserUtils; + +import javax.mail.MessagingException; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@Transactional +public class UserService implements UserDetailsService { + private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; + + private final Logger log = LoggerFactory.getLogger(UserService.class); + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final UserRoleRepository userRoleRepository; + private final UserMapper userMapper; + private final MailService mailService; + private final ApplicationProperties applicationProperties; + + public UserService(UserRepository userRepository, + PasswordEncoder passwordEncoder, + UserRoleRepository userRoleRepository, + UserMapper userMapper, + MailService mailService, + ApplicationProperties applicationProperties) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.userRoleRepository = userRoleRepository; + this.userMapper = userMapper; + this.mailService = mailService; + this.applicationProperties = applicationProperties; + } + + private User getUserByEmail(String email) { + return userRepository.findOneByEmailIgnoreCase(email); + } + + private User getUserByActivationKey(String activationKey) { + return userRepository.findOneByActivationKey(activationKey); + } + + public User getUserByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Transactional(readOnly = true) + public UserDto getUserWithRolesById(Integer userId) { + final User userEntity = userRepository.findOneWithRolesById(userId); + if (userEntity == null) { + throw new UserNotFoundException(userId.toString()); + } + return userMapper.userEntityToUserDto(userEntity); + } + + @Transactional(readOnly = true) + public PageableItems getAllUsers(int offset, int count) { + final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); + return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); + } + + // TODO: read only active users + public List findAll() { + return userRepository.findAll(); + } + + @Transactional(readOnly = true) + public PageableItems getUserRoles() { + final List roles = userRoleRepository.findAll().stream() + .map(UserRoleDto::new) + .sorted(Comparator.comparing(UserRoleDto::getViewValue)) + .collect(Collectors.toList()); + return new PageableItems<>(roles.size(), roles); + } + + public UserDto createUser(UserDto userDto) { + if (userDto.getId() != null) { + throw new UserIdExistsException(); + } + if (getUserByLogin(userDto.getLogin()) != null) { + throw new UserLoginExistsException(userDto.getLogin()); + } + if (getUserByEmail(userDto.getEmail()) != null) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!userDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userMapper.userDtoToUserEntity(userDto); + user.setActivated(false); + user.setActivationKey(UserUtils.generateActivationKey()); + user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + user = userRepository.save(user); + mailService.sendActivationEmail(user); + log.debug("Created Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto activateUser(String activationKey) { + final User user = getUserByActivationKey(activationKey); + if (user == null) { + throw new UserActivationError(activationKey); + } + user.setActivated(true); + user.setActivationKey(null); + user.setActivationDate(null); + log.debug("Activated user: {}", user.getLogin()); + return userMapper.userEntityToUserDto(userRepository.save(user)); + } + + public UserDto updateUser(UserDto userDto) { + if (userDto.getId() == null) { + throw new EntityIdIsNullException(); + } + if (!Objects.equals( + Optional.ofNullable(getUserByEmail(userDto.getEmail())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!Objects.equals( + Optional.ofNullable(getUserByLogin(userDto.getLogin())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserLoginExistsException(userDto.getLogin()); + } + User user = userRepository.findOne(userDto.getId()); + if (user == null) { + throw new UserNotFoundException(userDto.getId().toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + userDto.setLogin(applicationProperties.getUndeadUserLogin()); + userDto.setActivated(true); + userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); + } + user.setLogin(userDto.getLogin()); + user.setFirstName(userDto.getFirstName()); + user.setLastName(userDto.getLastName()); + user.setEmail(userDto.getEmail()); + if (userDto.isActivated() != user.getActivated()) { + if (userDto.isActivated()) { + user.setActivationKey(null); + user.setActivationDate(null); + } else { + user.setActivationKey(UserUtils.generateActivationKey()); + user.setActivationDate(new Date()); + } + } + user.setActivated(userDto.isActivated()); + final Set roles = userMapper.rolesFromDto(userDto.getRoles()); + user.setRoles(roles.isEmpty() + ? Collections.singleton(new UserRole(UserRoleConstants.USER)) + : roles); + if (!StringUtils.isEmpty(userDto.getOldPassword())) { + if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + log.debug("Changed password for User: {}", user.getLogin()); + } + user = userRepository.save(user); + log.debug("Changed Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto updateUserInformation(User user, UserDto updateUser) { + user.setFirstName(updateUser.getFirstName()); + user.setLastName(updateUser.getLastName()); + user.setEmail(updateUser.getEmail()); + user.setLogin(updateUser.getLogin()); + user = userRepository.save(user); + log.debug("Updated Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public void changeUserPassword(User user, Map payload) { + if (!payload.get("password").equals(payload.get("confirmPassword"))) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); + } + user.setPassword(passwordEncoder.encode(payload.get("password"))); + log.debug("Changed password for User: {}", user.getLogin()); + userRepository.save(user); + + mailService.sendChangePasswordMail(user); + } + + public boolean requestUserPasswordReset(String email) { + User user = userRepository.findOneByEmailIgnoreCase(email); + if (user == null) { + throw new UserNotFoundException(email); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + user.setResetKey(UserUtils.generateResetKey()); + user.setResetDate(new Date()); + user = userRepository.save(user); + mailService.sendPasswordResetMail(user); + log.debug("Created Reset Password Request for User: {}", user.getLogin()); + return true; + } + + public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { + if (!userResetPasswordDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userRepository.findOneByResetKey(key); + if (user == null) { + throw new UserResetKeyError(key); + } + user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); + user.setResetKey(null); + user.setResetDate(null); + user = userRepository.save(user); + log.debug("Reset Password for User: {}", user.getLogin()); + return true; + } + + public UserDto deleteUser(Integer userId) { + final User user = userRepository.findOne(userId); + if (user == null) { + throw new UserNotFoundException(userId.toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + throw new UserIsUndeadException(user.getLogin()); + } + userRepository.delete(user); + log.debug("Deleted User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + @Override + public UserDetails loadUserByUsername(String username) { + final User user = userRepository.findOneByLoginIgnoreCase(username); + if (user == null) { + throw new UserNotFoundException(username); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + return new org.springframework.security.core.userdetails.User(user.getLogin(), + user.getPassword(), + Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() + .map(role -> new SimpleGrantedAuthority(role.getName())) + .collect(Collectors.toList())); + } + + public List findByIds(List ids) { + return userRepository.findAll(ids); + } + + public User findById(Integer id) { + return userRepository.findOne(id); + } + + public User getCurrentUser() { + String login = UserUtils.getCurrentUserLogin(); + User user = userRepository.findOneByLoginIgnoreCase(login); + if (user == null) { + throw new UserNotFoundException(login); + } + return user; + } + + public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { + return userRepository.filterByAgeAndDegree(hasDegree, hasAge); + } + + public void inviteUser(String email) throws UserSendingMailException { + if (userRepository.findOneByEmailIgnoreCase(email) != null) { + throw new UserEmailExistsException(email); + } + + String password = UserUtils.generatePassword(); + + User user = new User(); + user.setPassword(passwordEncoder.encode(password)); + user.setLogin(email); + user.setEmail(email); + user.setFirstName("user"); + user.setLastName("user"); + user.setActivated(true); + userRepository.save(user); + + Map variables = ImmutableMap.of("password", password, "email", email); + try { + mailService.sendInviteMail(variables, email); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + } + + public User findOneByLoginIgnoreCase(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } +} diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver old mode 100644 new mode 100755 diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver old mode 100644 new mode 100755 From 181086c9db9e7eb5683c520d4a89110d6561b38f Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Thu, 23 May 2019 16:36:48 +0400 Subject: [PATCH 16/37] #120 disable start browser on run application --- src/main/java/ru/ulstu/grant/service/KiasService.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java index 6ff0bd9..449b948 100644 --- a/src/main/java/ru/ulstu/grant/service/KiasService.java +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -32,17 +32,16 @@ public class KiasService { private final static String DRIVER_TYPE = "webdriver.chrome.driver"; private final UserService userService; - private WebDriver webDriver; public KiasService(UserService userService) { - System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); this.userService = userService; - final ChromeOptions chromeOptions = new ChromeOptions(); - chromeOptions.addArguments("--headless"); - webDriver = new ChromeDriver(chromeOptions); } public List getNewGrantsDto() throws ParseException { + System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); + final ChromeOptions chromeOptions = new ChromeOptions(); + chromeOptions.addArguments("--headless"); + WebDriver webDriver = new ChromeDriver(chromeOptions); webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)); KiasPage kiasPage = new KiasPage(webDriver); List kiasGrants = new ArrayList<>(); @@ -64,7 +63,7 @@ public class KiasService { kiasGrants.clear(); } while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами - + webDriver.quit(); return newGrants; } From 308da4113d395005204741494b71d85bcf252271 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Fri, 24 May 2019 13:26:02 +0400 Subject: [PATCH 17/37] fix week number calculation --- .../ru/ulstu/utils/timetable/TimetableService.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java index aa49fed..d65e276 100644 --- a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -3,6 +3,7 @@ package ru.ulstu.utils.timetable; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import ru.ulstu.core.util.DateUtils; import ru.ulstu.utils.timetable.errors.TimetableClientException; import ru.ulstu.utils.timetable.model.Lesson; import ru.ulstu.utils.timetable.model.TimetableResponse; @@ -50,9 +51,15 @@ public class TimetableService { } private int getCurrentWeek() { - Calendar cal = Calendar.getInstance(); - cal.setTime(new Date()); - return (cal.get(Calendar.WEEK_OF_YEAR) + 1) % 2; + Date currentDate = Calendar.getInstance().getTime(); + currentDate = DateUtils.clearTime(currentDate); + + Calendar firstJan = Calendar.getInstance(); + firstJan.set(Calendar.MONTH, 0); + firstJan.set(Calendar.DAY_OF_MONTH, 1); + + return (int) Math.round(Math.ceil((((currentDate.getTime() - firstJan.getTime().getTime()) / 86400000) + + DateUtils.addDays(firstJan.getTime(), 1).getTime() / 7) % 2)); } private TimetableResponse getTimetableForUser(String userFIO) throws RestClientException { From 193b2b3a3255f45274f299364e8c398f9f1ce3ad Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Sat, 25 May 2019 14:03:43 +0400 Subject: [PATCH 18/37] #91 using RestTemplate & show error on timetable loading exception --- .../user/controller/UserMvcController.java | 2 +- .../ru/ulstu/user/service/UserService.java | 12 +++-- .../utils/timetable/TimetableService.java | 46 ++++++++----------- .../errors/TimetableClientException.java | 7 +++ .../ru/ulstu/utils/timetable/model/Day.java | 9 ++-- .../ulstu/utils/timetable/model/Lesson.java | 5 +- .../ulstu/utils/timetable/model/Response.java | 3 +- .../timetable/model/TimetableResponse.java | 2 +- .../ru/ulstu/utils/timetable/model/Week.java | 6 ++- src/main/resources/application.properties | 4 +- .../resources/templates/users/dashboard.html | 13 +++++- 11 files changed, 62 insertions(+), 47 deletions(-) create mode 100644 src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java index d283a21..044bde8 100644 --- a/src/main/java/ru/ulstu/user/controller/UserMvcController.java +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -51,6 +51,6 @@ public class UserMvcController extends OdinController { @GetMapping("/dashboard") public void getUsersDashboard(ModelMap modelMap) { - modelMap.addAttribute("users", userService.getUsersInfo()); + modelMap.addAllAttributes(userService.getUsersInfo()); } } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index 334fbf5..b022866 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -42,10 +42,10 @@ import ru.ulstu.user.repository.UserRepository; import ru.ulstu.user.repository.UserRoleRepository; import ru.ulstu.user.util.UserUtils; import ru.ulstu.utils.timetable.TimetableService; +import ru.ulstu.utils.timetable.errors.TimetableClientException; import ru.ulstu.utils.timetable.model.Lesson; import javax.mail.MessagingException; -import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; @@ -358,14 +358,16 @@ public class UserService implements UserDetailsService { } } - public List getUsersInfo() { + public Map getUsersInfo() { List usersInfoNow = new ArrayList<>(); + String err = ""; + for (User user : userRepository.findAll()) { Lesson lesson = null; try { lesson = timetableService.getCurrentLesson(user.getUserAbbreviate()); - } catch (IOException e) { - e.printStackTrace(); + } catch (TimetableClientException e) { + err = "Не удалось загрузить расписание"; } usersInfoNow.add(new UserInfoNow( lesson, @@ -374,6 +376,6 @@ public class UserService implements UserDetailsService { userSessionService.isOnline(user)) ); } - return usersInfoNow; + return ImmutableMap.of("users", usersInfoNow, "error", err); } } diff --git a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java index f17ea86..aa49fed 100644 --- a/src/main/java/ru/ulstu/utils/timetable/TimetableService.java +++ b/src/main/java/ru/ulstu/utils/timetable/TimetableService.java @@ -1,15 +1,12 @@ package ru.ulstu.utils.timetable; import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import ru.ulstu.utils.timetable.errors.TimetableClientException; import ru.ulstu.utils.timetable.model.Lesson; import ru.ulstu.utils.timetable.model.TimetableResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; @@ -17,10 +14,10 @@ import java.util.Date; import java.util.List; public class TimetableService { - private static final String TIMETABLE_URL = "http://timetable.athene.tech"; + private static final String TIMETABLE_URL = "http://timetable.athene.tech/api/1.0/timetable?filter=%s"; private SimpleDateFormat lessonTimeFormat = new SimpleDateFormat("hh:mm"); - private long[] lessonsStarts = new long[]{ + private long[] lessonsStarts = new long[] { lessonTimeFormat.parse("8:00:00").getTime(), lessonTimeFormat.parse("9:40:00").getTime(), lessonTimeFormat.parse("11:30:00").getTime(), @@ -30,7 +27,8 @@ public class TimetableService { lessonTimeFormat.parse("18:10:00").getTime(), }; - public TimetableService() throws ParseException { } + public TimetableService() throws ParseException { + } private int getCurrentDay() { Calendar calendar = Calendar.getInstance(); @@ -42,6 +40,7 @@ public class TimetableService { long lessonDuration = 90 * 60000; Date now = new Date(); long timeNow = now.getTime() % (24 * 60 * 60 * 1000L); + for (int i = 0; i < lessonsStarts.length; i++) { if (timeNow > lessonsStarts[i] && timeNow < lessonsStarts[i] + lessonDuration) { return i; @@ -56,31 +55,26 @@ public class TimetableService { return (cal.get(Calendar.WEEK_OF_YEAR) + 1) % 2; } - private TimetableResponse getTimetableForUser(String userFIO) throws IOException { - URL url = new URL(TIMETABLE_URL + "/api/1.0/timetable?filter=" + URLEncoder.encode(userFIO, "UTF-8")); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); + private TimetableResponse getTimetableForUser(String userFIO) throws RestClientException { + RestTemplate restTemplate = new RestTemplate(); + return restTemplate.getForObject(String.format(TIMETABLE_URL, userFIO), TimetableResponse.class); + } - BufferedReader in = new BufferedReader( - new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuilder content = new StringBuilder(); - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); + public Lesson getCurrentLesson(String userFio) { + TimetableResponse response; + try { + response = getTimetableForUser(userFio); + } catch (RestClientException e) { + e.printStackTrace(); + throw new TimetableClientException(userFio); } - in.close(); - - return new ObjectMapper().readValue(content.toString(), TimetableResponse.class); - } - public Lesson getCurrentLesson(String userFio) throws IOException { - TimetableResponse response = getTimetableForUser(userFio); int lessonNumber = getCurrentLessonNumber(); if (lessonNumber < 0) { return null; } - List lessons = response + List lessons = response .getResponse() .getWeeks() .get(getCurrentWeek()) diff --git a/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java new file mode 100644 index 0000000..4723bda --- /dev/null +++ b/src/main/java/ru/ulstu/utils/timetable/errors/TimetableClientException.java @@ -0,0 +1,7 @@ +package ru.ulstu.utils.timetable.errors; + +public class TimetableClientException extends RuntimeException { + public TimetableClientException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Day.java b/src/main/java/ru/ulstu/utils/timetable/model/Day.java index f548462..e4e37f9 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Day.java +++ b/src/main/java/ru/ulstu/utils/timetable/model/Day.java @@ -1,12 +1,13 @@ package ru.ulstu.utils.timetable.model; +import java.util.ArrayList; import java.util.List; -public class Day { +public class Day { private Integer day; - private List> lessons = null; + private List> lessons = new ArrayList<>(); public Integer getDay() { return day; @@ -16,11 +17,11 @@ public class Day { this.day = day; } - public List> getLessons() { + public List> getLessons() { return lessons; } - public void setLessons(List> lessons) { + public void setLessons(List> lessons) { this.lessons = lessons; } } diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java index e651e1a..b1b1707 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java +++ b/src/main/java/ru/ulstu/utils/timetable/model/Lesson.java @@ -1,14 +1,11 @@ package ru.ulstu.utils.timetable.model; -public class Lesson { +public class Lesson { private String group; private String nameOfLesson; private String teacher; private String room; - public Lesson() { - } - public String getGroup() { return group; } diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Response.java b/src/main/java/ru/ulstu/utils/timetable/model/Response.java index b5b9e97..dfd3a84 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Response.java +++ b/src/main/java/ru/ulstu/utils/timetable/model/Response.java @@ -1,10 +1,11 @@ package ru.ulstu.utils.timetable.model; +import java.util.ArrayList; import java.util.List; public class Response { - private List weeks = null; + private List weeks = new ArrayList<>(); public List getWeeks() { return weeks; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java index 118c979..925d9a8 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java +++ b/src/main/java/ru/ulstu/utils/timetable/model/TimetableResponse.java @@ -1,6 +1,6 @@ package ru.ulstu.utils.timetable.model; -public class TimetableResponse { +public class TimetableResponse { private Response response; private String error; diff --git a/src/main/java/ru/ulstu/utils/timetable/model/Week.java b/src/main/java/ru/ulstu/utils/timetable/model/Week.java index 19f3c50..8ea76ea 100644 --- a/src/main/java/ru/ulstu/utils/timetable/model/Week.java +++ b/src/main/java/ru/ulstu/utils/timetable/model/Week.java @@ -1,10 +1,12 @@ package ru.ulstu.utils.timetable.model; +import java.io.Serializable; +import java.util.ArrayList; import java.util.List; -public class Week { +public class Week implements Serializable { - private List days = null; + private List days = new ArrayList<>(); public List getDays() { return days; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 038ddcf..41c8ece 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -24,7 +24,7 @@ spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFact # JPA Settings spring.datasource.url=jdbc:postgresql://localhost:5432/ng-tracker spring.datasource.username=postgres -spring.datasource.password=postgres +spring.datasource.password=password spring.datasource.driverclassName=org.postgresql.Driver spring.jpa.hibernate.ddl-auto=validate # Liquibase Settings @@ -34,6 +34,6 @@ liquibase.change-log=classpath:db/changelog-master.xml # Application Settings ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin -ng-tracker.dev-mode=true +ng-tracker.dev-mode=false ng-tracker.use-https=false ng-tracker.check-run=false \ No newline at end of file diff --git a/src/main/resources/templates/users/dashboard.html b/src/main/resources/templates/users/dashboard.html index 8236734..e5b7563 100644 --- a/src/main/resources/templates/users/dashboard.html +++ b/src/main/resources/templates/users/dashboard.html @@ -3,15 +3,18 @@ xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml"> + -

Пользователи

+
+

teste

+
@@ -19,6 +22,14 @@
+
\ No newline at end of file From f4479c2ab7d7d48806cac42361aa970b50cbd2ff Mon Sep 17 00:00:00 2001 From: "Artem.Arefev" Date: Sat, 25 May 2019 14:11:57 +0400 Subject: [PATCH 19/37] #91 fixed app properties --- src/main/resources/application.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 41c8ece..038ddcf 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -24,7 +24,7 @@ spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFact # JPA Settings spring.datasource.url=jdbc:postgresql://localhost:5432/ng-tracker spring.datasource.username=postgres -spring.datasource.password=password +spring.datasource.password=postgres spring.datasource.driverclassName=org.postgresql.Driver spring.jpa.hibernate.ddl-auto=validate # Liquibase Settings @@ -34,6 +34,6 @@ liquibase.change-log=classpath:db/changelog-master.xml # Application Settings ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin -ng-tracker.dev-mode=false +ng-tracker.dev-mode=true ng-tracker.use-https=false ng-tracker.check-run=false \ No newline at end of file From 59d6edb818c766e4f70776a0cf19de60119b84f2 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 15:42:08 +0400 Subject: [PATCH 20/37] #120 refactor --- .../java/ru/ulstu/grant/model/GrantDto.java | 7 +++ .../java/ru/ulstu/grant/page/KiasPage.java | 54 ++++++++++++------ .../ru/ulstu/grant/service/KiasService.java | 49 +++++++--------- src/test/java/IndexKiasTest.java | 56 ------------------- src/test/java/grant/KiasPage.java | 41 -------------- 5 files changed, 63 insertions(+), 144 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index 5a561b1..9e59d86 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -12,6 +12,7 @@ import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -96,6 +97,12 @@ public class GrantDto extends NameContainer { this.papers = convert(grant.getPapers(), PaperDto::new); } + public GrantDto(String grantTitle, Date deadLineDate) { + this.title = grantTitle; + deadlines.add(new Deadline(deadLineDate, "Окончание приёма заявок")); + status = Grant.GrantStatus.LOADED_FROM_KIAS; + } + public Integer getId() { return id; } diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java index 4353684..8a6e444 100644 --- a/src/main/java/ru/ulstu/grant/page/KiasPage.java +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -3,34 +3,31 @@ package ru.ulstu.grant.page; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; +import ru.ulstu.grant.model.GrantDto; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.NoSuchElementException; public class KiasPage { private WebDriver driver; + public KiasPage(WebDriver webDriver) { this.driver = webDriver; } - public List getGrants() { - List grants = new ArrayList<>(); + public List getKiasGrants() throws ParseException { + List newGrants = new ArrayList<>(); do { - grants.addAll(getPageOfGrants()); - } - while (checkPagination()); - - return grants; - } - - public List getPageOfGrants() { - WebElement listContest = driver.findElement(By.tagName("tBody")); - List grants = listContest.findElements(By.cssSelector("tr.tr")); - return grants; + newGrants.addAll(getGrantsFromPage()); + } while (goToNextPage()); //проверка существования следующей страницы с грантами + return newGrants; } - public boolean checkPagination() { + private boolean goToNextPage() { try { if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { driver.findElement(By.id("js-ctrlNext")).click(); @@ -42,11 +39,34 @@ public class KiasPage { return false; } - public String getGrantTitle(WebElement grant) { + private List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + private String getGrantTitle(WebElement grant) { return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); } - public String getFirstDeadline(WebElement grant) { - return grant.findElement(By.xpath("./td[5]")).getText(); + private List getGrantsFromPage() throws ParseException { + List grants = new ArrayList<>(); + for (WebElement grantElement : getPageOfGrants()) { + GrantDto grantDto = new GrantDto( + getGrantTitle(grantElement), + parseDeadLineDate(grantElement)); + grants.add(grantDto); + } + return grants; + } + + private Date parseDeadLineDate(WebElement grantElement) throws ParseException { + String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + return formatter.parse(deadlineDate); + } + + private String getFirstDeadline(WebElement grantElement) { + return grantElement.findElement(By.xpath("./td[5]")).getText(); } } diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java index 449b948..6881292 100644 --- a/src/main/java/ru/ulstu/grant/service/KiasService.java +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -1,22 +1,17 @@ package ru.ulstu.grant.service; import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.springframework.stereotype.Service; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.page.KiasPage; import ru.ulstu.user.service.UserService; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; -import java.util.Date; import java.util.List; @Service @@ -24,7 +19,6 @@ public class KiasService { private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; private final static String CONTEST_STATUS_ID = "1"; private final static String CONTEST_TYPE = "-1"; - private final static int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR); private final static String DRIVER_LOCATION = "drivers/%s"; private final static String WINDOWS_DRIVER = "chromedriver.exe"; @@ -38,33 +32,28 @@ public class KiasService { } public List getNewGrantsDto() throws ParseException { + WebDriver webDriver = getDriver(); + Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); + List grants = new ArrayList<>(); + for (Integer year : generateGrantYears()) { + webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); + grants.addAll(new KiasPage(webDriver).getKiasGrants()); + } + grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); + webDriver.quit(); + return grants; + } + + private List generateGrantYears() { + return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR), + Calendar.getInstance().get(Calendar.YEAR) + 1); + } + + private WebDriver getDriver() { System.setProperty(DRIVER_TYPE, getDriverExecutablePath()); final ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--headless"); - WebDriver webDriver = new ChromeDriver(chromeOptions); - webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)); - KiasPage kiasPage = new KiasPage(webDriver); - List kiasGrants = new ArrayList<>(); - List newGrants = new ArrayList<>(); - do { - kiasGrants.addAll(kiasPage.getPageOfGrants()); - for (WebElement grant : kiasGrants) { - GrantDto grantDto = new GrantDto(); - grantDto.setTitle(kiasPage.getGrantTitle(grant)); - String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 - SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); - Date date = formatter.parse(deadlineDate); - Deadline deadline = new Deadline(date, "Окончание приёма заявок"); - grantDto.setDeadlines(Arrays.asList(deadline)); - grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId()); - grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); - newGrants.add(grantDto); - } - kiasGrants.clear(); - } - while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами - webDriver.quit(); - return newGrants; + return new ChromeDriver(chromeOptions); } private String getDriverExecutablePath() { diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java index 73dc646..8228e76 100644 --- a/src/test/java/IndexKiasTest.java +++ b/src/test/java/IndexKiasTest.java @@ -1,67 +1,11 @@ -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import core.PageObject; import core.TestTemplate; -import grant.KiasPage; import org.junit.runner.RunWith; -import org.openqa.selenium.WebElement; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import ru.ulstu.NgTrackerApplication; -import ru.ulstu.deadline.model.Deadline; -import ru.ulstu.grant.model.Grant; -import ru.ulstu.grant.model.GrantDto; -import ru.ulstu.user.repository.UserRepository; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class IndexKiasTest extends TestTemplate { - private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; - private final static String CONTEST_STATUS_ID = "1"; - private final static String CONTEST_TYPE = "-1"; - private final static String CONTEST_YEAR = "2019"; - - private final Map> navigationHolder = ImmutableMap.of( - new KiasPage(), Arrays.asList("Поиск по конкурсам", - String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR)) - ); - - @Autowired - UserRepository userRepository; - - public List getNewGrantsDto() throws ParseException { - Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); - getContext().goTo(page.getValue().get(1)); - KiasPage kiasPage = (KiasPage) getContext().initPage(page.getKey()); - List kiasGrants = new ArrayList<>(); - List newGrants = new ArrayList<>(); - do { - kiasGrants.addAll(kiasPage.getPageOfGrants()); - for (WebElement grant : kiasGrants) { - GrantDto grantDto = new GrantDto(); - grantDto.setTitle(kiasPage.getGrantTitle(grant)); - String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59 - SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); - Date date = formatter.parse(deadlineDate); - Deadline deadline = new Deadline(date, "Окончание приёма заявок"); - grantDto.setDeadlines(Arrays.asList(deadline)); - grantDto.setLeaderId(userRepository.findOneByLoginIgnoreCase("admin").getId()); - grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS); - newGrants.add(grantDto); - } - kiasGrants.clear(); - } - while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами - return newGrants; - } } diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java index 7723b01..5864511 100644 --- a/src/test/java/grant/KiasPage.java +++ b/src/test/java/grant/KiasPage.java @@ -2,51 +2,10 @@ package grant; import core.PageObject; import org.openqa.selenium.By; -import org.openqa.selenium.WebElement; - -import java.util.ArrayList; -import java.util.List; -import java.util.NoSuchElementException; public class KiasPage extends PageObject { @Override public String getSubTitle() { return driver.findElement(By.tagName("h1")).getText(); } - - public List getGrants() { - List grants = new ArrayList<>(); - do { - grants.addAll(getPageOfGrants()); - } - while (checkPagination()); - - return grants; - } - - public List getPageOfGrants() { - WebElement listContest = driver.findElement(By.tagName("tBody")); - List grants = listContest.findElements(By.cssSelector("tr.tr")); - return grants; - } - - public boolean checkPagination() { - try { - if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { - driver.findElement(By.id("js-ctrlNext")).click(); - return true; - } - } catch (NoSuchElementException e) { - return false; - } - return false; - } - - public String getGrantTitle(WebElement grant) { - return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); - } - - public String getFirstDeadline(WebElement grant) { - return grant.findElement(By.xpath("./td[5]")).getText(); - } } From 477a9fd6ffbff5d4128d31f298cc1212a4f0cc0b Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 15:48:32 +0400 Subject: [PATCH 21/37] #120 move to service --- .../java/ru/ulstu/grant/page/KiasPage.java | 29 +++---------------- .../ru/ulstu/grant/service/KiasService.java | 23 ++++++++++++++- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java index 8a6e444..ea9bdb4 100644 --- a/src/main/java/ru/ulstu/grant/page/KiasPage.java +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -3,11 +3,9 @@ package ru.ulstu.grant.page; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; -import ru.ulstu.grant.model.GrantDto; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.NoSuchElementException; @@ -19,15 +17,7 @@ public class KiasPage { this.driver = webDriver; } - public List getKiasGrants() throws ParseException { - List newGrants = new ArrayList<>(); - do { - newGrants.addAll(getGrantsFromPage()); - } while (goToNextPage()); //проверка существования следующей страницы с грантами - return newGrants; - } - - private boolean goToNextPage() { + public boolean goToNextPage() { try { if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { driver.findElement(By.id("js-ctrlNext")).click(); @@ -39,28 +29,17 @@ public class KiasPage { return false; } - private List getPageOfGrants() { + public List getPageOfGrants() { WebElement listContest = driver.findElement(By.tagName("tBody")); List grants = listContest.findElements(By.cssSelector("tr.tr")); return grants; } - private String getGrantTitle(WebElement grant) { + public String getGrantTitle(WebElement grant) { return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); } - private List getGrantsFromPage() throws ParseException { - List grants = new ArrayList<>(); - for (WebElement grantElement : getPageOfGrants()) { - GrantDto grantDto = new GrantDto( - getGrantTitle(grantElement), - parseDeadLineDate(grantElement)); - grants.add(grantDto); - } - return grants; - } - - private Date parseDeadLineDate(WebElement grantElement) throws ParseException { + public Date parseDeadLineDate(WebElement grantElement) throws ParseException { String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); return formatter.parse(deadlineDate); diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java index 6881292..618e83c 100644 --- a/src/main/java/ru/ulstu/grant/service/KiasService.java +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -1,6 +1,7 @@ package ru.ulstu.grant.service; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.springframework.stereotype.Service; @@ -37,13 +38,33 @@ public class KiasService { List grants = new ArrayList<>(); for (Integer year : generateGrantYears()) { webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); - grants.addAll(new KiasPage(webDriver).getKiasGrants()); + grants.addAll(getKiasGrants(webDriver)); } grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); webDriver.quit(); return grants; } + public List getKiasGrants(WebDriver webDriver) throws ParseException { + List newGrants = new ArrayList<>(); + KiasPage kiasPage = new KiasPage(webDriver); + do { + newGrants.addAll(getGrantsFromPage(kiasPage)); + } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами + return newGrants; + } + + private List getGrantsFromPage(KiasPage kiasPage) throws ParseException { + List grants = new ArrayList<>(); + for (WebElement grantElement : kiasPage.getPageOfGrants()) { + GrantDto grantDto = new GrantDto( + kiasPage.getGrantTitle(grantElement), + kiasPage.parseDeadLineDate(grantElement)); + grants.add(grantDto); + } + return grants; + } + private List generateGrantYears() { return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.YEAR) + 1); From 916bbae41494d0420a4aaede0c633d3730ca4806 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 21:15:21 +0400 Subject: [PATCH 22/37] #120 add debug email --- .../ulstu/configuration/ApplicationProperties.java | 10 ++++++++++ .../java/ru/ulstu/user/service/MailService.java | 13 ++++++++++--- src/main/resources/application.properties | 1 + 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java index f75f53f..49efac4 100644 --- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java +++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java @@ -21,6 +21,8 @@ public class ApplicationProperties { private boolean checkRun; + private String debugEmail; + public boolean isUseHttps() { return useHttps; } @@ -60,4 +62,12 @@ public class ApplicationProperties { public void setCheckRun(boolean checkRun) { this.checkRun = checkRun; } + + public String getDebugEmail() { + return debugEmail; + } + + public void setDebugEmail(String debugEmail) { + this.debugEmail = debugEmail; + } } diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java index 864b749..3724792 100644 --- a/src/main/java/ru/ulstu/user/service/MailService.java +++ b/src/main/java/ru/ulstu/user/service/MailService.java @@ -1,5 +1,6 @@ package ru.ulstu.user.service; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.mail.MailProperties; @@ -21,11 +22,9 @@ import java.util.Map; @Service public class MailService { - private final Logger log = LoggerFactory.getLogger(MailService.class); - private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; - + private final Logger log = LoggerFactory.getLogger(MailService.class); private final JavaMailSender javaMailSender; private final SpringTemplateEngine templateEngine; private final MailProperties mailProperties; @@ -48,10 +47,18 @@ public class MailService { message.setFrom(mailProperties.getUsername()); message.setSubject(subject); message.setText(content, true); + modifyForDebug(message, subject); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); } + private void modifyForDebug(MimeMessageHelper message, String originalSubject) throws MessagingException { + if (!StringUtils.isEmpty(applicationProperties.getDebugEmail())) { + message.setTo(applicationProperties.getDebugEmail()); + message.setSubject("To " + applicationProperties.getDebugEmail() + "; " + originalSubject); + } + } + @Async public void sendEmailFromTemplate(User user, String templateName, String subject) { Context context = new Context(); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 038ddcf..cdd7569 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,5 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin ng-tracker.dev-mode=true +ng-tracker.debug_email=romanov73@gmail.com ng-tracker.use-https=false ng-tracker.check-run=false \ No newline at end of file From 678397e970099cb6c655cc3ece6f43c3a47abf30 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 21:15:54 +0400 Subject: [PATCH 23/37] #120 test classes refactor --- .../{IndexConferenceTest.java => ConferenceTest.java} | 2 +- src/test/java/IndexKiasTest.java | 11 ----------- .../java/{IndexTaskTest.java => StudentTaskTest.java} | 2 +- 3 files changed, 2 insertions(+), 13 deletions(-) rename src/test/java/{IndexConferenceTest.java => ConferenceTest.java} (99%) delete mode 100644 src/test/java/IndexKiasTest.java rename src/test/java/{IndexTaskTest.java => StudentTaskTest.java} (99%) diff --git a/src/test/java/IndexConferenceTest.java b/src/test/java/ConferenceTest.java similarity index 99% rename from src/test/java/IndexConferenceTest.java rename to src/test/java/ConferenceTest.java index 269561f..3fae34b 100644 --- a/src/test/java/IndexConferenceTest.java +++ b/src/test/java/ConferenceTest.java @@ -26,7 +26,7 @@ import java.util.Map; @RunWith(SpringRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class IndexConferenceTest extends TestTemplate { +public class ConferenceTest extends TestTemplate { private final Map> navigationHolder = ImmutableMap.of( new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"), new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"), diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java deleted file mode 100644 index 8228e76..0000000 --- a/src/test/java/IndexKiasTest.java +++ /dev/null @@ -1,11 +0,0 @@ -import core.TestTemplate; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import ru.ulstu.NgTrackerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class IndexKiasTest extends TestTemplate { - -} diff --git a/src/test/java/IndexTaskTest.java b/src/test/java/StudentTaskTest.java similarity index 99% rename from src/test/java/IndexTaskTest.java rename to src/test/java/StudentTaskTest.java index 51b5e07..f15b55c 100644 --- a/src/test/java/IndexTaskTest.java +++ b/src/test/java/StudentTaskTest.java @@ -24,7 +24,7 @@ import java.util.Map; @RunWith(SpringRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class IndexTaskTest extends TestTemplate { +public class StudentTaskTest extends TestTemplate { private final Map> navigationHolder = ImmutableMap.of( new TasksPage(), Arrays.asList("Список задач", "/students/tasks"), new TasksDashboardPage(), Arrays.asList("Панель управления", "/students/dashboard"), From 828d320e0f9f9d38b6beca019c9cdf3b97245a49 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 21:16:26 +0400 Subject: [PATCH 24/37] #120 try to run test in docker --- .gitlab-ci.yml | 2 +- src/main/java/ru/ulstu/grant/page/KiasPage.java | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fb4c0ed..6709891 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,7 +22,7 @@ checkRun: checkStyle: stage: test - script: ./gradlew check -x test + script: ./gradlew check deploy: stage: deploy diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java index ea9bdb4..631f5db 100644 --- a/src/main/java/ru/ulstu/grant/page/KiasPage.java +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -8,9 +8,9 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; -import java.util.NoSuchElementException; public class KiasPage { + private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm"; private WebDriver driver; public KiasPage(WebDriver webDriver) { @@ -23,10 +23,9 @@ public class KiasPage { driver.findElement(By.id("js-ctrlNext")).click(); return true; } - } catch (NoSuchElementException e) { + } finally { return false; } - return false; } public List getPageOfGrants() { @@ -41,7 +40,7 @@ public class KiasPage { public Date parseDeadLineDate(WebElement grantElement) throws ParseException { String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 - SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); + SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT); return formatter.parse(deadlineDate); } From 280c39dae4ddc76db07b21e5d12dbc2d47c59ca9 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 21:32:20 +0400 Subject: [PATCH 25/37] #120 fix variable --- src/test/java/StudentTaskTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/StudentTaskTest.java b/src/test/java/StudentTaskTest.java index f15b55c..f55a679 100644 --- a/src/test/java/StudentTaskTest.java +++ b/src/test/java/StudentTaskTest.java @@ -31,7 +31,7 @@ public class StudentTaskTest extends TestTemplate { new TaskPage(), Arrays.asList("Создать задачу", "/students/task?id=0") ); - private final String TAG = "ATag"; + private final String tag = "ATag"; @Autowired private ApplicationProperties applicationProperties; @@ -168,13 +168,13 @@ public class StudentTaskTest extends TestTemplate { String taskName = "Task " + (new Date()).getTime(); taskPage.setName(taskName); - taskPage.setTag(TAG); + taskPage.setTag(tag); Thread.sleep(1000); taskPage.addDeadlineDate("01.01.2020", 0); taskPage.addDeadlineDescription("Description", 0); taskPage.save(); - Assert.assertTrue(tasksPage.findTaskByTag(taskName, TAG)); + Assert.assertTrue(tasksPage.findTaskByTag(taskName, tag)); } @Test @@ -185,7 +185,7 @@ public class StudentTaskTest extends TestTemplate { TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); - Assert.assertTrue(tasksPage.findTag(TAG)); + Assert.assertTrue(tasksPage.findTag(tag)); } @Test @@ -194,9 +194,9 @@ public class StudentTaskTest extends TestTemplate { getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); - tasksPage.selectTag(TAG); + tasksPage.selectTag(tag); - Assert.assertTrue(tasksPage.findTasksByTag(TAG)); + Assert.assertTrue(tasksPage.findTasksByTag(tag)); } @Test From 0cd3055176e76f2214478755da97830d44ee6bc9 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Sat, 25 May 2019 21:33:06 +0400 Subject: [PATCH 26/37] #120 disable tests --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6709891..fb4c0ed 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,7 +22,7 @@ checkRun: checkStyle: stage: test - script: ./gradlew check + script: ./gradlew check -x test deploy: stage: deploy From 336a16ff73938acb32188a0f55caca3577961c16 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Mon, 27 May 2019 09:14:24 +0400 Subject: [PATCH 27/37] some refactor --- .../grant/controller/GrantController.java | 2 +- src/main/java/ru/ulstu/grant/model/Grant.java | 7 ++-- .../grant/repository/GrantRepository.java | 3 ++ .../ulstu/grant/service/GrantScheduler.java | 2 +- .../ru/ulstu/grant/service/GrantService.java | 19 +++++---- .../java/ru/ulstu/timeline/model/Event.java | 4 +- src/main/resources/application.properties | 2 +- .../grants/fragments/grantLineFragment.html | 3 +- .../resources/templates/grants/grant.html | 42 +------------------ .../papers/fragments/paperLineFragment.html | 3 +- 10 files changed, 27 insertions(+), 60 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java index 91b0f91..a9c01ed 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -43,7 +43,7 @@ public class GrantController { @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllDto()); + modelMap.put("grants", grantService.findAllActiveDto()); } @GetMapping("/grant") diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java index e0cd9be..369568f 100644 --- a/src/main/java/ru/ulstu/grant/model/Grant.java +++ b/src/main/java/ru/ulstu/grant/model/Grant.java @@ -43,7 +43,8 @@ public class Grant extends BaseEntity implements UserContainer { IN_WORK("В работе"), COMPLETED("Завершен"), FAILED("Провалены сроки"), - LOADED_FROM_KIAS("Загружен автоматически"); + LOADED_FROM_KIAS("Загружен автоматически"), + SKIPPED("Не интересует"); private String statusName; @@ -62,14 +63,14 @@ public class Grant extends BaseEntity implements UserContainer { @Enumerated(value = EnumType.STRING) private GrantStatus status = GrantStatus.APPLICATION; - @OneToMany(cascade = CascadeType.ALL) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "grant_id") @OrderBy("date") private List deadlines = new ArrayList<>(); private String comment; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "grant_id", unique = true) @Fetch(FetchMode.SUBSELECT) private List files = new ArrayList<>(); diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index ae9fcc8..876a8c1 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -17,4 +17,7 @@ public interface GrantRepository extends JpaRepository, BaseRepo @Override @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')") + List findAllActive(); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index fb236af..a2950a6 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -31,7 +31,7 @@ public class GrantScheduler { log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); } - @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara") + @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara") public void loadGrantsFromKias() { log.debug("GrantScheduler.loadGrantsFromKias started"); try { diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 8d65da7..86f8f1b 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -41,7 +41,6 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service public class GrantService extends BaseService { - private final static int MAX_DISPLAY_SIZE = 50; private final Logger log = LoggerFactory.getLogger(GrantService.class); private final GrantRepository grantRepository; @@ -80,9 +79,7 @@ public class GrantService extends BaseService { } public List findAllDto() { - List grants = convert(findAll(), GrantDto::new); - grants.forEach(grantDto -> grantDto.setTitle(StringUtils.abbreviate(grantDto.getTitle(), MAX_DISPLAY_SIZE))); - return grants; + return convert(findAll(), GrantDto::new); } public GrantDto findOneDto(Integer id) { @@ -273,11 +270,7 @@ public class GrantService extends BaseService { } public List getAllUncompletedPapers() { - List papers = paperService.findAllNotCompleted(); - papers.stream() - .forEach(paper -> - paper.setTitle(StringUtils.abbreviate(paper.getTitle(), MAX_DISPLAY_SIZE))); - return papers; + return paperService.findAllNotCompleted(); } public void attachPaper(GrantDto grantDto) { @@ -335,4 +328,12 @@ public class GrantService extends BaseService { } } } + + public List findAllActiveDto() { + return convert(findAllActive(), GrantDto::new); + } + + private List findAllActive() { + return grantRepository.findAllActive(); + } } diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java index e56c91c..8038f0b 100644 --- a/src/main/java/ru/ulstu/timeline/model/Event.java +++ b/src/main/java/ru/ulstu/timeline/model/Event.java @@ -65,8 +65,8 @@ public class Event extends BaseEntity { private String description; - @ManyToMany(fetch = FetchType.EAGER) - private List recipients = new ArrayList(); + @ManyToMany(fetch = FetchType.LAZY) + private List recipients = new ArrayList<>(); @ManyToOne @JoinColumn(name = "child_id") diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index cdd7569..f4be778 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,6 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin ng-tracker.dev-mode=true -ng-tracker.debug_email=romanov73@gmail.com +ng-tracker.debug_email= ng-tracker.use-https=false ng-tracker.check-run=false \ No newline at end of file diff --git a/src/main/resources/templates/grants/fragments/grantLineFragment.html b/src/main/resources/templates/grants/fragments/grantLineFragment.html index dda0e8d..877f1d7 100644 --- a/src/main/resources/templates/grants/fragments/grantLineFragment.html +++ b/src/main/resources/templates/grants/fragments/grantLineFragment.html @@ -8,7 +8,8 @@
- + + diff --git a/src/main/resources/templates/grants/grant.html b/src/main/resources/templates/grants/grant.html index 38047bf..acb7f7b 100644 --- a/src/main/resources/templates/grants/grant.html +++ b/src/main/resources/templates/grants/grant.html @@ -186,47 +186,7 @@
- - -
- - - Статус статьи - -
- +
diff --git a/src/main/resources/templates/papers/fragments/paperLineFragment.html b/src/main/resources/templates/papers/fragments/paperLineFragment.html index b703859..40d9c34 100644 --- a/src/main/resources/templates/papers/fragments/paperLineFragment.html +++ b/src/main/resources/templates/papers/fragments/paperLineFragment.html @@ -8,7 +8,8 @@
- + + From 4eeb79ab80fedec0b8d69dc901cb5d9cb326e312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 27 May 2019 09:19:52 +0300 Subject: [PATCH 28/37] #98 changelog edited --- .../java/ru/ulstu/deadline/model/Deadline.java | 10 +++++----- .../db/changelog-20190517_000001-schema.xml | 14 ++++++++++++++ src/main/resources/db/changelog-master.xml | 1 + 3 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 src/main/resources/db/changelog-20190517_000001-schema.xml diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 5ab9f47..4dfebef 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -20,7 +20,7 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; - private String executor; + private Integer executor; private Boolean done; public Deadline() { @@ -31,7 +31,7 @@ public class Deadline extends BaseEntity { this.description = description; } - public Deadline(Date deadlineDate, String description, String executor, Boolean done) { + public Deadline(Date deadlineDate, String description, Integer executor, Boolean done) { this.date = deadlineDate; this.description = description; this.executor = executor; @@ -42,7 +42,7 @@ public class Deadline extends BaseEntity { public Deadline(@JsonProperty("id") Integer id, @JsonProperty("description") String description, @JsonProperty("date") Date date, - @JsonProperty("executor") String executor, + @JsonProperty("executor") Integer executor, @JsonProperty("done") Boolean done) { this.setId(id); this.description = description; @@ -67,11 +67,11 @@ public class Deadline extends BaseEntity { this.date = date; } - public String getExecutor() { + public Integer getExecutor() { return executor; } - public void setExecutor(String executor) { + public void setExecutor(Integer executor) { this.executor = executor; } diff --git a/src/main/resources/db/changelog-20190517_000001-schema.xml b/src/main/resources/db/changelog-20190517_000001-schema.xml new file mode 100644 index 0000000..73c6435 --- /dev/null +++ b/src/main/resources/db/changelog-20190517_000001-schema.xml @@ -0,0 +1,14 @@ + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index 1cab67b..d81f1cb 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -44,4 +44,5 @@ + \ No newline at end of file From 7388e12e3f5d50ab6278f99e96ff0d49046b9ea7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Mon, 27 May 2019 18:19:31 +0300 Subject: [PATCH 29/37] #98 edited project executors --- .../project/controller/ProjectController.java | 6 +++++ .../java/ru/ulstu/project/model/Project.java | 9 ++++++- .../ru/ulstu/project/model/ProjectDto.java | 24 ++++++++++++++++++- .../ulstu/project/service/ProjectService.java | 13 +++++++++- .../resources/templates/projects/project.html | 9 +++++-- 5 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/main/java/ru/ulstu/project/controller/ProjectController.java b/src/main/java/ru/ulstu/project/controller/ProjectController.java index 14b8736..88f0c7a 100644 --- a/src/main/java/ru/ulstu/project/controller/ProjectController.java +++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java @@ -13,6 +13,7 @@ import ru.ulstu.deadline.model.Deadline; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.service.ProjectService; +import ru.ulstu.user.model.User; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; @@ -92,6 +93,11 @@ public class ProjectController { return String.format("redirect:%s", "/projects/projects"); } + @ModelAttribute("allExecutors") + public List getAllExecutors(ProjectDto projectDto) { + return projectService.getProjectExecutors(projectDto); + } + private void filterEmptyDeadlines(ProjectDto projectDto) { projectDto.setDeadlines(projectDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index acf0d0f..f061221 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -2,6 +2,7 @@ package ru.ulstu.project.model; import org.hibernate.validator.constraints.NotBlank; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.UserContainer; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileData; import ru.ulstu.grant.model.Grant; @@ -23,7 +24,8 @@ import java.util.List; import java.util.Set; @Entity -public class Project extends BaseEntity { +public class Project extends BaseEntity implements UserContainer { + public enum ProjectStatus { APPLICATION("Заявка"), ON_COMPETITION("Отправлен на конкурс"), @@ -133,4 +135,9 @@ public class Project extends BaseEntity { public void setExecutors(Set executors) { this.executors = executors; } + + @Override + public Set getUsers() { + return getExecutors(); + } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 0f86e1a..0292f1f 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -29,6 +29,8 @@ public class ProjectDto { private List removedDeadlineIds = new ArrayList<>(); private Set executorIds; private Set executors; + private boolean hasAge; + private boolean hasDegree; private final static int MAX_EXECUTORS_LENGTH = 40; @@ -48,7 +50,9 @@ public class ProjectDto { @JsonProperty("repository") String repository, @JsonProperty("deadlines") List deadlines, @JsonProperty("executorIds") Set executorIds, - @JsonProperty("executors") Set executors) { + @JsonProperty("executors") Set executors, + @JsonProperty("hasAge") boolean hasAge, + @JsonProperty("hasDegree") boolean hasDegree) { this.id = id; this.title = title; this.status = status; @@ -59,6 +63,8 @@ public class ProjectDto { this.applicationFileName = null; this.executorIds = executorIds; this.executors = executors; + this.hasAge = hasAge; + this.hasDegree = hasDegree; } @@ -163,6 +169,22 @@ public class ProjectDto { this.executors = executors; } + public boolean isHasAge() { + return hasAge; + } + + public void setHasAge(boolean hasAge) { + this.hasAge = hasAge; + } + + public boolean isHasDegree() { + return hasDegree; + } + + public void setHasDegree(boolean hasDegree) { + this.hasDegree = hasDegree; + } + public String getExecutorsString() { return StringUtils.abbreviate(executors .stream() diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 4a79e6c..2f6473b 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -5,10 +5,13 @@ import org.springframework.transaction.annotation.Transactional; import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.service.FileService; +import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.repository.ProjectRepository; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; import java.io.IOException; import java.util.Arrays; @@ -26,15 +29,18 @@ public class ProjectService { private final DeadlineService deadlineService; private final GrantRepository grantRepository; private final FileService fileService; + private final UserService userService; public ProjectService(ProjectRepository projectRepository, DeadlineService deadlineService, GrantRepository grantRepository, - FileService fileService) { + FileService fileService, + UserService userService) { this.projectRepository = projectRepository; this.deadlineService = deadlineService; this.grantRepository = grantRepository; this.fileService = fileService; + this.userService = userService; } public List findAll() { @@ -115,4 +121,9 @@ public class ProjectService { return projectRepository.findOne(id); } + public List getProjectExecutors(ProjectDto projectDto) { + List filteredUsers = userService.filterByAgeAndDegree(projectDto.isHasAge(), projectDto.isHasDegree()); + return filteredUsers; + } + } diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index 8385694..304fed0 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -92,8 +92,13 @@
- +
Date: Tue, 28 May 2019 00:40:36 +0400 Subject: [PATCH 30/37] #98 project statuses edited --- src/main/java/ru/ulstu/project/model/Project.java | 10 +++++----- .../java/ru/ulstu/project/service/ProjectService.java | 4 ++-- .../projects/fragments/projectStatusFragment.html | 10 +++++----- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index f061221..cf0de14 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -27,11 +27,11 @@ import java.util.Set; public class Project extends BaseEntity implements UserContainer { public enum ProjectStatus { - APPLICATION("Заявка"), - ON_COMPETITION("Отправлен на конкурс"), - SUCCESSFUL_PASSAGE("Успешное прохождение"), + TT("ТЗ"), + OPEN("Открыт"), IN_WORK("В работе"), - COMPLETED("Завершен"), + CERTIFICATE_ISSUED("Оформление свидетельства"), + CLOSED("Закрыт"), FAILED("Провалены сроки"); private String statusName; @@ -49,7 +49,7 @@ public class Project extends BaseEntity implements UserContainer { private String title; @Enumerated(value = EnumType.STRING) - private ProjectStatus status = ProjectStatus.APPLICATION; + private ProjectStatus status = ProjectStatus.TT; @NotNull private String description; diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 2f6473b..2b9e82b 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -19,7 +19,7 @@ import java.util.List; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.project.model.Project.ProjectStatus.APPLICATION; +import static ru.ulstu.project.model.Project.ProjectStatus.TT; @Service public class ProjectService { @@ -89,7 +89,7 @@ public class ProjectService { private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { project.setDescription(projectDto.getDescription()); - project.setStatus(projectDto.getStatus() == null ? APPLICATION : projectDto.getStatus()); + project.setStatus(projectDto.getStatus() == null ? TT : projectDto.getStatus()); project.setTitle(projectDto.getTitle()); if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { project.setGrant(grantRepository.findOne(projectDto.getGrant().getId())); diff --git a/src/main/resources/templates/projects/fragments/projectStatusFragment.html b/src/main/resources/templates/projects/fragments/projectStatusFragment.html index d8f29cc..c56958e 100644 --- a/src/main/resources/templates/projects/fragments/projectStatusFragment.html +++ b/src/main/resources/templates/projects/fragments/projectStatusFragment.html @@ -6,19 +6,19 @@ -
+
-
+
-
+
-
+
-
+
From 3b0a2dd964c60fc53c4ec9ac64fedcedb4dc7594 Mon Sep 17 00:00:00 2001 From: "a.vasin" Date: Tue, 28 May 2019 11:12:27 +0400 Subject: [PATCH 31/37] #98 executors list added --- .../ru/ulstu/deadline/model/Deadline.java | 30 ++++++++++--------- .../deadline/service/DeadlineService.java | 4 +-- .../java/ru/ulstu/project/model/Project.java | 15 +++++----- .../ru/ulstu/project/model/ProjectDto.java | 13 ++++---- .../ulstu/project/service/ProjectService.java | 5 ++-- .../db/changelog-20190528_000000-schema.xml | 11 +++++++ .../db/changelog-20190528_000001-schema.xml | 17 +++++++++++ src/main/resources/db/changelog-master.xml | 2 ++ .../fragments/projectStatusFragment.html | 2 +- 9 files changed, 67 insertions(+), 32 deletions(-) create mode 100644 src/main/resources/db/changelog-20190528_000000-schema.xml create mode 100644 src/main/resources/db/changelog-20190528_000001-schema.xml diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 3a54bec..97b6441 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -4,11 +4,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.user.model.User; -import javax.persistence.Entity; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import javax.persistence.*; import java.util.Date; +import java.util.List; import java.util.Objects; @Entity @@ -20,7 +20,9 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; - private Integer executor; + @OneToMany(targetEntity=User.class, fetch=FetchType.EAGER) + private List executors; + private Boolean done; public Deadline() { @@ -31,10 +33,10 @@ public class Deadline extends BaseEntity { this.description = description; } - public Deadline(Date deadlineDate, String description, Integer executor, Boolean done) { + public Deadline(Date deadlineDate, String description, List executors, Boolean done) { this.date = deadlineDate; this.description = description; - this.executor = executor; + this.executors = executors; this.done = done; } @@ -42,12 +44,12 @@ public class Deadline extends BaseEntity { public Deadline(@JsonProperty("id") Integer id, @JsonProperty("description") String description, @JsonProperty("date") Date date, - @JsonProperty("executor") Integer executor, + @JsonProperty("executors") List executors, @JsonProperty("done") Boolean done) { this.setId(id); this.description = description; this.date = date; - this.executor = executor; + this.executors = executors; this.done = done; } @@ -67,12 +69,12 @@ public class Deadline extends BaseEntity { this.date = date; } - public Integer getExecutor() { - return executor; + public List getExecutors() { + return executors; } - public void setExecutor(Integer executor) { - this.executor = executor; + public void setExecutors(List executors) { + this.executors = executors; } public Boolean getDone() { @@ -103,12 +105,12 @@ public class Deadline extends BaseEntity { return getId().equals(deadline.getId()) && description.equals(deadline.description) && date.equals(deadline.date) && - executor.equals(deadline.executor) && + executors.equals(deadline.executors) && done.equals(deadline.done); } @Override public int hashCode() { - return Objects.hash(super.hashCode(), description, date, executor, done); + return Objects.hash(super.hashCode(), description, date, executors, done); } } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java index 83f1afb..9c45537 100644 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java @@ -30,7 +30,7 @@ public class DeadlineService { Deadline updateDeadline = deadlineRepository.findOne(deadline.getId()); updateDeadline.setDate(deadline.getDate()); updateDeadline.setDescription(deadline.getDescription()); - updateDeadline.setExecutor(deadline.getExecutor()); + updateDeadline.setExecutors(deadline.getExecutors()); updateDeadline.setDone(deadline.getDone()); deadlineRepository.save(updateDeadline); return updateDeadline; @@ -41,7 +41,7 @@ public class DeadlineService { Deadline newDeadline = new Deadline(); newDeadline.setDate(deadline.getDate()); newDeadline.setDescription(deadline.getDescription()); - newDeadline.setExecutor(deadline.getExecutor()); + newDeadline.setExecutors(deadline.getExecutors()); newDeadline.setDone(deadline.getDone()); newDeadline = deadlineRepository.save(newDeadline); return newDeadline; diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java index cf0de14..3d11583 100644 --- a/src/main/java/ru/ulstu/project/model/Project.java +++ b/src/main/java/ru/ulstu/project/model/Project.java @@ -27,7 +27,7 @@ import java.util.Set; public class Project extends BaseEntity implements UserContainer { public enum ProjectStatus { - TT("ТЗ"), + TECHNICAL_TASK("Техническое задание"), OPEN("Открыт"), IN_WORK("В работе"), CERTIFICATE_ISSUED("Оформление свидетельства"), @@ -49,7 +49,7 @@ public class Project extends BaseEntity implements UserContainer { private String title; @Enumerated(value = EnumType.STRING) - private ProjectStatus status = ProjectStatus.TT; + private ProjectStatus status = ProjectStatus.TECHNICAL_TASK; @NotNull private String description; @@ -69,8 +69,8 @@ public class Project extends BaseEntity implements UserContainer { @JoinColumn(name = "file_id") private FileData application; - @ManyToMany(fetch = FetchType.EAGER) - private Set executors = new HashSet<>(); + @ManyToMany(fetch = FetchType.LAZY) + private List executors = new ArrayList<>(); public String getTitle() { return title; @@ -128,16 +128,17 @@ public class Project extends BaseEntity implements UserContainer { this.application = application; } - public Set getExecutors() { + public List getExecutors() { return executors; } - public void setExecutors(Set executors) { + public void setExecutors(List executors) { this.executors = executors; } @Override public Set getUsers() { - return getExecutors(); + Set users = new HashSet(getExecutors()); + return users; } } diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index 0292f1f..f6ee831 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -6,9 +6,11 @@ import org.hibernate.validator.constraints.NotEmpty; import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -28,7 +30,7 @@ public class ProjectDto { private String applicationFileName; private List removedDeadlineIds = new ArrayList<>(); private Set executorIds; - private Set executors; + private List executors; private boolean hasAge; private boolean hasDegree; @@ -50,7 +52,7 @@ public class ProjectDto { @JsonProperty("repository") String repository, @JsonProperty("deadlines") List deadlines, @JsonProperty("executorIds") Set executorIds, - @JsonProperty("executors") Set executors, + @JsonProperty("executors") List executors, @JsonProperty("hasAge") boolean hasAge, @JsonProperty("hasDegree") boolean hasDegree) { this.id = id; @@ -69,6 +71,7 @@ public class ProjectDto { public ProjectDto(Project project) { + Set users = new HashSet(project.getExecutors()); this.id = project.getId(); this.title = project.getTitle(); this.status = project.getStatus(); @@ -77,7 +80,7 @@ public class ProjectDto { this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.repository = project.getRepository(); this.deadlines = project.getDeadlines(); - this.executorIds = convert(project.getExecutors(), user -> user.getId()); + this.executorIds = convert(users, user -> user.getId()); this.executors = convert(project.getExecutors(), UserDto::new); } @@ -161,11 +164,11 @@ public class ProjectDto { this.executorIds = executorIds; } - public Set getExecutors() { + public List getExecutors() { return executors; } - public void setExecutors(Set executors) { + public void setExecutors(List executors) { this.executors = executors; } diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index 2b9e82b..ab2fa91 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -5,7 +5,6 @@ import org.springframework.transaction.annotation.Transactional; import org.thymeleaf.util.StringUtils; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.service.FileService; -import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.project.model.Project; import ru.ulstu.project.model.ProjectDto; @@ -19,7 +18,7 @@ import java.util.List; import static org.springframework.util.ObjectUtils.isEmpty; import static ru.ulstu.core.util.StreamApiUtils.convert; -import static ru.ulstu.project.model.Project.ProjectStatus.TT; +import static ru.ulstu.project.model.Project.ProjectStatus.TECHNICAL_TASK; @Service public class ProjectService { @@ -89,7 +88,7 @@ public class ProjectService { private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { project.setDescription(projectDto.getDescription()); - project.setStatus(projectDto.getStatus() == null ? TT : projectDto.getStatus()); + project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus()); project.setTitle(projectDto.getTitle()); if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { project.setGrant(grantRepository.findOne(projectDto.getGrant().getId())); diff --git a/src/main/resources/db/changelog-20190528_000000-schema.xml b/src/main/resources/db/changelog-20190528_000000-schema.xml new file mode 100644 index 0000000..02ba642 --- /dev/null +++ b/src/main/resources/db/changelog-20190528_000000-schema.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/src/main/resources/db/changelog-20190528_000001-schema.xml b/src/main/resources/db/changelog-20190528_000001-schema.xml new file mode 100644 index 0000000..0605b48 --- /dev/null +++ b/src/main/resources/db/changelog-20190528_000001-schema.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index b4ce865..fbc1ec3 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -47,4 +47,6 @@ + + \ No newline at end of file diff --git a/src/main/resources/templates/projects/fragments/projectStatusFragment.html b/src/main/resources/templates/projects/fragments/projectStatusFragment.html index c56958e..bf0d3f6 100644 --- a/src/main/resources/templates/projects/fragments/projectStatusFragment.html +++ b/src/main/resources/templates/projects/fragments/projectStatusFragment.html @@ -6,7 +6,7 @@ -
+
From c25392337a3ababebf34e4c3404f277ab945b184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Tue, 28 May 2019 16:16:41 +0300 Subject: [PATCH 32/37] #98 project deadlines edited --- .../ru/ulstu/project/model/ProjectDto.java | 24 +------------------ .../ulstu/project/service/ProjectService.java | 8 +++---- ...l => changelog-20190528_000002-schema.xml} | 6 ++--- src/main/resources/db/changelog-master.xml | 2 +- .../resources/templates/projects/project.html | 8 +++---- 5 files changed, 13 insertions(+), 35 deletions(-) rename src/main/resources/db/{changelog-20190528_000001-schema.xml => changelog-20190528_000002-schema.xml} (87%) diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java index f6ee831..affee4e 100644 --- a/src/main/java/ru/ulstu/project/model/ProjectDto.java +++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java @@ -31,8 +31,6 @@ public class ProjectDto { private List removedDeadlineIds = new ArrayList<>(); private Set executorIds; private List executors; - private boolean hasAge; - private boolean hasDegree; private final static int MAX_EXECUTORS_LENGTH = 40; @@ -52,9 +50,7 @@ public class ProjectDto { @JsonProperty("repository") String repository, @JsonProperty("deadlines") List deadlines, @JsonProperty("executorIds") Set executorIds, - @JsonProperty("executors") List executors, - @JsonProperty("hasAge") boolean hasAge, - @JsonProperty("hasDegree") boolean hasDegree) { + @JsonProperty("executors") List executors) { this.id = id; this.title = title; this.status = status; @@ -65,8 +61,6 @@ public class ProjectDto { this.applicationFileName = null; this.executorIds = executorIds; this.executors = executors; - this.hasAge = hasAge; - this.hasDegree = hasDegree; } @@ -172,22 +166,6 @@ public class ProjectDto { this.executors = executors; } - public boolean isHasAge() { - return hasAge; - } - - public void setHasAge(boolean hasAge) { - this.hasAge = hasAge; - } - - public boolean isHasDegree() { - return hasDegree; - } - - public void setHasDegree(boolean hasDegree) { - this.hasDegree = hasDegree; - } - public String getExecutorsString() { return StringUtils.abbreviate(executors .stream() diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java index ab2fa91..fe8813c 100644 --- a/src/main/java/ru/ulstu/project/service/ProjectService.java +++ b/src/main/java/ru/ulstu/project/service/ProjectService.java @@ -110,8 +110,8 @@ public class ProjectService { } public void removeDeadline(ProjectDto projectDto, Integer deadlineId) { - if (projectDto.getDeadlines().get(deadlineId).getId() != null) { - projectDto.getRemovedDeadlineIds().add(projectDto.getDeadlines().get(deadlineId).getId()); + if (deadlineId != null) { + projectDto.getRemovedDeadlineIds().add(deadlineId); } projectDto.getDeadlines().remove((int) deadlineId); } @@ -121,8 +121,8 @@ public class ProjectService { } public List getProjectExecutors(ProjectDto projectDto) { - List filteredUsers = userService.filterByAgeAndDegree(projectDto.isHasAge(), projectDto.isHasDegree()); - return filteredUsers; + List users = userService.findAll(); + return users; } } diff --git a/src/main/resources/db/changelog-20190528_000001-schema.xml b/src/main/resources/db/changelog-20190528_000002-schema.xml similarity index 87% rename from src/main/resources/db/changelog-20190528_000001-schema.xml rename to src/main/resources/db/changelog-20190528_000002-schema.xml index 0605b48..7df707c 100644 --- a/src/main/resources/db/changelog-20190528_000001-schema.xml +++ b/src/main/resources/db/changelog-20190528_000002-schema.xml @@ -2,15 +2,15 @@ - + - + - diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index fbc1ec3..c8a6e63 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -48,5 +48,5 @@ - + \ No newline at end of file diff --git a/src/main/resources/templates/projects/project.html b/src/main/resources/templates/projects/project.html index 304fed0..2c4a67b 100644 --- a/src/main/resources/templates/projects/project.html +++ b/src/main/resources/templates/projects/project.html @@ -92,11 +92,11 @@
-
From 8ffafd669328c16d759e37d91fb04cfe32cb07ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Tue, 28 May 2019 16:46:12 +0300 Subject: [PATCH 33/37] #98 deadline imports edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 97b6441..d9f2373 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -6,7 +6,11 @@ import org.springframework.format.annotation.DateTimeFormat; import ru.ulstu.core.model.BaseEntity; import ru.ulstu.user.model.User; -import javax.persistence.*; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; import java.util.Date; import java.util.List; import java.util.Objects; @@ -20,7 +24,7 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; - @OneToMany(targetEntity=User.class, fetch=FetchType.EAGER) + @OneToMany(targetEntity=User.class, fetch= FetchType.EAGER) private List executors; private Boolean done; From 77ce908d584caf5d4346c0929b22744037319c34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B0=D1=81=D0=B8=D0=BD=20=D0=90=D0=BD=D1=82=D0=BE?= =?UTF-8?q?=D0=BD?= Date: Tue, 28 May 2019 16:55:08 +0300 Subject: [PATCH 34/37] #98 deadline edited --- src/main/java/ru/ulstu/deadline/model/Deadline.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index d9f2373..17287a8 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -24,7 +24,7 @@ public class Deadline extends BaseEntity { @DateTimeFormat(pattern = "yyyy-MM-dd") private Date date; - @OneToMany(targetEntity=User.class, fetch= FetchType.EAGER) + @OneToMany(targetEntity = User.class, fetch = FetchType.EAGER) private List executors; private Boolean done; From b4b7b9087e024617a83e29fb6d62644bd6c4b2fc Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Fri, 31 May 2019 08:12:57 +0400 Subject: [PATCH 35/37] fix npe --- src/main/java/ru/ulstu/grant/service/GrantService.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 86f8f1b..3243ace 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -232,10 +232,8 @@ public class GrantService extends BaseService { private boolean checkSameDeadline(GrantDto grantDto, Integer id) { Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас - if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой - return true; - } - return false; + Date foundGrantDate = deadlineService.findByGrantIdAndDate(id, date); + return foundGrantDate != null && foundGrantDate.compareTo(date) == 0; } public List getGrantAuthors(GrantDto grantDto) { From d2ce6d604e4ef228a28be0fbe2ac865f0061bcda Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Fri, 31 May 2019 08:46:21 +0400 Subject: [PATCH 36/37] fix merging collection --- .../java/ru/ulstu/timeline/service/EventService.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/java/ru/ulstu/timeline/service/EventService.java b/src/main/java/ru/ulstu/timeline/service/EventService.java index 8c68291..f9b88f3 100644 --- a/src/main/java/ru/ulstu/timeline/service/EventService.java +++ b/src/main/java/ru/ulstu/timeline/service/EventService.java @@ -105,7 +105,7 @@ public class EventService { public void createFromPaper(Paper newPaper) { List timelines = timelineService.findAll(); Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); - + timeline.getEvents().removeAll(newPaper.getEvents()); for (Deadline deadline : newPaper.getDeadlines() .stream() .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) @@ -119,16 +119,13 @@ public class EventService { newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' cтатьи '" + newPaper.getTitle() + "'"); newEvent.setRecipients(new ArrayList(newPaper.getAuthors())); newEvent.setPaper(newPaper); - eventRepository.save(newEvent); - - timeline.getEvents().add(newEvent); - timelineService.save(timeline); + timeline.getEvents().add(eventRepository.save(newEvent)); } + timelineService.save(timeline); } public void updatePaperDeadlines(Paper paper) { eventRepository.delete(eventRepository.findAllByPaper(paper)); - createFromPaper(paper); } From a878f8c22ca04636449f0d33feb99354cd213540 Mon Sep 17 00:00:00 2001 From: Anton Romanov Date: Fri, 31 May 2019 09:06:21 +0400 Subject: [PATCH 37/37] fix remove older events --- .../ru/ulstu/timeline/service/EventService.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/ru/ulstu/timeline/service/EventService.java b/src/main/java/ru/ulstu/timeline/service/EventService.java index f9b88f3..328014a 100644 --- a/src/main/java/ru/ulstu/timeline/service/EventService.java +++ b/src/main/java/ru/ulstu/timeline/service/EventService.java @@ -17,6 +17,8 @@ import ru.ulstu.user.model.UserDto; import ru.ulstu.user.service.UserService; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -103,9 +105,13 @@ public class EventService { } public void createFromPaper(Paper newPaper) { + createFromPaper(newPaper, Collections.emptyList()); + } + + public void createFromPaper(Paper newPaper, List events) { List timelines = timelineService.findAll(); Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); - timeline.getEvents().removeAll(newPaper.getEvents()); + timeline.getEvents().removeAll(events); for (Deadline deadline : newPaper.getDeadlines() .stream() .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) @@ -125,8 +131,9 @@ public class EventService { } public void updatePaperDeadlines(Paper paper) { - eventRepository.delete(eventRepository.findAllByPaper(paper)); - createFromPaper(paper); + List foundEvents = eventRepository.findAllByPaper(paper); + eventRepository.delete(foundEvents); + createFromPaper(paper, foundEvents); } public List findByCurrentDate() {