diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index c3ff3e3..b064dce 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,30 +1,28 @@
-image: ubuntu:18.04
-
-cache:
- key: "$CI_PROJECT_ID"
- paths:
- - .gradle/
+image: romanov73/is:ng-tracker-container-11
variables:
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
before_script:
- - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
- - apt-get install openjdk-8-jdk git -y
- - eval $(ssh-agent -s)
- - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- - mkdir -p ~/.ssh
- - chmod 700 ~/.ssh
+ - service postgresql stop
+ - service postgresql start
+ - eval $(ssh-agent -s)
+ - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
+ - mkdir -p ~/.ssh
+ - chmod 700 ~/.ssh
+ - git log --pretty="%cn;%cd;%s" > src/main/resources/commits.log
build:
stage: build
script: ./gradlew assemble
- cache:
- key: "$CI_PROJECT_ID"
- policy: push
- paths:
- - build
- - .gradle
+
+checkRun:
+ stage: test
+ script: ./gradlew bootRun -Dng-tracker.check-run=true
+
+checkStyle:
+ stage: test
+ script: ./gradlew check -x test
deploy:
stage: deploy
@@ -32,9 +30,6 @@ deploy:
- sh deploy/gdccloud/deploy.sh
only:
- dev
- cache:
- key: "$CI_PROJECT_ID"
- policy: pull
- paths:
- - build
- - .gradle
\ No newline at end of file
+ environment:
+ name: staging
+ url: http://193.110.3.124:8080
diff --git a/.gitlab/issue_templates/feature.md b/.gitlab/issue_templates/feature.md
new file mode 100644
index 0000000..c9e1757
--- /dev/null
+++ b/.gitlab/issue_templates/feature.md
@@ -0,0 +1,46 @@
+## Краткое описание задачи
+
+Что требуется сделать
+
+
+## `Опционально` Список верстаемых страниц
+
+Будут затронуты страницы:
+* page1.html
+* page2.html
+* page3.html
+
+## `Опционально` Список затрагиваемых модулей
+
+При реализации задачи потребуется также реализовать методы контроллера
+
+
+## `Опционально` Список реализуемых функций
+
+После выполнения задачи станет доступным:
+* просмотр `entity_name`
+* редактирование `entity_name`
+* валидация `entity_name`
+
+## `Опционально` Сценарии работы
+
+Сценарий просмотра:
+1. Зайти на главную страницу приложения
+2. Перейти в раздел `section_name`
+3. Перейти к списку `entity_name`
+4. Выбрать нужную `entity_name` и нажать на нее
+
+Сценарий редактирования:
+1. Зайти на главную страницу приложения
+2. Перейти в раздел `section_name`
+3. Перейти к списку `entity_name`
+4. Выбрать нужную `entity_name` и нажать на нее
+5. Внести нужные правки в поля и сохранить
+
+## Описание конечного результата, дающего возможность проверки выполнения задачи: компоненты проекта, сценарии работы
+
+* Сверстаны страницы page1.hml, page2.hml, page3.hml
+* Реализован контроллер для обслуживания страниц
+* Сохранение в БД еще не реализовано
+* Валидация происходит по полям `field1, field2`
+* Сценарий просмотра проверяется при ручном внечении записей в БД
diff --git a/README.md b/README.md
index ca4db83..f4f6ddd 100644
--- a/README.md
+++ b/README.md
@@ -7,6 +7,7 @@
2. Создать новую функцию автоматизированной системы управления задчами - интеллектуальную постановку задач исполнителям.
3. Получить платформу для обкатки научных проектов магистрантов по созданию интеллектуальны систем.
4. Получить проект для обучения бакалавров современым технологиям разработки.
+5. Создать систему хранения и трансляции опыта между участниками научной группы.
[Демо версия доступна здесь](http://193.110.3.124:8080)
diff --git a/build.gradle b/build.gradle
index 4e0e9cb..0edeb92 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,6 +1,6 @@
buildscript {
ext {
- versionSpringBoot = '1.5.10.RELEASE'
+ versionSpringBoot = '2.1.3.RELEASE'
}
repositories {
@@ -30,6 +30,10 @@ bootRun.dependsOn checkstyleMain
sourceCompatibility = 1.8
targetCompatibility = 1.8
+bootRun {
+ systemProperties = System.properties
+}
+
checkstyle {
project.ext.checkstyleVersion = '8.8'
@@ -101,18 +105,16 @@ dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jetty'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
- compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4'
+ compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect'
+ compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity5'
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5'
- compile group: 'postgresql', name: 'postgresql', version: '9.1-901.jdbc4'
+ compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
- compile group: 'org.liquibase', name: 'liquibase-core', version: '3.5.3'
+ compile group: 'org.liquibase', name: 'liquibase-core', version: '3.6.3'
compile group: 'com.mattbertolini', name: 'liquibase-slf4j', version: '2.0.0'
- compile group: 'org.apache.poi', name: 'poi', version: '3.9'
- compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.9'
-
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
compile group: 'org.webjars', name: 'bootstrap', version: '4.1.0'
@@ -121,8 +123,10 @@ dependencies {
compile group: 'org.webjars.npm', name: 'jquery.easing', version: '1.4.1'
compile group: 'org.webjars', name: 'font-awesome', version: '4.7.0'
- compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.5.0'
- compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.5.0'
+ compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0'
+ 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'
+
}
\ No newline at end of file
diff --git a/checkstyle.xml b/checkstyle.xml
index 5877ec9..828cdaa 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -100,7 +100,7 @@
-
+
+
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 568c50b..663c448 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
diff --git a/src/main/java/ru/ulstu/NgTrackerApplication.java b/src/main/java/ru/ulstu/NgTrackerApplication.java
index 5e6ee4f..fbe3a2f 100644
--- a/src/main/java/ru/ulstu/NgTrackerApplication.java
+++ b/src/main/java/ru/ulstu/NgTrackerApplication.java
@@ -2,13 +2,30 @@ package ru.ulstu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.repository.JpaDetachableRepositoryImpl;
@SpringBootApplication
@EnableJpaRepositories(repositoryBaseClass = JpaDetachableRepositoryImpl.class)
public class NgTrackerApplication {
+ private final ApplicationProperties applicationProperties;
+
+ public NgTrackerApplication(ApplicationProperties applicationProperties) {
+ this.applicationProperties = applicationProperties;
+ }
+
public static void main(String[] args) {
SpringApplication.run(NgTrackerApplication.class, args);
}
+
+ @EventListener(ApplicationReadyEvent.class)
+ public void doSomethingAfterStartup() {
+ System.out.println("hello world, I have just started up");
+ if (applicationProperties.isCheckRun()) {
+ System.exit(0);
+ }
+ }
}
diff --git a/src/main/java/ru/ulstu/conference/controller/ConferenceController.java b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java
new file mode 100644
index 0000000..a416345
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/controller/ConferenceController.java
@@ -0,0 +1,156 @@
+package ru.ulstu.conference.controller;
+
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.ModelMap;
+import org.springframework.validation.Errors;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import ru.ulstu.conference.model.ConferenceDto;
+import ru.ulstu.conference.model.ConferenceFilterDto;
+import ru.ulstu.conference.model.ConferenceUser;
+import ru.ulstu.conference.service.ConferenceService;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.user.model.User;
+import springfox.documentation.annotations.ApiIgnore;
+
+import javax.validation.Valid;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.springframework.util.StringUtils.isEmpty;
+import static ru.ulstu.core.controller.Navigation.CONFERENCES_PAGE;
+import static ru.ulstu.core.controller.Navigation.CONFERENCE_PAGE;
+import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
+
+
+@Controller()
+@RequestMapping(value = "/conferences")
+@ApiIgnore
+public class ConferenceController {
+
+ private final ConferenceService conferenceService;
+
+ public ConferenceController(ConferenceService conferenceService) {
+ this.conferenceService = conferenceService;
+ }
+
+ @GetMapping("/conferences")
+ public void getConferences(ModelMap modelMap) {
+ modelMap.put("filteredConferences", new ConferenceFilterDto(conferenceService.findAllDto()));
+ }
+
+ @PostMapping("/conferences")
+ public void filterConferences(@Valid ConferenceFilterDto conferenceFilterDto, ModelMap modelMap) {
+ modelMap.put("filteredConferences", new ConferenceFilterDto(conferenceService.filter(conferenceFilterDto),
+ conferenceFilterDto.getFilterUserId(),
+ conferenceFilterDto.getYear()));
+ }
+
+ @GetMapping("/dashboard")
+ public void getDashboard(ModelMap modelMap) {
+ modelMap.put("conferences", conferenceService.findAllActiveDto());
+ }
+
+ @GetMapping("/conference")
+ public void getConference(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
+ if (id != null && id > 0) {
+ modelMap.put("conferenceDto", conferenceService.getExistConferenceById(id));
+ } else {
+ modelMap.put("conferenceDto", conferenceService.getNewConference());
+ }
+ }
+
+ @PostMapping(value = "/conference", params = "save")
+ public String save(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException {
+ filterEmptyDeadlines(conferenceDto);
+ if (errors.hasErrors()) {
+ return CONFERENCE_PAGE;
+ }
+ conferenceService.save(conferenceDto);
+ return String.format(REDIRECT_TO, CONFERENCES_PAGE);
+
+ }
+
+ @GetMapping("/delete/{conference-id}")
+ public String delete(@PathVariable("conference-id") Integer conferenceId) throws IOException {
+ conferenceService.delete(conferenceId);
+ return String.format(REDIRECT_TO, CONFERENCES_PAGE);
+ }
+
+ @PostMapping(value = "/conference", params = "addDeadline")
+ public String addDeadline(@Valid ConferenceDto conferenceDto, Errors errors) {
+ filterEmptyDeadlines(conferenceDto);
+ if (errors.hasErrors()) {
+ return CONFERENCE_PAGE;
+ }
+ conferenceDto.getDeadlines().add(new Deadline());
+ return CONFERENCE_PAGE;
+ }
+
+ @PostMapping(value = "/conference", params = "removeDeadline")
+ public String removeDeadline(@Valid ConferenceDto conferenceDto, Errors errors,
+ @RequestParam(value = "removeDeadline") Integer deadlineIndex) throws IOException {
+ if (errors.hasErrors()) {
+ return CONFERENCE_PAGE;
+ }
+ conferenceService.removeDeadline(conferenceDto, deadlineIndex);
+ return CONFERENCE_PAGE;
+ }
+
+ @PostMapping(value = "/conference", params = "removePaper")
+ public String removePaper(@Valid ConferenceDto conferenceDto, Errors errors,
+ @RequestParam(value = "removePaper") Integer paperIndex) throws IOException {
+ if (errors.hasErrors()) {
+ return CONFERENCE_PAGE;
+ }
+ conferenceService.removePaper(conferenceDto, paperIndex);
+ return CONFERENCE_PAGE;
+ }
+
+ @PostMapping(value = "/conference", params = "takePart")
+ public String takePart(@Valid ConferenceDto conferenceDto, Errors errors) throws IOException {
+ if (errors.hasErrors()) {
+ return CONFERENCE_PAGE;
+ }
+ conferenceService.takePart(conferenceDto);
+ return CONFERENCE_PAGE;
+ }
+
+ @ModelAttribute("allParticipation")
+ public List getAllParticipation() {
+ return conferenceService.getAllParticipations();
+ }
+
+ @ModelAttribute("allDeposit")
+ public List getAllDeposit() {
+ return conferenceService.getAllDeposit();
+ }
+
+ @ModelAttribute("allUsers")
+ public List getAllUsers() {
+ return conferenceService.getAllUsers();
+ }
+
+ @ModelAttribute("allYears")
+ public List getAllYears() {
+ List years = new ArrayList<>();
+ for (int i = Calendar.getInstance().get(Calendar.YEAR); i > 2010; i--) {
+ years.add(i);
+ }
+ return years;
+ }
+
+ private void filterEmptyDeadlines(ConferenceDto conferenceDto) {
+ conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream()
+ .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
+ .collect(Collectors.toList()));
+ }
+}
diff --git a/src/main/java/ru/ulstu/conference/model/Conference.java b/src/main/java/ru/ulstu/conference/model/Conference.java
new file mode 100644
index 0000000..9831a0e
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/model/Conference.java
@@ -0,0 +1,138 @@
+package ru.ulstu.conference.model;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+import org.springframework.format.annotation.DateTimeFormat;
+import ru.ulstu.core.model.BaseEntity;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.paper.model.Paper;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.validation.constraints.NotBlank;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+@Entity
+@Table(name = "conference")
+public class Conference extends BaseEntity {
+
+ @NotBlank
+ private String title;
+
+ private String description;
+
+ private String url;
+
+ private int ping;
+
+ @Column(name = "begin_date")
+ @Temporal(TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
+ private Date beginDate;
+
+ @Column(name = "end_date")
+ @Temporal(TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
+ private Date endDate;
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "conference_id", unique = true)
+ @Fetch(FetchMode.SUBSELECT)
+ @OrderBy("date")
+ private List deadlines = new ArrayList<>();
+
+ @ManyToMany(fetch = FetchType.EAGER)
+ @JoinTable(name = "paper_conference",
+ joinColumns = {@JoinColumn(name = "conference_id")},
+ inverseJoinColumns = {@JoinColumn(name = "paper_id")})
+ private List papers = new ArrayList<>();
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "conference_id", unique = true)
+ @Fetch(FetchMode.SUBSELECT)
+ private List users = new ArrayList<>();
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public int getPing() {
+ return ping;
+ }
+
+ public void setPing(int ping) {
+ this.ping = ping;
+ }
+
+ public Date getBeginDate() {
+ return beginDate;
+ }
+
+ public void setBeginDate(Date beginDate) {
+ this.beginDate = beginDate;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(Date endDate) {
+ this.endDate = endDate;
+ }
+
+ public List getDeadlines() {
+ return deadlines;
+ }
+
+ public void setDeadlines(List deadlines) {
+ this.deadlines = deadlines;
+ }
+
+ public List getPapers() {
+ return papers;
+ }
+
+ public void setPapers(List papers) {
+ this.papers = papers;
+ }
+
+ public List getUsers() {
+ return users;
+ }
+
+ public void setUsers(List users) {
+ this.users = users;
+ }
+}
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
new file mode 100644
index 0000000..6264f62
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
@@ -0,0 +1,222 @@
+package ru.ulstu.conference.model;
+
+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.deadline.model.Deadline;
+import ru.ulstu.paper.model.Paper;
+
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.Size;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import static ru.ulstu.core.util.StreamApiUtils.convert;
+
+public class ConferenceDto {
+
+ private final static String BEGIN_DATE = "Начало: ";
+ private final static String END_DATE = "Конец: ";
+
+ private Integer id;
+ @NotEmpty
+ @Size(min = 2, max = 400)
+ private String title;
+ @Size(max = 500)
+ private String description = "";
+ @Size(max = 255)
+ private String url = "";
+ private int ping = 0;
+ @Temporal(TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
+ private Date beginDate = new Date();
+ @Temporal(TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
+ private Date endDate = new Date();
+ private List deadlines = new ArrayList<>();
+ private List removedDeadlineIds = new ArrayList<>();
+ private List userIds = new ArrayList<>();
+ private List paperIds = new ArrayList<>();
+ private List papers = new ArrayList<>();
+ private List notSelectedPapers = new ArrayList<>();
+ private List users = new ArrayList<>();
+ private boolean disabledTakePart = false;
+
+ public ConferenceDto() {
+ }
+
+ @JsonCreator
+ public ConferenceDto(@JsonProperty("id") Integer id,
+ @JsonProperty("title") String title,
+ @JsonProperty("description") String description,
+ @JsonProperty("url") String url,
+ @JsonProperty("ping") Integer ping,
+ @JsonProperty("beginDate") Date beginDate,
+ @JsonProperty("endDate") Date endDate,
+ @JsonProperty("deadlines") List deadlines,
+ @JsonProperty("userIds") List userIds,
+ @JsonProperty("paperIds") List paperIds,
+ @JsonProperty("users") List users,
+ @JsonProperty("papers") List papers,
+ @JsonProperty("notSelectedPapers") List notSelectedPapers,
+ @JsonProperty("notSelectedPapers") Boolean disabledTakePart) {
+ this.id = id;
+ this.title = title;
+ this.description = description;
+ this.url = url;
+ this.ping = ping;
+ this.beginDate = beginDate;
+ this.endDate = endDate;
+ this.deadlines = deadlines;
+ this.userIds = userIds;
+ this.paperIds = paperIds;
+ this.users = users;
+ this.papers = papers;
+ this.notSelectedPapers = notSelectedPapers;
+ this.disabledTakePart = disabledTakePart;
+ }
+
+ public ConferenceDto(Conference conference) {
+ this.id = conference.getId();
+ this.title = conference.getTitle();
+ this.description = conference.getDescription();
+ this.url = conference.getUrl();
+ this.ping = conference.getPing();
+ this.beginDate = conference.getBeginDate();
+ this.endDate = conference.getEndDate();
+ this.deadlines = conference.getDeadlines();
+ this.userIds = convert(conference.getUsers(), BaseEntity::getId);
+ this.paperIds = convert(conference.getPapers(), BaseEntity::getId);
+ this.users = conference.getUsers();
+ this.papers = conference.getPapers();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public int getPing() {
+ return ping;
+ }
+
+ public void setPing(int ping) {
+ this.ping = ping;
+ }
+
+ public Date getBeginDate() {
+ return beginDate;
+ }
+
+ public void setBeginDate(Date beginDate) {
+ this.beginDate = beginDate;
+ }
+
+ public Date getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(Date endDate) {
+ this.endDate = endDate;
+ }
+
+ public List getDeadlines() {
+ return deadlines;
+ }
+
+ public void setDeadlines(List deadlines) {
+ this.deadlines = deadlines;
+ }
+
+ public List getUserIds() {
+ return userIds;
+ }
+
+ public void setUserIds(List userIds) {
+ this.userIds = userIds;
+ }
+
+ public List getPaperIds() {
+ return paperIds;
+ }
+
+ public void setPaperIds(List paperIds) {
+ this.paperIds = paperIds;
+ }
+
+ public List getPapers() {
+ return papers;
+ }
+
+ public void setPapers(List papers) {
+ this.papers = papers;
+ }
+
+ public List getUsers() {
+ return users;
+ }
+
+ public void setUsers(List users) {
+ this.users = users;
+ }
+
+ public boolean isDisabledTakePart() {
+ return disabledTakePart;
+ }
+
+ public void setDisabledTakePart(boolean disabledTakePart) {
+ this.disabledTakePart = disabledTakePart;
+ }
+
+ public List getRemovedDeadlineIds() {
+ return removedDeadlineIds;
+ }
+
+ public void setRemovedDeadlineIds(List removedDeadlineIds) {
+ this.removedDeadlineIds = removedDeadlineIds;
+ }
+
+ public List getNotSelectedPapers() {
+ return notSelectedPapers;
+ }
+
+ public void setNotSelectedPapers(List notSelectedPapers) {
+ this.notSelectedPapers = notSelectedPapers;
+ }
+
+ public String getDatesString() {
+ return BEGIN_DATE + beginDate.toString().split(" ")[0] + " " + END_DATE + endDate.toString().split(" ")[0];
+ }
+
+}
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java
new file mode 100644
index 0000000..8503b40
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceFilterDto.java
@@ -0,0 +1,47 @@
+package ru.ulstu.conference.model;
+
+import java.util.List;
+
+public class ConferenceFilterDto {
+
+ private List conferences;
+ private Integer filterUserId;
+ private Integer year;
+
+ public ConferenceFilterDto() {
+ }
+
+ public ConferenceFilterDto(List conferenceDtos, Integer filterUserId, Integer year) {
+ this.conferences = conferenceDtos;
+ this.filterUserId = filterUserId;
+ this.year = year;
+ }
+
+ public ConferenceFilterDto(List conferenceDtos) {
+ this(conferenceDtos, null, null);
+ }
+
+ public List getConferences() {
+ return conferences;
+ }
+
+ public void setConferences(List conferences) {
+ this.conferences = conferences;
+ }
+
+ public Integer getFilterUserId() {
+ return filterUserId;
+ }
+
+ public void setFilterUserId(Integer filterUserId) {
+ this.filterUserId = filterUserId;
+ }
+
+ public Integer getYear() {
+ return year;
+ }
+
+ public void setYear(Integer year) {
+ this.year = year;
+ }
+}
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceUser.java b/src/main/java/ru/ulstu/conference/model/ConferenceUser.java
new file mode 100644
index 0000000..63eeb6d
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceUser.java
@@ -0,0 +1,110 @@
+package ru.ulstu.conference.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import ru.ulstu.core.model.BaseEntity;
+import ru.ulstu.user.model.User;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.validation.constraints.NotNull;
+
+@Entity
+@Table(name = "users_conference")
+public class ConferenceUser extends BaseEntity {
+
+ public enum Participation {
+ INTRAMURAL("Очная"),
+ EXTRAMURAL("Заочная");
+
+ private String participationName;
+
+ Participation(String name) {
+ this.participationName = name;
+ }
+
+ public String getParticipation() {
+ return participationName;
+ }
+ }
+
+ public enum Deposit {
+ ARTICLE("Статья"),
+ REPORT("Доклад"),
+ PRESENTATION("Презентация");
+
+ private String depositName;
+
+ Deposit(String name) {
+ this.depositName = name;
+ }
+
+ public String getDeposit() {
+ return depositName;
+ }
+ }
+
+
+ @NotNull
+ @Column(name = "participation", nullable = false)
+ @Enumerated(value = EnumType.STRING)
+ private Participation participation = Participation.INTRAMURAL;
+
+ @NotNull
+ @Column(name = "deposit", nullable = false)
+ @Enumerated(value = EnumType.STRING)
+ private Deposit deposit = Deposit.ARTICLE;
+
+ @ManyToOne(optional = false)
+ @JoinColumn(name = "users_id")
+ private User user;
+
+ public ConferenceUser() {
+ }
+
+ public ConferenceUser(User user) {
+ this.user = user;
+ }
+
+ @JsonCreator
+ public ConferenceUser(@JsonProperty("id") Integer id,
+ @JsonProperty("deposit") Participation participation,
+ @JsonProperty("deposit") Deposit deposit,
+ @JsonProperty("user") User user) {
+ this.setId(id);
+ this.participation = participation;
+ this.deposit = deposit;
+ this.user = user;
+ }
+
+
+ public Participation getParticipation() {
+ return participation;
+ }
+
+ public void setParticipation(Participation participation) {
+ this.participation = participation;
+ }
+
+ public Deposit getDeposit() {
+ return deposit;
+ }
+
+ public void setDeposit(Deposit deposit) {
+ this.deposit = deposit;
+ }
+
+ public User getUser() {
+ return user;
+ }
+
+ public void setUser(User user) {
+ this.user = user;
+ }
+
+}
diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java
new file mode 100644
index 0000000..cb8a488
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/repository/ConferenceRepository.java
@@ -0,0 +1,19 @@
+package ru.ulstu.conference.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.conference.model.Conference;
+import ru.ulstu.user.model.User;
+
+import java.util.Date;
+import java.util.List;
+
+public interface ConferenceRepository extends JpaRepository {
+ @Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " +
+ "AND (YEAR(c.beginDate) = :year OR :year IS NULL) ORDER BY begin_date DESC")
+ List findByUserAndYear(@Param("user") User user, @Param("year") Integer year);
+
+ @Query("SELECT c FROM Conference c WHERE c.beginDate > :date")
+ List findAllActive(@Param("date") Date date);
+}
diff --git a/src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java b/src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java
new file mode 100644
index 0000000..5e654d5
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/repository/ConferenceUserRepository.java
@@ -0,0 +1,7 @@
+package ru.ulstu.conference.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import ru.ulstu.conference.model.ConferenceUser;
+
+public interface ConferenceUserRepository extends JpaRepository {
+}
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java b/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java
new file mode 100644
index 0000000..ff9f69a
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceNotificationService.java
@@ -0,0 +1,7 @@
+package ru.ulstu.conference.service;
+
+import org.springframework.stereotype.Service;
+
+@Service
+public class ConferenceNotificationService {
+}
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
new file mode 100644
index 0000000..dfd0f8a
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -0,0 +1,176 @@
+package ru.ulstu.conference.service;
+
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.data.domain.Sort;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import ru.ulstu.conference.model.Conference;
+import ru.ulstu.conference.model.ConferenceDto;
+import ru.ulstu.conference.model.ConferenceFilterDto;
+import ru.ulstu.conference.model.ConferenceUser;
+import ru.ulstu.conference.repository.ConferenceRepository;
+import ru.ulstu.deadline.service.DeadlineService;
+import ru.ulstu.paper.model.Paper;
+import ru.ulstu.paper.service.PaperService;
+import ru.ulstu.user.model.User;
+import ru.ulstu.user.service.UserService;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import static org.springframework.util.ObjectUtils.isEmpty;
+import static ru.ulstu.core.util.StreamApiUtils.convert;
+
+@Service
+public class ConferenceService {
+ private final static int MAX_DISPLAY_SIZE = 40;
+
+ private final ConferenceRepository conferenceRepository;
+ private final ConferenceUserService conferenceUserService;
+ private final DeadlineService deadlineService;
+ private final PaperService paperService;
+ private final UserService userService;
+
+ public ConferenceService(ConferenceRepository conferenceRepository,
+ ConferenceUserService conferenceUserService,
+ DeadlineService deadlineService,
+ PaperService paperService,
+ UserService userService) {
+ this.conferenceRepository = conferenceRepository;
+ this.conferenceUserService = conferenceUserService;
+ this.deadlineService = deadlineService;
+ this.paperService = paperService;
+ this.userService = userService;
+ }
+
+ public ConferenceDto getExistConferenceById(Integer id) {
+ ConferenceDto conferenceDto = findOneDto(id);
+ conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds()));
+ conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers()));
+ return conferenceDto;
+ }
+
+ public ConferenceDto getNewConference() {
+ ConferenceDto conferenceDto = new ConferenceDto();
+ conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList()));
+ return conferenceDto;
+ }
+
+
+ public List findAll() {
+ return conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"));
+ }
+
+ public List findAllDto() {
+ List conferences = convert(findAll(), ConferenceDto::new);
+ conferences.forEach(conferenceDto -> conferenceDto.setTitle(StringUtils.abbreviate(conferenceDto.getTitle(), MAX_DISPLAY_SIZE)));
+ return conferences;
+ }
+
+ public ConferenceDto findOneDto(Integer id) {
+ return new ConferenceDto(conferenceRepository.getOne(id));
+ }
+
+ public void save(ConferenceDto conferenceDto) throws IOException {
+ if (isEmpty(conferenceDto.getId())) {
+ create(conferenceDto);
+ } else {
+ update(conferenceDto);
+ }
+ }
+
+ @Transactional
+ public Integer create(ConferenceDto conferenceDto) throws IOException {
+ Conference newConference = copyFromDto(new Conference(), conferenceDto);
+ newConference = conferenceRepository.save(newConference);
+ return newConference.getId();
+ }
+
+ @Transactional
+ public Integer update(ConferenceDto conferenceDto) throws IOException {
+ Conference conference = conferenceRepository.getOne(conferenceDto.getId());
+ conferenceRepository.save(copyFromDto(conference, conferenceDto));
+ conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove);
+ return conference.getId();
+ }
+
+ @Transactional
+ public void delete(Integer conferenceId) {
+ if (conferenceRepository.existsById(conferenceId)) {
+ conferenceRepository.deleteById(conferenceId);
+ }
+ }
+
+ public void removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException {
+ if (conferenceDto.getDeadlines().get(deadlineIndex).getId() != null) {
+ conferenceDto.getRemovedDeadlineIds().add(conferenceDto.getDeadlines().get(deadlineIndex).getId());
+ }
+ conferenceDto.getDeadlines().remove((int) deadlineIndex);
+ }
+
+ public void removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException {
+ Paper removedPaper = conferenceDto.getPapers().remove((int) paperIndex);
+ conferenceDto.getNotSelectedPapers().add(removedPaper);
+ }
+
+ public void takePart(ConferenceDto conferenceDto) throws IOException {
+ conferenceDto.getUsers().add(new ConferenceUser(userService.getCurrentUser()));
+ conferenceDto.setDisabledTakePart(true);
+ }
+
+ public List getNotSelectPapers(List paperIds) {
+ return paperService.findAllNotSelect(paperIds);
+ }
+
+ public List getAllUsers() {
+ return userService.findAll();
+ }
+
+ public List getAllParticipations() {
+ return Arrays.asList(ConferenceUser.Participation.values());
+ }
+
+ public List getAllDeposit() {
+ return Arrays.asList(ConferenceUser.Deposit.values());
+ }
+
+ private Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
+ conference.setTitle(conferenceDto.getTitle());
+ conference.setDescription(conferenceDto.getDescription());
+ conference.setUrl(conferenceDto.getUrl());
+ conference.setPing(0);
+ conference.setBeginDate(conferenceDto.getBeginDate());
+ conference.setEndDate(conferenceDto.getEndDate());
+ conference.setPapers(conferenceDto.getPapers());
+ conference.setDeadlines(deadlineService.saveOrCreate(conferenceDto.getDeadlines()));
+ conference.setUsers(conferenceUserService.saveOrCreate(conferenceDto.getUsers()));
+ if (conferenceDto.getPaperIds() != null && !conferenceDto.getPaperIds().isEmpty()) {
+ conferenceDto.getPaperIds().forEach(paperId ->
+ conference.getPapers().add(paperService.findEntityById(paperId)));
+ }
+ return conference;
+ }
+
+
+ public boolean isCurrentUserParticipant(List conferenceUsers) {
+ return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser()));
+ }
+
+ public List filter(ConferenceFilterDto conferenceFilterDto) {
+ return convert(conferenceRepository.findByUserAndYear(
+ conferenceFilterDto.getFilterUserId() == null ? null : userService.findById(conferenceFilterDto.getFilterUserId()),
+ conferenceFilterDto.getYear()), ConferenceDto::new);
+
+ }
+
+ public List findAllActiveDto() {
+ return convert(findAllActive(), ConferenceDto::new);
+ }
+
+ public List findAllActive() {
+ return conferenceRepository.findAllActive(new Date());
+ }
+}
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java
new file mode 100644
index 0000000..269e7df
--- /dev/null
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceUserService.java
@@ -0,0 +1,48 @@
+package ru.ulstu.conference.service;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import ru.ulstu.conference.model.ConferenceUser;
+import ru.ulstu.conference.repository.ConferenceUserRepository;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Service
+public class ConferenceUserService {
+
+ private final ConferenceUserRepository conferenceUserRepository;
+
+ public ConferenceUserService(ConferenceUserRepository conferenceUserRepository) {
+ this.conferenceUserRepository = conferenceUserRepository;
+ }
+
+ public List saveOrCreate(List users) {
+ return users
+ .stream()
+ .map(user -> {
+ return user.getId() != null ? update(user) : create(user);
+ }).collect(Collectors.toList());
+ }
+
+ @Transactional
+ public ConferenceUser update(ConferenceUser user) {
+ ConferenceUser updateUser = conferenceUserRepository.getOne(user.getId());
+ updateUser.setDeposit(user.getDeposit());
+ updateUser.setParticipation(user.getParticipation());
+ conferenceUserRepository.save(updateUser);
+ return updateUser;
+ }
+
+ @Transactional
+ public ConferenceUser create(ConferenceUser user) {
+ ConferenceUser newUser = new ConferenceUser();
+ newUser.setDeposit(user.getDeposit());
+ newUser.setParticipation(user.getParticipation());
+ newUser.setUser(user.getUser());
+ newUser = conferenceUserRepository.save(newUser);
+ return newUser;
+ }
+
+
+}
diff --git a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
index 8615cb2..0b09821 100644
--- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
+++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
@@ -1,22 +1,27 @@
package ru.ulstu.configuration;
-import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
+import javax.validation.constraints.NotBlank;
+
@Component
@ConfigurationProperties(prefix = "ng-tracker")
@Validated
public class ApplicationProperties {
@NotBlank
private String baseUrl;
+
@NotBlank
private String undeadUserLogin;
+
private boolean devMode;
private boolean useHttps;
+ private boolean checkRun;
+
public boolean isUseHttps() {
return useHttps;
}
@@ -48,4 +53,12 @@ public class ApplicationProperties {
public void setDevMode(boolean devMode) {
this.devMode = devMode;
}
+
+ public boolean isCheckRun() {
+ return checkRun;
+ }
+
+ public void setCheckRun(boolean checkRun) {
+ this.checkRun = checkRun;
+ }
}
diff --git a/src/main/java/ru/ulstu/configuration/HttpListenerConfiguration.java b/src/main/java/ru/ulstu/configuration/HttpListenerConfiguration.java
index bcbcab8..514319d 100644
--- a/src/main/java/ru/ulstu/configuration/HttpListenerConfiguration.java
+++ b/src/main/java/ru/ulstu/configuration/HttpListenerConfiguration.java
@@ -2,18 +2,18 @@ package ru.ulstu.configuration;
import org.eclipse.jetty.server.ServerConnector;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
-import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
-import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
-import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer;
+import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer;
+import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
+import org.springframework.boot.web.server.ConfigurableWebServerFactory;
+import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
@Configuration
-public class HttpListenerConfiguration implements EmbeddedServletContainerCustomizer {
+public class HttpListenerConfiguration implements WebServerFactoryCustomizer {
@Value("${server.http.port}")
private int httpPort;
- private void configureJetty(JettyEmbeddedServletContainerFactory jettyFactory) {
+ private void configureJetty(JettyServletWebServerFactory jettyFactory) {
jettyFactory.addServerCustomizers((JettyServerCustomizer) server -> {
ServerConnector serverConnector = new ServerConnector(server);
serverConnector.setPort(httpPort);
@@ -22,9 +22,9 @@ public class HttpListenerConfiguration implements EmbeddedServletContainerCustom
}
@Override
- public void customize(ConfigurableEmbeddedServletContainer container) {
- if (container instanceof JettyEmbeddedServletContainerFactory) {
- configureJetty((JettyEmbeddedServletContainerFactory) container);
+ public void customize(ConfigurableWebServerFactory factory) {
+ if (factory instanceof JettyServletWebServerFactory) {
+ configureJetty((JettyServletWebServerFactory) factory);
}
}
}
diff --git a/src/main/java/ru/ulstu/configuration/MailTemplateConfiguration.java b/src/main/java/ru/ulstu/configuration/MailTemplateConfiguration.java
index addf7ac..31de65c 100644
--- a/src/main/java/ru/ulstu/configuration/MailTemplateConfiguration.java
+++ b/src/main/java/ru/ulstu/configuration/MailTemplateConfiguration.java
@@ -3,8 +3,8 @@ package ru.ulstu.configuration;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
-import org.thymeleaf.spring4.SpringTemplateEngine;
+import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
+import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
@@ -17,7 +17,6 @@ public class MailTemplateConfiguration {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver);
templateEngine.addTemplateResolver(emailTemplateResolver());
- templateEngine.addTemplateResolver(mvcTemplateResolver());
templateEngine.addDialect(new LayoutDialect());
templateEngine.addDialect(sec);
return templateEngine;
@@ -25,22 +24,10 @@ public class MailTemplateConfiguration {
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
- emailTemplateResolver.setPrefix("mail_templates/");
- emailTemplateResolver.setTemplateMode("HTML5");
+ emailTemplateResolver.setPrefix("/mail_templates/");
+ emailTemplateResolver.setTemplateMode("HTML");
emailTemplateResolver.setSuffix(".html");
- emailTemplateResolver.setOrder(1);
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
-
- public ClassLoaderTemplateResolver mvcTemplateResolver() {
- ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
- emailTemplateResolver.setPrefix("templates");
- emailTemplateResolver.setTemplateMode("HTML5");
- emailTemplateResolver.setSuffix(".html");
- emailTemplateResolver.setOrder(2);
- emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
- return emailTemplateResolver;
- }
-
}
diff --git a/src/main/java/ru/ulstu/configuration/MvcConfiguration.java b/src/main/java/ru/ulstu/configuration/MvcConfiguration.java
index 8543847..35e9ad2 100644
--- a/src/main/java/ru/ulstu/configuration/MvcConfiguration.java
+++ b/src/main/java/ru/ulstu/configuration/MvcConfiguration.java
@@ -3,16 +3,18 @@ package ru.ulstu.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
-public class MvcConfiguration extends WebMvcConfigurerAdapter {
+public class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/{articlename:\\w+}");
- //registry.addViewController("/admin/{articlename:\\w+}");
+ registry.addViewController("/admin/{articlename:\\w+}");
registry.addViewController("/papers/{articlename:\\w+}");
registry.addViewController("/grants/{articlename:\\w+}");
+ registry.addViewController("/conferences/{articlename:\\w+}");
+ registry.addViewController("/students/{articlename:\\w+}");
registry.addRedirectViewController("/", "/index");
registry.addRedirectViewController("/default", "/index");
}
diff --git a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java
index da498fa..591fa0c 100644
--- a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java
+++ b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java
@@ -58,7 +58,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.anyRequest()
.permitAll();
http.anonymous()
- .principal("developer")
+ .principal("admin")
.authorities(UserRoleConstants.ADMIN);
} else {
log.debug("Security enabled");
diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java
index 18c25dc..8238797 100644
--- a/src/main/java/ru/ulstu/core/controller/AdviceController.java
+++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java
@@ -1,100 +1,110 @@
-package ru.ulstu.core.controller;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.validation.FieldError;
-import org.springframework.web.bind.MethodArgumentNotValidException;
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.RestController;
-import ru.ulstu.core.error.EntityIdIsNullException;
-import ru.ulstu.core.model.ErrorConstants;
-import ru.ulstu.core.model.response.Response;
-import ru.ulstu.core.model.response.ResponseExtended;
-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 java.util.Set;
-import java.util.stream.Collectors;
-
-@RestController
-@ControllerAdvice
-public class AdviceController {
- private final Logger log = LoggerFactory.getLogger(AdviceController.class);
-
- private Response handleException(ErrorConstants error) {
- log.warn(error.toString());
- return new Response<>(error);
- }
-
- private ResponseExtended handleException(ErrorConstants error, E errorData) {
- log.warn(error.toString());
- return new ResponseExtended<>(error, errorData);
- }
-
- @ExceptionHandler(EntityIdIsNullException.class)
- public Response handleEntityIdIsNullException(Throwable e) {
- return handleException(ErrorConstants.ID_IS_NULL);
- }
-
- @ExceptionHandler(MethodArgumentNotValidException.class)
- public ResponseExtended> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
- final Set errors = e.getBindingResult().getAllErrors().stream()
- .filter(error -> error instanceof FieldError)
- .map(error -> ((FieldError) error).getField())
- .collect(Collectors.toSet());
- return handleException(ErrorConstants.VALIDATION_ERROR, errors);
- }
-
- @ExceptionHandler(UserIdExistsException.class)
- public Response handleUserIdExistsException(Throwable e) {
- return handleException(ErrorConstants.USER_ID_EXISTS);
- }
-
- @ExceptionHandler(UserActivationError.class)
- public ResponseExtended handleUserActivationError(Throwable e) {
- return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
- }
-
- @ExceptionHandler(UserLoginExistsException.class)
- public ResponseExtended handleUserLoginExistsException(Throwable e) {
- return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
- }
-
- @ExceptionHandler(UserEmailExistsException.class)
- public ResponseExtended handleUserEmailExistsException(Throwable e) {
- return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
- }
-
- @ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
- public Response handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
- return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
- }
-
- @ExceptionHandler(UserNotFoundException.class)
- public ResponseExtended handleUserNotFoundException(Throwable e) {
- return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
- }
-
- @ExceptionHandler(UserNotActivatedException.class)
- public Response handleUserNotActivatedException(Throwable e) {
- return handleException(ErrorConstants.USER_NOT_ACTIVATED);
- }
-
- @ExceptionHandler(UserResetKeyError.class)
- public ResponseExtended handleUserResetKeyError(Throwable e) {
- return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
- }
-
- @ExceptionHandler(UserIsUndeadException.class)
- public ResponseExtended handleUserIsUndeadException(Throwable e) {
- return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
- }
-}
+package ru.ulstu.core.controller;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.validation.FieldError;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import ru.ulstu.core.error.EntityIdIsNullException;
+import ru.ulstu.core.model.ErrorConstants;
+import ru.ulstu.core.model.response.Response;
+import ru.ulstu.core.model.response.ResponseExtended;
+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.service.UserService;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@ControllerAdvice
+public class AdviceController {
+ private final Logger log = LoggerFactory.getLogger(AdviceController.class);
+ private final UserService userService;
+
+ public AdviceController(UserService userService) {
+ this.userService = userService;
+ }
+
+ @ModelAttribute("currentUser")
+ public String getCurrentUser() {
+ return userService.getCurrentUser().getUserAbbreviate();
+ }
+
+ private Response handleException(ErrorConstants error) {
+ log.warn(error.toString());
+ return new Response<>(error);
+ }
+
+ private ResponseExtended handleException(ErrorConstants error, E errorData) {
+ log.warn(error.toString());
+ return new ResponseExtended<>(error, errorData);
+ }
+
+ @ExceptionHandler(EntityIdIsNullException.class)
+ public Response handleEntityIdIsNullException(Throwable e) {
+ return handleException(ErrorConstants.ID_IS_NULL);
+ }
+
+ @ExceptionHandler(MethodArgumentNotValidException.class)
+ public ResponseExtended> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
+ final Set errors = e.getBindingResult().getAllErrors().stream()
+ .filter(error -> error instanceof FieldError)
+ .map(error -> ((FieldError) error).getField())
+ .collect(Collectors.toSet());
+ return handleException(ErrorConstants.VALIDATION_ERROR, errors);
+ }
+
+ @ExceptionHandler(UserIdExistsException.class)
+ public Response handleUserIdExistsException(Throwable e) {
+ return handleException(ErrorConstants.USER_ID_EXISTS);
+ }
+
+ @ExceptionHandler(UserActivationError.class)
+ public ResponseExtended handleUserActivationError(Throwable e) {
+ return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
+ }
+
+ @ExceptionHandler(UserLoginExistsException.class)
+ public ResponseExtended handleUserLoginExistsException(Throwable e) {
+ return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
+ }
+
+ @ExceptionHandler(UserEmailExistsException.class)
+ public ResponseExtended handleUserEmailExistsException(Throwable e) {
+ return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
+ }
+
+ @ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
+ public Response handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
+ return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
+ }
+
+ @ExceptionHandler(UserNotFoundException.class)
+ public ResponseExtended handleUserNotFoundException(Throwable e) {
+ return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
+ }
+
+ @ExceptionHandler(UserNotActivatedException.class)
+ public Response handleUserNotActivatedException(Throwable e) {
+ return handleException(ErrorConstants.USER_NOT_ACTIVATED);
+ }
+
+ @ExceptionHandler(UserResetKeyError.class)
+ public ResponseExtended handleUserResetKeyError(Throwable e) {
+ return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
+ }
+
+ @ExceptionHandler(UserIsUndeadException.class)
+ public ResponseExtended handleUserIsUndeadException(Throwable e) {
+ return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
+ }
+}
diff --git a/src/main/java/ru/ulstu/core/controller/Navigation.java b/src/main/java/ru/ulstu/core/controller/Navigation.java
new file mode 100644
index 0000000..caea429
--- /dev/null
+++ b/src/main/java/ru/ulstu/core/controller/Navigation.java
@@ -0,0 +1,19 @@
+package ru.ulstu.core.controller;
+
+import org.springframework.validation.Errors;
+
+public class Navigation {
+ public static final String REDIRECT_TO = "redirect:%s";
+ public static final String GRANTS_PAGE = "/grants/grants";
+ public static final String GRANT_PAGE = "/grants/grant";
+
+ public static final String CONFERENCES_PAGE = "/conferences/conferences";
+ public static final String CONFERENCE_PAGE = "/conferences/conference";
+
+ public static String hasErrors(Errors errors, String page) {
+ if (errors.hasErrors()) {
+ return page;
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/ru/ulstu/core/error/XlsLoadException.java b/src/main/java/ru/ulstu/core/error/XlsLoadException.java
deleted file mode 100644
index 372731f..0000000
--- a/src/main/java/ru/ulstu/core/error/XlsLoadException.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package ru.ulstu.core.error;
-
-public class XlsLoadException extends Exception {
- public XlsLoadException(String s) {
- super(s);
- }
-}
diff --git a/src/main/java/ru/ulstu/core/error/XlsParseException.java b/src/main/java/ru/ulstu/core/error/XlsParseException.java
deleted file mode 100644
index fe8c4b3..0000000
--- a/src/main/java/ru/ulstu/core/error/XlsParseException.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package ru.ulstu.core.error;
-
-public class XlsParseException extends Exception {
- public XlsParseException(String s) {
- super(s);
- }
-}
diff --git a/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java b/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java
index 388e9a1..af3be5c 100644
--- a/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java
+++ b/src/main/java/ru/ulstu/core/jpa/OffsetablePageRequest.java
@@ -6,19 +6,19 @@ import org.springframework.data.domain.Sort;
import java.io.Serializable;
public class OffsetablePageRequest implements Pageable, Serializable {
- private final int offset;
+ private final long offset;
private final int count;
private final Sort sort;
- public OffsetablePageRequest(int offset, int count) {
+ public OffsetablePageRequest(long offset, int count) {
this(offset, count, null);
}
- public OffsetablePageRequest(int offset, int count, Sort.Direction direction, String... properties) {
+ public OffsetablePageRequest(long offset, int count, Sort.Direction direction, String... properties) {
this(offset, count, new Sort(direction, properties));
}
- public OffsetablePageRequest(int offset, int count, Sort sort) {
+ public OffsetablePageRequest(long offset, int count, Sort sort) {
if (offset < 0) {
throw new IllegalArgumentException("Offset value must not be less than zero!");
}
@@ -42,11 +42,11 @@ public class OffsetablePageRequest implements Pageable, Serializable {
@Override
public int getPageNumber() {
- return offset / count;
+ return (int) (offset / count);
}
@Override
- public int getOffset() {
+ public long getOffset() {
return offset;
}
@@ -89,9 +89,9 @@ public class OffsetablePageRequest implements Pageable, Serializable {
@Override
public int hashCode() {
final int prime = 31;
- int result = 1;
+ long result = 1;
result = prime * result + offset;
result = prime * result + count;
- return result;
+ return (int) result;
}
}
diff --git a/src/main/java/ru/ulstu/core/model/BaseEntity.java b/src/main/java/ru/ulstu/core/model/BaseEntity.java
index bd0f1e4..d3dfa76 100644
--- a/src/main/java/ru/ulstu/core/model/BaseEntity.java
+++ b/src/main/java/ru/ulstu/core/model/BaseEntity.java
@@ -1,6 +1,10 @@
package ru.ulstu.core.model;
-import javax.persistence.*;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+import javax.persistence.Version;
import java.io.Serializable;
@MappedSuperclass
diff --git a/src/main/java/ru/ulstu/core/service/TreeService.java b/src/main/java/ru/ulstu/core/service/TreeService.java
deleted file mode 100644
index 1e3d4a0..0000000
--- a/src/main/java/ru/ulstu/core/service/TreeService.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package ru.ulstu.core.service;
-
-import org.springframework.stereotype.Service;
-import ru.ulstu.core.model.TreeDto;
-import ru.ulstu.core.model.TreeEntity;
-
-import java.util.List;
-import java.util.function.Predicate;
-
-@Service
-public class TreeService {
- public TreeDto getTree(String rootName, List rootItems) {
- return addChildNode(new TreeDto(rootName), rootItems, element -> true);
- }
-
- public TreeDto getTree(String rootName, List rootItems, Predicate filterPredicate) {
- return addChildNode(new TreeDto(rootName), rootItems, filterPredicate);
- }
-
- private TreeDto addChildNode(TreeDto currentRoot, List children, Predicate filterPredicate) {
- if (children != null) {
- children.stream()
- .filter(filterPredicate)
- .forEach(item -> {
- TreeDto newNode = new TreeDto(item);
- currentRoot.getChildren().add(addChildNode(newNode, item.getChildren(), filterPredicate));
- });
- }
- return currentRoot;
- }
-}
diff --git a/src/main/java/ru/ulstu/core/service/XlsDocumentBuilder.java b/src/main/java/ru/ulstu/core/service/XlsDocumentBuilder.java
deleted file mode 100644
index d70d86e..0000000
--- a/src/main/java/ru/ulstu/core/service/XlsDocumentBuilder.java
+++ /dev/null
@@ -1,207 +0,0 @@
-package ru.ulstu.core.service;
-
-import org.apache.poi.POIXMLDocument;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.ss.util.CellRangeAddress;
-import org.apache.poi.ss.util.RegionUtil;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import ru.ulstu.core.error.XlsParseException;
-
-import java.io.*;
-
-public class XlsDocumentBuilder {
- private static final int DEFAULT_SHEET_NUM = 0;
- private File documentFile;
- private Workbook workBook;
- private Sheet currentSheet;
-
- /**
- * Constructor for reading and writing data from/to *.[xls|xlsx] document
- *
- * @param file contains existing document for reading or new document to save
- */
- public XlsDocumentBuilder(File file) throws IOException, XlsParseException {
- this.documentFile = file;
- if (file.exists()) {
- workBook = getWorkBook(file);
- currentSheet = workBook.getSheetAt(DEFAULT_SHEET_NUM);
- } else {
- workBook = new XSSFWorkbook();
- currentSheet = workBook.createSheet();
- }
- }
-
- private Workbook getWorkBook(File file) throws XlsParseException, IOException {
- InputStream inputStream = new PushbackInputStream(new FileInputStream(file), 4096);
- if (isXlsx(inputStream)) {
- return new XSSFWorkbook(inputStream);
- } else if (isExcel(inputStream)) {
- return new HSSFWorkbook(inputStream);
- }
- throw new XlsParseException("Wrong document format");
- }
-
- /**
- * Change active sheet to write or read data
- *
- * @param index index of sheet to activate
- */
- public XlsDocumentBuilder setActiveSheet(int index) {
- workBook.setActiveSheet(index);
- currentSheet = workBook.getSheetAt(index);
- return this;
- }
-
- /**
- * Create new sheet in document and set it active
- *
- * @param sheetName
- */
- public XlsDocumentBuilder insertNewSheet(String sheetName) {
- currentSheet = workBook.createSheet(sheetName);
- workBook.setActiveSheet(getSheetCount() - 1);
- return this;
- }
-
- public XlsDocumentBuilder insertNewSheet(String sheetName, int order) {
- insertNewSheet(sheetName);
- workBook.setSheetOrder(sheetName, order);
- return this;
- }
-
- /**
- * Returns number of sheet in document
- *
- * @return sheets count
- */
- public int getSheetCount() {
- return workBook.getNumberOfSheets();
- }
-
- /**
- * Returns number of rows in sheet
- *
- * @return rows count
- */
- public int getRowCount() {
- return currentSheet.getLastRowNum();
- }
-
- /**
- * Returns number of columns in sheet
- *
- * @return columns count
- */
- public int getColumnCount() {
- Row row = currentSheet.getRow(getRowCount());
- if (row == null) {
- return 0;
- }
- return row.getLastCellNum() - 1;
- }
-
- /**
- * Returns converted to string representation of cell value
- *
- * @param rowIndex row index of current sheet
- * @param colIndex column index of current sheet
- * @return string value of cell
- */
- public String getCellAsString(int rowIndex, int colIndex) {
- Cell cell = currentSheet.getRow(rowIndex).getCell(colIndex);
- cell.setCellType(Cell.CELL_TYPE_STRING);
- return cell.getStringCellValue();
- }
-
- /**
- * Sets string cell value
- *
- * @param rowIndex row index of current sheet
- * @param colIndex column index of current sheet
- */
- public XlsDocumentBuilder setCellValue(int rowIndex, int colIndex, String value) {
- if (currentSheet.getRow(rowIndex) == null) {
- currentSheet.createRow(rowIndex);
- }
- if (currentSheet.getRow(rowIndex).getCell(colIndex) == null) {
- currentSheet.getRow(rowIndex).createCell(colIndex);
- }
- Cell cell = currentSheet.getRow(rowIndex).getCell(colIndex);
- cell.setCellValue(value);
- setColumnAutosize(colIndex, colIndex);
- return this;
- }
-
- public XlsDocumentBuilder setCellValue(int rowIndex, int colIndex, int value) {
- return setCellValue(rowIndex, colIndex, String.valueOf(value));
- }
-
- public XlsDocumentBuilder setCellValue(int rowIndex, int colIndex, long value) {
- return setCellValue(rowIndex, colIndex, String.valueOf(value));
- }
-
- /**
- * Save current file
- */
- public XlsDocumentBuilder save() throws IOException {
- OutputStream out = new FileOutputStream(documentFile);
- workBook.write(out);
- return this;
- }
-
- private boolean isExcel(InputStream i) throws IOException {
- return (POIFSFileSystem.hasPOIFSHeader(i) || POIXMLDocument.hasOOXMLHeader(i));
- }
-
- private boolean isXlsx(InputStream i) throws IOException {
- return POIXMLDocument.hasOOXMLHeader(i);
- }
-
- public int getActiveSheetIndex() {
- return workBook.getActiveSheetIndex();
- }
-
- public XlsDocumentBuilder mergeCells(int rowFrom, int rowTo, int colFrom, int colTo) {
- currentSheet.addMergedRegion(new CellRangeAddress(rowFrom, rowTo, colFrom, colTo));
- return this;
- }
-
- public void setRegionBorderWithMedium(int rowFrom, int rowTo, int colFrom, int colTo) {
- for (int row = rowFrom; row < rowTo; row++) {
- for (int col = colFrom; col <= colTo; col++) {
- CellRangeAddress cellRangeAddress = new CellRangeAddress(row, row, col, col);
- RegionUtil.setBorderBottom(CellStyle.BORDER_THIN, cellRangeAddress, currentSheet, workBook);
- RegionUtil.setBorderLeft(CellStyle.BORDER_THIN, cellRangeAddress, currentSheet, workBook);
- RegionUtil.setBorderRight(CellStyle.BORDER_THIN, cellRangeAddress, currentSheet, workBook);
- RegionUtil.setBorderTop(CellStyle.BORDER_THIN, cellRangeAddress, currentSheet, workBook);
- }
- }
- }
-
- public XlsDocumentBuilder setColumnAutosize(int from, int to) {
- for (int col = from; col <= to; col++) {
- currentSheet.autoSizeColumn(col, true);
- }
- return this;
- }
-
- public XlsDocumentBuilder setRowAutosize(int from, int to) {
- CellStyle style = workBook.createCellStyle();
- style.setWrapText(true);
- for (int row = from; row <= to; row++) {
- for (int col = 0; col <= currentSheet.getRow(row).getLastCellNum(); col++) {
- if (currentSheet.getRow(row).getCell(col) != null) {
- currentSheet.getRow(row).getCell(col).setCellStyle(style);
- }
- }
- }
- return this;
- }
-
- public XlsDocumentBuilder deleteSheet(int index) {
- workBook.removeSheetAt(index);
- return this;
- }
-}
diff --git a/src/main/java/ru/ulstu/core/util/DateUtils.java b/src/main/java/ru/ulstu/core/util/DateUtils.java
index b24b09c..6122583 100644
--- a/src/main/java/ru/ulstu/core/util/DateUtils.java
+++ b/src/main/java/ru/ulstu/core/util/DateUtils.java
@@ -1,6 +1,11 @@
package ru.ulstu.core.util;
-import java.time.*;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Month;
+import java.time.ZoneId;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
@@ -24,7 +29,7 @@ public class DateUtils {
return cal;
}
- public static List getMonths () {
+ public static List getMonths() {
return Arrays.asList(Month.values());
}
diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java
index 1a73e59..404e5c8 100644
--- a/src/main/java/ru/ulstu/deadline/model/Deadline.java
+++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java
@@ -1,5 +1,8 @@
package ru.ulstu.deadline.model;
+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 javax.persistence.Entity;
@@ -13,6 +16,7 @@ public class Deadline extends BaseEntity {
private String description;
@Temporal(value = TemporalType.TIMESTAMP)
+ @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
public Deadline() {
@@ -23,6 +27,15 @@ public class Deadline extends BaseEntity {
this.description = description;
}
+ @JsonCreator
+ public Deadline(@JsonProperty("id") Integer id,
+ @JsonProperty("description") String description,
+ @JsonProperty("date") Date date) {
+ this.setId(id);
+ this.description = description;
+ this.date = date;
+ }
+
public String getDescription() {
return description;
}
diff --git a/src/main/java/ru/ulstu/deadline/model/DeadlineDto.java b/src/main/java/ru/ulstu/deadline/model/DeadlineDto.java
deleted file mode 100644
index 7f724aa..0000000
--- a/src/main/java/ru/ulstu/deadline/model/DeadlineDto.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package ru.ulstu.deadline.model;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.springframework.format.annotation.DateTimeFormat;
-
-import java.util.Date;
-
-public class DeadlineDto {
- private Integer id;
-
- private String description;
-
- @DateTimeFormat(pattern = "yyyy-MM-dd")
- private Date date;
-
- public DeadlineDto() {
- }
-
- @JsonCreator
- public DeadlineDto(@JsonProperty("id") Integer id,
- @JsonProperty("description") String description,
- @JsonProperty("date") Date date) {
- this.id = id;
- this.description = description;
- this.date = date;
- }
-
- public DeadlineDto(Deadline deadline) {
- this.id = deadline.getId();
- this.description = deadline.getDescription();
- this.date = deadline.getDate();
- }
-
- public Integer getId() {
- return id;
- }
-
- public String getDescription() {
- return description;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setDate(Date date) {
- this.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 c371d87..cb80bfe 100644
--- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java
+++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java
@@ -3,7 +3,6 @@ package ru.ulstu.deadline.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.model.Deadline;
-import ru.ulstu.deadline.model.DeadlineDto;
import ru.ulstu.deadline.repository.DeadlineRepository;
import java.util.List;
@@ -17,29 +16,34 @@ public class DeadlineService {
this.deadlineRepository = deadlineRepository;
}
- public List saveOrCreate(List deadlines) {
- return deadlines.stream().map(deadlineDto -> {
- return deadlineDto.getId() != null ? update(deadlineDto) : create(deadlineDto);
- }).collect(Collectors.toList());
+ public List saveOrCreate(List deadlines) {
+ return deadlines
+ .stream()
+ .map(deadline -> {
+ return deadline.getId() != null ? update(deadline) : create(deadline);
+ }).collect(Collectors.toList());
}
@Transactional
- public Deadline update(DeadlineDto deadlineDto) {
- Deadline deadline = deadlineRepository.findOne(deadlineDto.getId());
- deadlineRepository.save(copyFromDto(deadline, deadlineDto));
- return deadline;
+ public Deadline update(Deadline deadline) {
+ Deadline updateDeadline = deadlineRepository.getOne(deadline.getId());
+ updateDeadline.setDate(deadline.getDate());
+ updateDeadline.setDescription(deadline.getDescription());
+ deadlineRepository.save(updateDeadline);
+ return updateDeadline;
}
@Transactional
- public Deadline create(DeadlineDto deadlineDto) {
- Deadline newDeadline = copyFromDto(new Deadline(), deadlineDto);
+ public Deadline create(Deadline deadline) {
+ Deadline newDeadline = new Deadline();
+ newDeadline.setDate(deadline.getDate());
+ newDeadline.setDescription(deadline.getDescription());
newDeadline = deadlineRepository.save(newDeadline);
return newDeadline;
}
- private Deadline copyFromDto(Deadline deadline, DeadlineDto deadlineDto) {
- deadline.setDate(deadlineDto.getDate());
- deadline.setDescription(deadlineDto.getDescription());
- return deadline;
+ @Transactional
+ public void remove(Integer deadlineId) {
+ deadlineRepository.deleteById(deadlineId);
}
}
diff --git a/src/main/java/ru/ulstu/file/FileController.java b/src/main/java/ru/ulstu/file/FileController.java
index e60626b..ac08ac1 100644
--- a/src/main/java/ru/ulstu/file/FileController.java
+++ b/src/main/java/ru/ulstu/file/FileController.java
@@ -13,6 +13,7 @@ import org.springframework.web.multipart.MultipartFile;
import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.response.Response;
import ru.ulstu.file.model.FileData;
+import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService;
import java.io.IOException;
@@ -51,7 +52,7 @@ public class FileController {
}
@PostMapping("/uploadTmpFile")
- public Response upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
- return new Response(fileService.uploadToTmpDir(multipartFile));
+ public Response upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
+ return new Response(fileService.createFromMultipartFile(multipartFile));
}
}
diff --git a/src/main/java/ru/ulstu/file/model/FileData.java b/src/main/java/ru/ulstu/file/model/FileData.java
index e5b3277..3f97130 100644
--- a/src/main/java/ru/ulstu/file/model/FileData.java
+++ b/src/main/java/ru/ulstu/file/model/FileData.java
@@ -19,6 +19,9 @@ public class FileData extends BaseEntity {
private byte[] data;
+ @Column(name = "is_latex_attach")
+ private Boolean isLatexAttach;
+
public String getName() {
return name;
}
@@ -50,4 +53,12 @@ public class FileData extends BaseEntity {
public void setData(byte[] data) {
this.data = data;
}
+
+ public Boolean isLatexAttach() {
+ return isLatexAttach;
+ }
+
+ public void setLatexAttach(Boolean latexAttach) {
+ isLatexAttach = latexAttach;
+ }
}
diff --git a/src/main/java/ru/ulstu/file/model/FileDataDto.java b/src/main/java/ru/ulstu/file/model/FileDataDto.java
new file mode 100644
index 0000000..e83bf12
--- /dev/null
+++ b/src/main/java/ru/ulstu/file/model/FileDataDto.java
@@ -0,0 +1,95 @@
+package ru.ulstu.file.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class FileDataDto {
+ private Integer id;
+ private String name;
+ private String fileName;
+ private String tmpFileName;
+ private boolean deleted;
+ private Boolean isLatexAttach;
+
+ public FileDataDto() {
+ }
+
+ @JsonCreator
+ public FileDataDto(@JsonProperty("id") Integer id,
+ @JsonProperty("name") String name,
+ @JsonProperty("isLatexAttach") Boolean isLatexAttach,
+ @JsonProperty("fileName") String fileName,
+ @JsonProperty("tmpFileName") String tmpFileName) {
+ this.id = id;
+ this.name = name;
+ this.fileName = fileName;
+ this.tmpFileName = tmpFileName;
+ this.isLatexAttach = isLatexAttach;
+ }
+
+ public FileDataDto(FileData fileData) {
+ this.id = fileData.getId();
+ this.name = fileData.getName();
+ this.isLatexAttach = fileData.isLatexAttach();
+ }
+
+ public FileDataDto(String fileName, String tmpFileName) {
+ this.fileName = fileName;
+ this.tmpFileName = tmpFileName;
+ }
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public String getTmpFileName() {
+ return tmpFileName;
+ }
+
+ public void setTmpFileName(String tmpFileName) {
+ this.tmpFileName = tmpFileName;
+ }
+
+ public boolean isDeleted() {
+ return deleted;
+ }
+
+ public void setDeleted(boolean deleted) {
+ this.deleted = deleted;
+ }
+
+ public Boolean isLatexAttach() {
+ return isLatexAttach;
+ }
+
+ public Boolean getIsLatexAttach() {
+ return isLatexAttach;
+ }
+
+ public void setLatexAttach(Boolean latexAttach) {
+ isLatexAttach = latexAttach;
+ }
+
+ public void setIsLatexAttach(Boolean latexAttach) {
+ isLatexAttach = latexAttach;
+ }
+}
diff --git a/src/main/java/ru/ulstu/file/service/FileService.java b/src/main/java/ru/ulstu/file/service/FileService.java
index 2f1fb6d..a8e705a 100644
--- a/src/main/java/ru/ulstu/file/service/FileService.java
+++ b/src/main/java/ru/ulstu/file/service/FileService.java
@@ -1,15 +1,24 @@
package ru.ulstu.file.service;
import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import ru.ulstu.file.model.FileData;
+import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.repostory.FileRepository;
+import ru.ulstu.paper.model.PaperDto;
+import java.io.BufferedWriter;
+import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.Date;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
@@ -29,13 +38,13 @@ public class FileService {
public FileData createFileFromTmp(String tmpFileName) throws IOException {
FileData fileData = new FileData();
fileData.setData(getTmpFile(tmpFileName));
- fileData.setName(getTmpFileName(tmpFileName));
+ fileData.setSize(getTmpFileSize(tmpFileName));
fileData.setCreateDate(new Date());
return fileRepository.save(fileData);
}
public String uploadToTmpDir(MultipartFile multipartFile) throws IOException {
- String tmpFileName = String.valueOf(System.currentTimeMillis());
+ String tmpFileName = String.valueOf(System.currentTimeMillis()) + UUID.randomUUID();
Files.write(getTmpFilePath(tmpFileName), multipartFile.getBytes());
String meta = multipartFile.getOriginalFilename() + "\n" + multipartFile.getSize();
Files.write(getTmpFileMetaPath(tmpFileName), meta.getBytes(UTF_8));
@@ -60,7 +69,7 @@ public class FileService {
}
public FileData getFile(Integer fileId) {
- return fileRepository.findOne(fileId);
+ return fileRepository.getOne(fileId);
}
public void deleteTmpFile(String tmpFileName) throws IOException {
@@ -78,4 +87,63 @@ public class FileService {
public void deleteFile(FileData fileData) {
fileRepository.delete(fileData);
}
+
+ public List saveOrCreate(List fileDtos) throws IOException {
+ List files = new ArrayList<>();
+ for (FileDataDto file : fileDtos) {
+ files.add(file.getId() != null ? update(file) : create(file));
+ }
+ return files;
+ }
+
+ @Transactional
+ public FileData update(FileDataDto fileDataDto) {
+ FileData file = fileRepository.getOne(fileDataDto.getId());
+ return fileRepository.save(copyFromDto(file, fileDataDto));
+ }
+
+ @Transactional
+ public FileData create(FileDataDto fileDataDto) throws IOException {
+ FileData newFile = createFileFromTmp(fileDataDto.getTmpFileName());
+ copyFromDto(newFile, fileDataDto);
+ return fileRepository.save(newFile);
+ }
+
+ private FileData copyFromDto(FileData fileData, FileDataDto fileDataDto) {
+ fileData.setName(fileDataDto.getName());
+ fileData.setLatexAttach(fileDataDto.isLatexAttach());
+ return fileData;
+ }
+
+ @Transactional
+ public void delete(Integer fileId) {
+ fileRepository.delete(fileRepository.getOne(fileId));
+ }
+
+ public FileDataDto createFromMultipartFile(MultipartFile multipartFile) throws IOException {
+ return new FileDataDto(multipartFile.getOriginalFilename(), uploadToTmpDir(multipartFile));
+ }
+
+ public void createLatexAttachs(PaperDto paper) throws IOException {
+ for (FileDataDto fileDataDto : paper.getFiles()
+ .stream()
+ .filter(f -> (f.isLatexAttach() != null && f.isLatexAttach()) && !f.isDeleted())
+ .collect(Collectors.toList())) {
+ if (fileDataDto.getId() == null) {
+ File oldFile = getTmpFilePath(fileDataDto.getTmpFileName()).toFile();
+ File renamed = getTmpFilePath(fileDataDto.getName()).toFile();
+ oldFile.renameTo(renamed);
+ } else {
+ Files.write(getTmpFilePath(fileDataDto.getName()), fileRepository.getOne(fileDataDto.getId()).getData());
+ }
+ }
+ }
+
+ public File createLatexFile(PaperDto paper) throws IOException {
+ BufferedWriter writer = Files.newBufferedWriter(getTmpFilePath(paper.getTitle() + ".tex"));
+ writer.write(paper.getLatexText());
+ writer.close();
+
+ return getTmpFilePath(paper.getTitle() + ".tex").toFile();
+ }
}
diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java
index 415dd0b..a0bb916 100644
--- a/src/main/java/ru/ulstu/grant/controller/GrantController.java
+++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java
@@ -9,10 +9,12 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
-import ru.ulstu.deadline.model.DeadlineDto;
+import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.service.GrantService;
+import ru.ulstu.user.model.User;
+import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
@@ -20,10 +22,14 @@ 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;
@Controller()
@RequestMapping(value = "/grants")
+@ApiIgnore
public class GrantController {
private final GrantService grantService;
@@ -51,41 +57,50 @@ public class GrantController {
}
@PostMapping(value = "/grant", params = "save")
- public String save(@Valid GrantDto grantDto, Errors errors) throws IOException {
+ public String save(@Valid GrantDto grantDto, Errors errors)
+ throws IOException {
filterEmptyDeadlines(grantDto);
if (grantDto.getDeadlines().isEmpty()) {
- errors.rejectValue("deadlines", "errorCode", "Не может быть пустым");
+ errors.rejectValue("deadlines", "errorCode", "Не может быть пусто");
+ }
+ if (grantDto.getLeaderId().equals(-1)) {
+ errors.rejectValue("leaderId", "errorCode", "Укажите руководителя");
}
if (errors.hasErrors()) {
- return "/grants/grant";
+ return GRANT_PAGE;
}
grantService.save(grantDto);
- return "redirect:/grants/grants";
+ return String.format(REDIRECT_TO, GRANTS_PAGE);
+ }
+
+ @PostMapping(value = "/grant", params = "filterUsers")
+ public String filterUsers() {
+ return GRANT_PAGE;
}
@PostMapping(value = "/grant", params = "addDeadline")
public String addDeadline(@Valid GrantDto grantDto, Errors errors) {
filterEmptyDeadlines(grantDto);
if (errors.hasErrors()) {
- return "/grants/grant";
+ return GRANT_PAGE;
}
- grantDto.getDeadlines().add(new DeadlineDto());
- return "/grants/grant";
+ grantDto.getDeadlines().add(new Deadline());
+ return GRANT_PAGE;
}
@PostMapping(value = "/grant", params = "createProject")
- public String createProject(@Valid GrantDto grantDto, Errors errors) {
+ public String createProject(@Valid GrantDto grantDto, Errors errors) throws IOException {
if (errors.hasErrors()) {
- return "/grants/grant";
+ return GRANT_PAGE;
}
grantService.createProject(grantDto);
- return "/grants/grant";
+ return GRANT_PAGE;
}
@GetMapping("/delete/{grant-id}")
public String delete(@PathVariable("grant-id") Integer grantId) throws IOException {
grantService.delete(grantId);
- return "redirect:/grants/grants";
+ return String.format(REDIRECT_TO, GRANTS_PAGE);
}
@ModelAttribute("allStatuses")
@@ -93,6 +108,11 @@ public class GrantController {
return grantService.getGrantStatuses();
}
+ @ModelAttribute("allAuthors")
+ public List getAllAuthors(GrantDto grantDto) {
+ return grantService.getGrantAuthors(grantDto);
+ }
+
private void filterEmptyDeadlines(GrantDto grantDto) {
grantDto.setDeadlines(grantDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java
index 8d40e3a..30d9fb3 100644
--- a/src/main/java/ru/ulstu/grant/model/Grant.java
+++ b/src/main/java/ru/ulstu/grant/model/Grant.java
@@ -1,36 +1,44 @@
package ru.ulstu.grant.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.project.model.Project;
+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.persistence.OrderBy;
import javax.persistence.Table;
+import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
+import java.util.HashSet;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
@Entity
@Table(name = "grants")
-public class Grant extends BaseEntity {
+public class Grant extends BaseEntity implements UserContainer {
public enum GrantStatus {
APPLICATION("Заявка"),
ON_COMPETITION("Отправлен на конкурс"),
SUCCESSFUL_PASSAGE("Успешное прохождение"),
IN_WORK("В работе"),
COMPLETED("Завершен"),
- FAILED("Провалены сроки");
+ FAILED("Провалены сроки"),
+ LOADED_FROM_KIAS("Загружен автоматически");
private String statusName;
@@ -51,6 +59,7 @@ public class Grant extends BaseEntity {
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "grant_id")
+ @OrderBy("date")
private List deadlines = new ArrayList<>();
//Описание гранта
@@ -66,6 +75,14 @@ public class Grant extends BaseEntity {
@JoinColumn(name = "project_id")
private Project project;
+ @ManyToMany(fetch = FetchType.EAGER)
+ private Set authors = new HashSet<>();
+
+ @NotNull
+ @ManyToOne
+ @JoinColumn(name = "leader_id")
+ private User leader;
+
public GrantStatus getStatus() {
return status;
}
@@ -114,6 +131,27 @@ public class Grant extends BaseEntity {
this.project = project;
}
+ public Set getAuthors() {
+ return authors;
+ }
+
+ public void setAuthors(Set authors) {
+ this.authors = authors;
+ }
+
+ @Override
+ public Set getUsers() {
+ return getAuthors();
+ }
+
+ public User getLeader() {
+ return leader;
+ }
+
+ public void setLeader(User leader) {
+ this.leader = leader;
+ }
+
public Optional getNextDeadline() {
return deadlines
.stream()
diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java
index e56896a..d836dfb 100644
--- a/src/main/java/ru/ulstu/grant/model/GrantDto.java
+++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java
@@ -2,36 +2,54 @@ package ru.ulstu.grant.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import org.hibernate.validator.constraints.NotEmpty;
-import ru.ulstu.deadline.model.DeadlineDto;
+import org.apache.commons.lang3.StringUtils;
+import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.project.model.ProjectDto;
+import ru.ulstu.user.model.UserDto;
+import javax.validation.constraints.NotEmpty;
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 GrantDto {
+ private final static int MAX_AUTHORS_LENGTH = 60;
+
private Integer id;
@NotEmpty
private String title;
private Grant.GrantStatus status;
- private List deadlines = new ArrayList<>();
+ private List deadlines = new ArrayList<>();
private String comment;
private String applicationFileName;
private ProjectDto project;
+ private Set authorIds;
+ private Set authors;
+ private Integer leaderId;
+ private boolean wasLeader;
+ private boolean hasAge;
+ private boolean hasDegree;
public GrantDto() {
- deadlines.add(new DeadlineDto());
+ deadlines.add(new Deadline());
}
@JsonCreator
public GrantDto(@JsonProperty("id") Integer id,
@JsonProperty("title") String title,
@JsonProperty("status") Grant.GrantStatus status,
- @JsonProperty("deadlines") List deadlines,
+ @JsonProperty("deadlines") List deadlines,
@JsonProperty("comment") String comment,
- @JsonProperty("project") ProjectDto project) {
+ @JsonProperty("project") ProjectDto project,
+ @JsonProperty("authorIds") Set authorIds,
+ @JsonProperty("authors") Set authors,
+ @JsonProperty("leader") Integer leaderId,
+ @JsonProperty("wasLeader") boolean wasLeader,
+ @JsonProperty("hasAge") boolean hasAge,
+ @JsonProperty("hasDegree") boolean hasDegree) {
this.id = id;
this.title = title;
this.status = status;
@@ -39,16 +57,27 @@ public class GrantDto {
this.comment = comment;
this.applicationFileName = null;
this.project = project;
+ this.authors = authors;
+ this.leaderId = leaderId;
+ this.wasLeader = wasLeader;
+ this.hasAge = hasAge;
+ this.hasDegree = hasDegree;
}
public GrantDto(Grant grant) {
this.id = grant.getId();
this.title = grant.getTitle();
this.status = grant.getStatus();
- this.deadlines = convert(grant.getDeadlines(), DeadlineDto::new);
+ this.deadlines = grant.getDeadlines();
this.comment = grant.getComment();
this.project = grant.getProject() == null ? null : new ProjectDto(grant.getProject());
this.applicationFileName = grant.getApplication() == null ? null : grant.getApplication().getName();
+ this.authorIds = convert(grant.getAuthors(), user -> user.getId());
+ this.authors = convert(grant.getAuthors(), UserDto::new);
+ this.leaderId = grant.getLeader().getId();
+ this.wasLeader = false;
+ this.hasAge = false;
+ this.hasDegree = false;
}
public Integer getId() {
@@ -75,11 +104,11 @@ public class GrantDto {
this.status = status;
}
- public List getDeadlines() {
+ public List getDeadlines() {
return deadlines;
}
- public void setDeadlines(List deadlines) {
+ public void setDeadlines(List deadlines) {
this.deadlines = deadlines;
}
@@ -106,4 +135,59 @@ public class GrantDto {
public void setApplicationFileName(String applicationFileName) {
this.applicationFileName = applicationFileName;
}
+
+ public Set getAuthorIds() {
+ return authorIds;
+ }
+
+ public void setAuthorIds(Set authorIds) {
+ this.authorIds = authorIds;
+ }
+
+ public Set getAuthors() {
+ return authors;
+ }
+
+ public void setAuthors(Set authors) {
+ this.authors = authors;
+ }
+
+ public String getAuthorsString() {
+ return StringUtils.abbreviate(authors
+ .stream()
+ .map(author -> author.getLastName())
+ .collect(Collectors.joining(", ")), MAX_AUTHORS_LENGTH);
+ }
+
+ public Integer getLeaderId() {
+ return leaderId;
+ }
+
+ public void setLeaderId(Integer leaderId) {
+ this.leaderId = leaderId;
+ }
+
+ public boolean isWasLeader() {
+ return wasLeader;
+ }
+
+ public void setWasLeader(boolean wasLeader) {
+ this.wasLeader = wasLeader;
+ }
+
+ 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;
+ }
}
diff --git a/src/main/java/ru/ulstu/grant/model/GrantStatusDto.java b/src/main/java/ru/ulstu/grant/model/GrantStatusDto.java
deleted file mode 100644
index 34676d6..0000000
--- a/src/main/java/ru/ulstu/grant/model/GrantStatusDto.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package ru.ulstu.grant.model;
-
-public class GrantStatusDto {
- private final String id;
- private final String name;
-
- public GrantStatusDto(Grant.GrantStatus status) {
- this.id = status.name();
- this.name = status.getStatusName();
- }
-
- public String getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-}
diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
index 92dec43..44c2cc0 100644
--- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
+++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
@@ -3,6 +3,9 @@ package ru.ulstu.grant.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.grant.model.Grant;
+import java.util.List;
+
public interface GrantRepository extends JpaRepository {
+ List findByStatus(Grant.GrantStatus status);
}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java
index d5beec3..a6e255f 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantService.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantService.java
@@ -12,11 +12,14 @@ import ru.ulstu.grant.repository.GrantRepository;
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 ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
+import java.util.stream.Collectors;
import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert;
@@ -30,15 +33,18 @@ public class GrantService {
private final ProjectService projectService;
private final DeadlineService deadlineService;
private final FileService fileService;
+ private final UserService userService;
public GrantService(GrantRepository grantRepository,
FileService fileService,
DeadlineService deadlineService,
- ProjectService projectService) {
+ ProjectService projectService,
+ UserService userService) {
this.grantRepository = grantRepository;
- this.projectService = projectService;
this.fileService = fileService;
this.deadlineService = deadlineService;
+ this.projectService = projectService;
+ this.userService = userService;
}
public List findAll() {
@@ -52,7 +58,7 @@ public class GrantService {
}
public GrantDto findOneDto(Integer id) {
- return new GrantDto(grantRepository.findOne(id));
+ return new GrantDto(grantRepository.getOne(id));
}
@Transactional
@@ -73,17 +79,24 @@ public class GrantService {
if (grantDto.getApplicationFileName() != null) {
grant.setApplication(fileService.createFileFromTmp(grantDto.getApplicationFileName()));
}
+ grant.getAuthors().clear();
+ if (grantDto.getAuthorIds() != null && !grantDto.getAuthorIds().isEmpty()) {
+ grantDto.getAuthorIds().forEach(authorIds -> grant.getAuthors().add(userService.findById(authorIds)));
+ }
+ if (grantDto.getLeaderId() != null) {
+ grant.setLeader(userService.findById(grantDto.getLeaderId()));
+ }
return grant;
}
- public void createProject(GrantDto grantDto) {
+ public void createProject(GrantDto grantDto) throws IOException {
grantDto.setProject(
new ProjectDto(projectService.save(new ProjectDto(grantDto.getTitle()))));
}
@Transactional
public Integer update(GrantDto grantDto) throws IOException {
- Grant grant = grantRepository.findOne(grantDto.getId());
+ Grant grant = grantRepository.getOne(grantDto.getId());
Grant.GrantStatus oldStatus = grant.getStatus();
if (grantDto.getApplicationFileName() != null && grant.getApplication() != null) {
fileService.deleteFile(grant.getApplication());
@@ -94,11 +107,10 @@ public class GrantService {
@Transactional
public void delete(Integer grantId) throws IOException {
- Grant grant = grantRepository.findOne(grantId);
+ Grant grant = grantRepository.getOne(grantId);
if (grant.getApplication() != null) {
fileService.deleteFile(grant.getApplication());
}
- //возможно при удалении гранта будет удаляться и проект, к нему привязанный
grantRepository.delete(grant);
}
@@ -107,13 +119,15 @@ public class GrantService {
}
@Transactional
- public Grant create(String title, Project projectId, Date deadlineDate) {
+ public Grant create(String title, Project projectId, Date deadlineDate, User user) {
Grant grant = new Grant();
grant.setTitle(title);
grant.setComment("Комментарий к гранту 1");
grant.setProject(projectId);
grant.setStatus(APPLICATION);
grant.getDeadlines().add(new Deadline(deadlineDate, "первый дедлайн"));
+ grant.getAuthors().add(user);
+ grant.setLeader(user);
grant = grantRepository.save(grant);
return grant;
}
@@ -125,4 +139,22 @@ public class GrantService {
update(grantDto);
}
}
+
+ public List getGrantAuthors(GrantDto grantDto) {
+ List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree());
+ if (grantDto.isWasLeader()) {
+ filteredUsers = filteredUsers
+ .stream()
+ .filter(getCompletedGrantLeaders()::contains)
+ .collect(Collectors.toList());
+ }
+ return filteredUsers;
+ }
+
+ private List getCompletedGrantLeaders() {
+ return grantRepository.findByStatus(Grant.GrantStatus.COMPLETED)
+ .stream()
+ .map(Grant::getLeader)
+ .collect(Collectors.toList());
+ }
}
diff --git a/src/main/java/ru/ulstu/index/controller/IndexController.java b/src/main/java/ru/ulstu/index/controller/IndexController.java
new file mode 100644
index 0000000..f6ab100
--- /dev/null
+++ b/src/main/java/ru/ulstu/index/controller/IndexController.java
@@ -0,0 +1,23 @@
+package ru.ulstu.index.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.ModelMap;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import ru.ulstu.core.controller.AdviceController;
+import ru.ulstu.user.service.UserService;
+import springfox.documentation.annotations.ApiIgnore;
+
+@Controller()
+@RequestMapping(value = "/index")
+@ApiIgnore
+public class IndexController extends AdviceController {
+ public IndexController(UserService userService) {
+ super(userService);
+ }
+
+ @GetMapping
+ public void currentUser(ModelMap modelMap) {
+ //нужен здесь для добавления параметров на стартовой странице
+ }
+}
diff --git a/src/main/java/ru/ulstu/odin/model/OdinField.java b/src/main/java/ru/ulstu/odin/model/OdinField.java
index 5917a44..6beb7d9 100644
--- a/src/main/java/ru/ulstu/odin/model/OdinField.java
+++ b/src/main/java/ru/ulstu/odin/model/OdinField.java
@@ -1,13 +1,13 @@
package ru.ulstu.odin.model;
import com.fasterxml.jackson.annotation.JsonProperty;
-import org.hibernate.validator.constraints.NotBlank;
-import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.core.error.OdinException;
import ru.ulstu.odin.model.annotation.OdinCaption;
import ru.ulstu.odin.model.annotation.OdinReadOnly;
import ru.ulstu.odin.model.annotation.OdinVisible;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
@@ -31,14 +31,13 @@ public abstract class OdinField implements Comparable {
return this.name().toLowerCase();
}
}
-
- private Field field;
protected final OdinFieldType fieldType;
protected final String fieldName;
protected final String caption;
protected final OdinVisible.OdinVisibleType visible;
protected final boolean readOnly;
protected final boolean notEmpty;
+ private Field field;
public OdinField(Field field, OdinFieldType fieldType) {
this.field = field;
@@ -126,8 +125,12 @@ public abstract class OdinField implements Comparable {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
OdinField odinField = (OdinField) o;
return Objects.equals(fieldName, odinField.fieldName);
}
diff --git a/src/main/java/ru/ulstu/odin/model/OdinStringField.java b/src/main/java/ru/ulstu/odin/model/OdinStringField.java
index 5157d7e..498b375 100644
--- a/src/main/java/ru/ulstu/odin/model/OdinStringField.java
+++ b/src/main/java/ru/ulstu/odin/model/OdinStringField.java
@@ -1,9 +1,9 @@
package ru.ulstu.odin.model;
-import org.hibernate.validator.constraints.Email;
import ru.ulstu.odin.model.annotation.OdinString;
import ru.ulstu.odin.model.annotation.OdinString.OdinStringType;
+import javax.validation.constraints.Email;
import javax.validation.constraints.Size;
import java.lang.reflect.Field;
diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java
index cb34a8a..e11e4d9 100644
--- a/src/main/java/ru/ulstu/paper/controller/PaperController.java
+++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java
@@ -1,5 +1,8 @@
package ru.ulstu.paper.controller;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@@ -9,30 +12,37 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
-import ru.ulstu.deadline.model.DeadlineDto;
+import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperFilterDto;
+import ru.ulstu.paper.service.LatexService;
import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User;
+import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
+import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
+import static java.nio.charset.StandardCharsets.UTF_8;
import static org.springframework.util.StringUtils.isEmpty;
@Controller()
@RequestMapping(value = "/papers")
+@ApiIgnore
public class PaperController {
private final PaperService paperService;
+ private final LatexService latexService;
- public PaperController(PaperService paperService) {
+ public PaperController(PaperService paperService, LatexService latexService) {
this.paperService = paperService;
+ this.latexService = latexService;
}
@GetMapping("/papers")
@@ -49,7 +59,7 @@ public class PaperController {
@GetMapping("/dashboard")
public void getDashboard(ModelMap modelMap) {
- modelMap.put("papers", paperService.findAllActive());
+ modelMap.put("papers", paperService.findAllActiveDto());
}
@GetMapping("/paper")
@@ -80,7 +90,7 @@ public class PaperController {
if (errors.hasErrors()) {
return "/papers/paper";
}
- paperDto.getDeadlines().add(new DeadlineDto());
+ paperDto.getDeadlines().add(new Deadline());
return "/papers/paper";
}
@@ -95,6 +105,11 @@ public class PaperController {
return paperService.getPaperStatuses();
}
+ @ModelAttribute("allTypes")
+ public List getPaperTypes() {
+ return paperService.getPaperTypes();
+ }
+
@ModelAttribute("allAuthors")
public List getAllAuthors() {
return paperService.getPaperAuthors();
@@ -109,6 +124,14 @@ public class PaperController {
return years;
}
+ @PostMapping("/generatePdf")
+ public ResponseEntity getPdfFile(PaperDto paper) throws IOException, InterruptedException {
+ HttpHeaders headers = new HttpHeaders();
+ headers.add("Content-Disposition", "attachment; filename='" +
+ URLEncoder.encode(paper.getTitle() + ".pdf", UTF_8.toString()) + "'");
+ return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK);
+ }
+
private void filterEmptyDeadlines(PaperDto paperDto) {
paperDto.setDeadlines(paperDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
diff --git a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java b/src/main/java/ru/ulstu/paper/controller/PaperRestController.java
index 5dd6b9f..2bd8384 100644
--- a/src/main/java/ru/ulstu/paper/controller/PaperRestController.java
+++ b/src/main/java/ru/ulstu/paper/controller/PaperRestController.java
@@ -61,4 +61,9 @@ public class PaperRestController {
public Response> filter(@RequestBody @Valid PaperFilterDto paperFilterDto) throws IOException {
return new Response<>(paperService.filter(paperFilterDto));
}
+
+ @GetMapping("formatted-list")
+ public Response> getFormattedPaperList() {
+ return new Response<>(paperService.getFormattedPaperList());
+ }
}
diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java
index c09fd28..4f77826 100644
--- a/src/main/java/ru/ulstu/paper/model/Paper.java
+++ b/src/main/java/ru/ulstu/paper/model/Paper.java
@@ -2,11 +2,11 @@ package ru.ulstu.paper.model;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
-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.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
@@ -17,11 +17,11 @@ 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.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
@@ -53,12 +53,32 @@ public class Paper extends BaseEntity implements UserContainer {
}
}
+ public enum PaperType {
+ OTHER("Прочая публикация"),
+ VAK("ВАК"),
+ SCOPUS("Scopus"),
+ WEB_OF_SCIENCE("Web Of Science");
+
+ private String typeName;
+
+ PaperType(String name) {
+ this.typeName = name;
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+ }
+
@NotBlank
private String title;
@Enumerated(value = EnumType.STRING)
private PaperStatus status = PaperStatus.DRAFT;
+ @Enumerated(value = EnumType.STRING)
+ private PaperType type = PaperType.OTHER;
+
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate = new Date();
@@ -75,15 +95,25 @@ public class Paper extends BaseEntity implements UserContainer {
private String comment;
+ private String url;
+
private Boolean locked = false;
- @ManyToOne
- @JoinColumn(name = "file_id")
- private FileData fileData;
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
+ @JoinColumn(name = "paper_id")
+ private List events = new ArrayList<>();
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "paper_id", unique = true)
+ @Fetch(FetchMode.SUBSELECT)
+ private List files = new ArrayList<>();
@ManyToMany(fetch = FetchType.EAGER)
private Set authors = new HashSet<>();
+ @Column(name = "latex_text")
+ private String latexText;
+
public PaperStatus getStatus() {
return status;
}
@@ -92,6 +122,14 @@ public class Paper extends BaseEntity implements UserContainer {
this.status = status;
}
+ public PaperType getType() {
+ return type;
+ }
+
+ public void setType(PaperType type) {
+ this.type = type;
+ }
+
public Date getCreateDate() {
return createDate;
}
@@ -132,12 +170,12 @@ public class Paper extends BaseEntity implements UserContainer {
this.locked = locked;
}
- public FileData getFileData() {
- return fileData;
+ public List getFiles() {
+ return files;
}
- public void setFileData(FileData fileData) {
- this.fileData = fileData;
+ public void setFiles(List files) {
+ this.files = files;
}
public String getTitle() {
@@ -156,6 +194,30 @@ public class Paper extends BaseEntity implements UserContainer {
this.authors = authors;
}
+ public List getEvents() {
+ return events;
+ }
+
+ public void setEvents(List events) {
+ this.events = events;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getLatexText() {
+ return latexText;
+ }
+
+ public void setLatexText(String latexText) {
+ this.latexText = latexText;
+ }
+
@Override
public Set getUsers() {
return getAuthors();
diff --git a/src/main/java/ru/ulstu/paper/model/PaperDto.java b/src/main/java/ru/ulstu/paper/model/PaperDto.java
index 545b432..9ed60e7 100644
--- a/src/main/java/ru/ulstu/paper/model/PaperDto.java
+++ b/src/main/java/ru/ulstu/paper/model/PaperDto.java
@@ -3,10 +3,11 @@ package ru.ulstu.paper.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils;
-import org.hibernate.validator.constraints.NotEmpty;
-import ru.ulstu.deadline.model.DeadlineDto;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.user.model.UserDto;
+import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
@@ -24,48 +25,51 @@ public class PaperDto {
@Size(min = 3, max = 254)
private String title;
private Paper.PaperStatus status;
+ private Paper.PaperType type;
private Date createDate;
private Date updateDate;
@NotEmpty
- private List deadlines = new ArrayList<>();
+ private List deadlines = new ArrayList<>();
private String comment;
+ private String url;
private Boolean locked;
- private String tmpFileName;
- private Integer fileId;
- private String fileName;
- private Date fileCreateDate;
+ private List files = new ArrayList<>();
private Set authorIds;
private Set authors;
private Integer filterAuthorId;
+ private String latexText;
public PaperDto() {
- deadlines.add(new DeadlineDto());
+ deadlines.add(new Deadline());
}
@JsonCreator
public PaperDto(@JsonProperty("id") Integer id,
@JsonProperty("title") String title,
@JsonProperty("status") Paper.PaperStatus status,
+ @JsonProperty("type") Paper.PaperType type,
@JsonProperty("createDate") Date createDate,
@JsonProperty("updateDate") Date updateDate,
- @JsonProperty("deadlines") List deadlines,
+ @JsonProperty("deadlines") List deadlines,
@JsonProperty("comment") String comment,
+ @JsonProperty("latex_text") String latexText,
+ @JsonProperty("url") String url,
@JsonProperty("locked") Boolean locked,
- @JsonProperty("tmpFileName") String tmpFileName,
+ @JsonProperty("files") List files,
@JsonProperty("authorIds") Set authorIds,
@JsonProperty("authors") Set authors) {
this.id = id;
this.title = title;
this.status = status;
+ this.type = type;
this.createDate = createDate;
this.updateDate = updateDate;
this.deadlines = deadlines;
this.comment = comment;
+ this.url = url;
+ this.latexText = latexText;
this.locked = locked;
- this.tmpFileName = tmpFileName;
- this.fileId = null;
- this.fileName = null;
- this.fileCreateDate = null;
+ this.files = files;
this.authors = authors;
}
@@ -73,15 +77,15 @@ public class PaperDto {
this.id = paper.getId();
this.title = paper.getTitle();
this.status = paper.getStatus();
+ this.type = paper.getType();
this.createDate = paper.getCreateDate();
this.updateDate = paper.getUpdateDate();
- this.deadlines = convert(paper.getDeadlines(), DeadlineDto::new);
+ this.deadlines = paper.getDeadlines();
this.comment = paper.getComment();
+ this.url = paper.getUrl();
+ this.latexText = paper.getLatexText();
this.locked = paper.getLocked();
- this.tmpFileName = null;
- this.fileId = paper.getFileData() == null ? null : paper.getFileData().getId();
- this.fileName = paper.getFileData() == null ? null : paper.getFileData().getName();
- this.fileCreateDate = paper.getFileData() == null ? null : paper.getFileData().getCreateDate();
+ this.files = convert(paper.getFiles(), FileDataDto::new);
this.authorIds = convert(paper.getAuthors(), user -> user.getId());
this.authors = convert(paper.getAuthors(), UserDto::new);
}
@@ -110,6 +114,14 @@ public class PaperDto {
this.status = status;
}
+ public Paper.PaperType getType() {
+ return type;
+ }
+
+ public void setType(Paper.PaperType type) {
+ this.type = type;
+ }
+
public Date getCreateDate() {
return createDate;
}
@@ -126,11 +138,11 @@ public class PaperDto {
this.updateDate = updateDate;
}
- public List getDeadlines() {
+ public List getDeadlines() {
return deadlines;
}
- public void setDeadlines(List deadlines) {
+ public void setDeadlines(List deadlines) {
this.deadlines = deadlines;
}
@@ -150,36 +162,12 @@ public class PaperDto {
this.locked = locked;
}
- public String getTmpFileName() {
- return tmpFileName;
+ public List getFiles() {
+ return files;
}
- public void setTmpFileName(String tmpFileName) {
- this.tmpFileName = tmpFileName;
- }
-
- public Integer getFileId() {
- return fileId;
- }
-
- public void setFileId(Integer fileId) {
- this.fileId = fileId;
- }
-
- public String getFileName() {
- return fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public Date getFileCreateDate() {
- return fileCreateDate;
- }
-
- public void setFileCreateDate(Date fileCreateDate) {
- this.fileCreateDate = fileCreateDate;
+ public void setFiles(List files) {
+ this.files = files;
}
public Set getAuthors() {
@@ -198,6 +186,22 @@ public class PaperDto {
this.authorIds = authorIds;
}
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getLatexText() {
+ return latexText;
+ }
+
+ public void setLatexText(String latexText) {
+ this.latexText = latexText;
+ }
+
public String getAuthorsString() {
return StringUtils.abbreviate(authors
.stream()
diff --git a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java b/src/main/java/ru/ulstu/paper/repository/PaperRepository.java
index 3951f53..343e9e2 100644
--- a/src/main/java/ru/ulstu/paper/repository/PaperRepository.java
+++ b/src/main/java/ru/ulstu/paper/repository/PaperRepository.java
@@ -12,4 +12,6 @@ public interface PaperRepository extends JpaRepository {
@Query("SELECT p FROM Paper p WHERE (:author IS NULL OR :author MEMBER OF p.authors) AND (YEAR(p.createDate) = :year OR :year IS NULL)")
List filter(@Param("author") User author, @Param("year") Integer year);
+
+ List findByIdNotIn(List paperIds);
}
diff --git a/src/main/java/ru/ulstu/paper/service/LatexService.java b/src/main/java/ru/ulstu/paper/service/LatexService.java
new file mode 100644
index 0000000..82dd1ba
--- /dev/null
+++ b/src/main/java/ru/ulstu/paper/service/LatexService.java
@@ -0,0 +1,76 @@
+package ru.ulstu.paper.service;
+
+import org.springframework.stereotype.Service;
+import ru.ulstu.file.service.FileService;
+import ru.ulstu.paper.model.PaperDto;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.file.Files;
+
+@Service
+public class LatexService {
+ private final String pdfLatexError = "Errors occurred while executing pdfLaTeX.";
+ private final String bibtexError = "Errors occurred while executing bibtex.";
+ private String errorMessage;
+ private File pdfFile;
+ private FileService fileService;
+
+ public LatexService(FileService fileService) {
+ this.fileService = fileService;
+ }
+
+ public byte[] generatePdfFromLatexFile(PaperDto paper) throws IOException, InterruptedException {
+ fileService.createLatexAttachs(paper);
+ File tex = fileService.createLatexFile(paper);
+
+ if (!generate(paper.getTitle(), tex.getParentFile())) {
+ throw new IOException(errorMessage);
+ }
+
+ return Files.readAllBytes(pdfFile.toPath());
+ }
+
+ private int startProcess(String[] args, File dir, String message) throws IOException, InterruptedException {
+ ProcessBuilder processBuilder = new ProcessBuilder(args);
+ processBuilder.redirectErrorStream(true);
+ processBuilder.directory(dir);
+
+ Process process = processBuilder.start();
+ InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
+
+ try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
+ while ((bufferedReader.readLine()) != null) {
+ //
+ }
+ }
+
+ int exitCode = process.waitFor();
+ if (exitCode != 0) {
+ errorMessage = message + " Exit value of the process: " + exitCode;
+ }
+ return exitCode;
+ }
+
+ private boolean generate(String filename, File dir) throws IOException, InterruptedException {
+ startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, pdfLatexError);
+ startProcess(new String[]{"bibtex", filename}, dir, bibtexError);
+ if (startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, pdfLatexError) != 0) {
+ return false;
+ }
+ return checkPdf(filename, dir);
+ }
+
+ private boolean checkPdf(String filename, File dir) {
+ pdfFile = new File(dir.getAbsolutePath() + File.separator + filename + ".pdf");
+
+ if (pdfFile.isFile()) {
+ return true;
+ } else {
+ errorMessage = "The pdf file could not be created.";
+ return false;
+ }
+ }
+}
diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java
index 9df8be2..33344a5 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -5,11 +5,13 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
+import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperFilterDto;
import ru.ulstu.paper.repository.PaperRepository;
+import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
@@ -21,6 +23,7 @@ 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;
import static ru.ulstu.core.util.StreamApiUtils.convert;
import static ru.ulstu.paper.model.Paper.PaperStatus.ATTENTION;
@@ -28,27 +31,32 @@ import static ru.ulstu.paper.model.Paper.PaperStatus.COMPLETED;
import static ru.ulstu.paper.model.Paper.PaperStatus.DRAFT;
import static ru.ulstu.paper.model.Paper.PaperStatus.FAILED;
import static ru.ulstu.paper.model.Paper.PaperStatus.ON_PREPARATION;
+import static ru.ulstu.paper.model.Paper.PaperType.OTHER;
@Service
public class PaperService {
private final static int MAX_DISPLAY_SIZE = 40;
+ private final static String PAPER_FORMATTED_TEMPLATE = "%s %s";
private final PaperNotificationService paperNotificationService;
private final PaperRepository paperRepository;
private final UserService userService;
private final DeadlineService deadlineService;
private final FileService fileService;
+ private final EventService eventService;
public PaperService(PaperRepository paperRepository,
FileService fileService,
PaperNotificationService paperNotificationService,
UserService userService,
- DeadlineService deadlineService) {
+ DeadlineService deadlineService,
+ EventService eventService) {
this.paperRepository = paperRepository;
this.fileService = fileService;
this.paperNotificationService = paperNotificationService;
this.userService = userService;
this.deadlineService = deadlineService;
+ this.eventService = eventService;
}
public List findAll() {
@@ -61,15 +69,19 @@ public class PaperService {
return papers;
}
- public List findAllActive() {
- return findAllDto()
+ public List findAllActive() {
+ return findAll()
.stream()
.filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED)
- .collect(Collectors.toList());
+ .collect(toList());
+ }
+
+ public List findAllActiveDto() {
+ return convert(findAllActive(), PaperDto::new);
}
public PaperDto findOneDto(Integer id) {
- return new PaperDto(paperRepository.findOne(id));
+ return new PaperDto(paperRepository.getOne(id));
}
@Transactional
@@ -77,20 +89,24 @@ public class PaperService {
Paper newPaper = copyFromDto(new Paper(), paperDto);
newPaper = paperRepository.save(newPaper);
paperNotificationService.sendCreateNotification(newPaper);
+ eventService.createFromPaper(newPaper);
return newPaper.getId();
}
private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException {
paper.setComment(paperDto.getComment());
+ paper.setUrl(paperDto.getUrl());
+ paper.setLatexText(paperDto.getLatexText());
paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate());
paper.setLocked(paperDto.getLocked());
paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus());
+ paper.setType(paperDto.getType() == null ? OTHER : paperDto.getType());
paper.setTitle(paperDto.getTitle());
paper.setUpdateDate(new Date());
paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines()));
- if (paperDto.getTmpFileName() != null) {
- paper.setFileData(fileService.createFileFromTmp(paperDto.getTmpFileName()));
- }
+ paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream()
+ .filter(f -> !f.isDeleted())
+ .collect(toList())));
paper.getAuthors().clear();
if (paperDto.getAuthorIds() != null && !paperDto.getAuthorIds().isEmpty()) {
paperDto.getAuthorIds().forEach(authorIds -> paper.getAuthors().add(userService.findById(authorIds)));
@@ -100,13 +116,17 @@ public class PaperService {
@Transactional
public Integer update(PaperDto paperDto) throws IOException {
- Paper paper = paperRepository.findOne(paperDto.getId());
+ Paper paper = paperRepository.getOne(paperDto.getId());
Paper.PaperStatus oldStatus = paper.getStatus();
Set oldAuthors = new HashSet<>(paper.getAuthors());
- if (paperDto.getTmpFileName() != null && paper.getFileData() != null) {
- fileService.deleteFile(paper.getFileData());
+
+ for (FileDataDto file : paperDto.getFiles().stream()
+ .filter(f -> f.isDeleted() && f.getId() != null)
+ .collect(toList())) {
+ fileService.delete(file.getId());
}
paperRepository.save(copyFromDto(paper, paperDto));
+ eventService.updatePaperDeadlines(paper);
paper.getAuthors().forEach(author -> {
if (!oldAuthors.contains(author)) {
@@ -123,10 +143,7 @@ public class PaperService {
@Transactional
public void delete(Integer paperId) throws IOException {
- Paper paper = paperRepository.findOne(paperId);
- if (paper.getFileData() != null) {
- fileService.deleteFile(paper.getFileData());
- }
+ Paper paper = paperRepository.getOne(paperId);
paperRepository.delete(paper);
}
@@ -134,6 +151,10 @@ public class PaperService {
return Arrays.asList(Paper.PaperStatus.values());
}
+ public List getPaperTypes() {
+ return Arrays.asList(Paper.PaperType.values());
+ }
+
@Transactional
public Paper create(String title, User user, Date deadlineDate) {
Paper paper = new Paper();
@@ -143,9 +164,11 @@ public class PaperService {
paper.setCreateDate(new Date());
paper.setUpdateDate(new Date());
paper.setStatus(DRAFT);
+ paper.setType(OTHER);
paper = paperRepository.save(paper);
paperNotificationService.sendCreateNotification(paper);
+ eventService.createFromPaper(paper);
return paper;
}
@@ -165,7 +188,7 @@ public class PaperService {
return statusCompareResult;
}
return paper1.getTitle().compareTo(paper2.getTitle());
- }).collect(Collectors.toList());
+ }).collect(toList());
}
public PaperDto findPaper(int id) {
@@ -179,7 +202,7 @@ public class PaperService {
&& (paper.getStatus() == ON_PREPARATION
|| paper.getStatus() == DRAFT
|| paper.getStatus() == ATTENTION))
- .collect(Collectors.toList());
+ .collect(toList());
papers.forEach(paper -> {
Paper.PaperStatus oldStatus = paper.getStatus();
paper.setStatus(Paper.PaperStatus.FAILED);
@@ -197,10 +220,44 @@ public class PaperService {
}
public PaperDto findById(Integer paperId) {
- return new PaperDto(paperRepository.findOne(paperId));
+ return new PaperDto(paperRepository.getOne(paperId));
+ }
+
+ public Paper findEntityById(Integer paperId) {
+ return paperRepository.getOne(paperId);
+ }
+
+ public List findAllNotSelect(List paperIds) {
+ if (!paperIds.isEmpty()) {
+ return sortPapers(paperRepository.findByIdNotIn(paperIds));
+ } else {
+ return sortPapers(paperRepository.findAll());
+ }
+
}
public List getPaperAuthors() {
return userService.findAll();
}
+
+ public List getFormattedPaperList() {
+ return findAllCompleted()
+ .stream()
+ .map(paper -> String.format(PAPER_FORMATTED_TEMPLATE, paper.getTitle(), getAuthors(paper)))
+ .collect(toList());
+ }
+
+ private List findAllCompleted() {
+ return findAll()
+ .stream()
+ .filter(paper -> paper.getStatus() == COMPLETED)
+ .collect(toList());
+ }
+
+ private String getAuthors(Paper paper) {
+ return paper.getAuthors()
+ .stream()
+ .map(User::getUserAbbreviate)
+ .collect(Collectors.joining(", "));
+ }
}
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..affdaec
--- /dev/null
+++ b/src/main/java/ru/ulstu/project/controller/ProjectController.java
@@ -0,0 +1,86 @@
+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.GetMapping;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+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 org.springframework.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());
+ }
+
+ @GetMapping("/project")
+ public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
+ if (id != null && id > 0) {
+ modelMap.put("projectDto", projectService.findOneDto(id));
+ } else {
+ modelMap.put("projectDto", new ProjectDto());
+ }
+ }
+
+ @ModelAttribute("allStatuses")
+ public List getProjectStatuses() {
+ return projectService.getProjectStatuses();
+ }
+
+ @PostMapping(value = "/project", params = "save")
+ public String save(@Valid ProjectDto projectDto, Errors errors) throws IOException {
+ filterEmptyDeadlines(projectDto);
+ if (projectDto.getDeadlines().isEmpty()) {
+ errors.rejectValue("deadlines", "errorCode", "Не может быть пустым");
+ }
+ if (errors.hasErrors()) {
+ return "/projects/project";
+ }
+ projectService.save(projectDto);
+ return String.format("redirect:%s", "/projects/projects");
+ }
+
+ @PostMapping(value = "/project", params = "addDeadline")
+ public String addDeadline(@Valid ProjectDto projectDto, Errors errors) {
+ filterEmptyDeadlines(projectDto);
+ if (errors.hasErrors()) {
+ return "/projects/project";
+ }
+ projectDto.getDeadlines().add(new Deadline());
+ return "/projects/project";
+ }
+
+ private void filterEmptyDeadlines(ProjectDto projectDto) {
+ projectDto.setDeadlines(projectDto.getDeadlines().stream()
+ .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
+ .collect(Collectors.toList()));
+ }
+}
diff --git a/src/main/java/ru/ulstu/project/model/Project.java b/src/main/java/ru/ulstu/project/model/Project.java
index 06722a1..5b9da69 100644
--- a/src/main/java/ru/ulstu/project/model/Project.java
+++ b/src/main/java/ru/ulstu/project/model/Project.java
@@ -1,26 +1,67 @@
package ru.ulstu.project.model;
-import org.hibernate.validator.constraints.NotBlank;
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 javax.persistence.CascadeType;
import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Project extends BaseEntity {
+ public enum ProjectStatus {
+ APPLICATION("Заявка"),
+ ON_COMPETITION("Отправлен на конкурс"),
+ SUCCESSFUL_PASSAGE("Успешное прохождение"),
+ IN_WORK("В работе"),
+ COMPLETED("Завершен"),
+ FAILED("Провалены сроки");
+
+ private String statusName;
+
+ ProjectStatus(String statusName) {
+ this.statusName = statusName;
+ }
+
+ public String getStatusName() {
+ return statusName;
+ }
+ }
@NotBlank
private String title;
+ @Enumerated(value = EnumType.STRING)
+ private ProjectStatus status = ProjectStatus.APPLICATION;
+
+ @NotNull
+ private String description;
+
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "project_id")
private List deadlines = new ArrayList<>();
+ @ManyToOne(cascade = CascadeType.ALL)
+ @JoinColumn(name = "grant_id")
+ private Grant grant;
+
+ @NotNull
+ private String repository;
+
+ @ManyToOne
+ @JoinColumn(name = "file_id")
+ private FileData application;
+
public String getTitle() {
return title;
}
@@ -29,6 +70,38 @@ public class Project extends BaseEntity {
this.title = title;
}
+ public ProjectStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(ProjectStatus status) {
+ this.status = status;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Grant getGrant() {
+ return grant;
+ }
+
+ public void setGrant(Grant grant) {
+ this.grant = grant;
+ }
+
+ public String getRepository() {
+ return repository;
+ }
+
+ public void setRepository(String repository) {
+ this.repository = repository;
+ }
+
public List getDeadlines() {
return deadlines;
}
@@ -36,4 +109,12 @@ public class Project extends BaseEntity {
public void setDeadlines(List deadlines) {
this.deadlines = deadlines;
}
+
+ public FileData getApplication() {
+ return application;
+ }
+
+ public void setApplication(FileData application) {
+ this.application = application;
+ }
}
diff --git a/src/main/java/ru/ulstu/project/model/ProjectDto.java b/src/main/java/ru/ulstu/project/model/ProjectDto.java
index fdce26b..d9e60ab 100644
--- a/src/main/java/ru/ulstu/project/model/ProjectDto.java
+++ b/src/main/java/ru/ulstu/project/model/ProjectDto.java
@@ -2,21 +2,24 @@ package ru.ulstu.project.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import org.hibernate.validator.constraints.NotEmpty;
-import ru.ulstu.deadline.model.DeadlineDto;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.grant.model.GrantDto;
+import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
-import static ru.ulstu.core.util.StreamApiUtils.convert;
-
public class ProjectDto {
private Integer id;
@NotEmpty
private String title;
-
- private List deadlines = new ArrayList<>();
+ private Project.ProjectStatus status;
+ private String description;
+ private List deadlines = new ArrayList<>();
+ private GrantDto grant;
+ private String repository;
+ private String applicationFileName;
public ProjectDto() {
}
@@ -28,17 +31,31 @@ public class ProjectDto {
@JsonCreator
public ProjectDto(@JsonProperty("id") Integer id,
@JsonProperty("title") String title,
- @JsonProperty("deadlines") List deadlines) {
+ @JsonProperty("status") Project.ProjectStatus status,
+ @JsonProperty("description") String description,
+ @JsonProperty("grant") GrantDto grant,
+ @JsonProperty("repository") String repository,
+ @JsonProperty("deadlines") List deadlines) {
this.id = id;
this.title = title;
+ this.status = status;
+ this.description = description;
+ this.grant = grant;
+ this.repository = repository;
this.deadlines = deadlines;
+ this.applicationFileName = null;
}
public ProjectDto(Project project) {
this.id = project.getId();
this.title = project.getTitle();
- this.deadlines = convert(project.getDeadlines(), DeadlineDto::new);
+ this.status = project.getStatus();
+ this.description = project.getDescription();
+ this.applicationFileName = project.getApplication() == null ? null : project.getApplication().getName();
+ this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant());
+ this.repository = project.getRepository();
+ this.deadlines = project.getDeadlines();
}
public Integer getId() {
@@ -57,11 +74,51 @@ public class ProjectDto {
this.title = title;
}
- public List getDeadlines() {
+ public Project.ProjectStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(Project.ProjectStatus status) {
+ this.status = status;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public GrantDto getGrant() {
+ return grant;
+ }
+
+ public void setGrant(GrantDto grant) {
+ this.grant = grant;
+ }
+
+ public String getRepository() {
+ return repository;
+ }
+
+ public void setRepository(String repository) {
+ this.repository = repository;
+ }
+
+ public List getDeadlines() {
return deadlines;
}
- public void setDeadlines(List deadlines) {
+ public void setDeadlines(List deadlines) {
this.deadlines = deadlines;
}
+
+ public String getApplicationFileName() {
+ return applicationFileName;
+ }
+
+ public void setApplicationFileName(String applicationFileName) {
+ this.applicationFileName = applicationFileName;
+ }
}
diff --git a/src/main/java/ru/ulstu/project/service/ProjectService.java b/src/main/java/ru/ulstu/project/service/ProjectService.java
index b54a60a..115f5ae 100644
--- a/src/main/java/ru/ulstu/project/service/ProjectService.java
+++ b/src/main/java/ru/ulstu/project/service/ProjectService.java
@@ -2,45 +2,82 @@ 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.file.service.FileService;
+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 java.io.IOException;
+import java.util.Arrays;
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;
@Service
public class ProjectService {
+ private final static int MAX_DISPLAY_SIZE = 40;
private final ProjectRepository projectRepository;
private final DeadlineService deadlineService;
+ private final GrantRepository grantRepository;
+ private final FileService fileService;
public ProjectService(ProjectRepository projectRepository,
- DeadlineService deadlineService) {
+ DeadlineService deadlineService,
+ GrantRepository grantRepository,
+ FileService fileService) {
this.projectRepository = projectRepository;
this.deadlineService = deadlineService;
+ this.grantRepository = grantRepository;
+ this.fileService = fileService;
}
public List findAll() {
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;
+ }
+
+ public ProjectDto findOneDto(Integer id) {
+ return new ProjectDto(projectRepository.getOne(id));
+ }
+
+ public List getProjectStatuses() {
+ return Arrays.asList(Project.ProjectStatus.values());
+ }
+
@Transactional
- public Project create(ProjectDto projectDto) {
+ public Project create(ProjectDto projectDto) throws IOException {
Project newProject = copyFromDto(new Project(), projectDto);
newProject = projectRepository.save(newProject);
return newProject;
}
- private Project copyFromDto(Project project, ProjectDto projectDto) {
+ private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException {
+ project.setDescription(projectDto.getDescription());
+ project.setStatus(projectDto.getStatus() == null ? APPLICATION : projectDto.getStatus());
project.setTitle(projectDto.getTitle());
+ if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) {
+ project.setGrant(grantRepository.getOne(projectDto.getGrant().getId()));
+ }
+ project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
+ if (projectDto.getApplicationFileName() != null) {
+ project.setApplication(fileService.createFileFromTmp(projectDto.getApplicationFileName()));
+ }
return project;
}
- public Project save(ProjectDto projectDto) {
+ public Project save(ProjectDto projectDto) throws IOException {
if (isEmpty(projectDto.getId())) {
return create(projectDto);
} else {
@@ -53,7 +90,7 @@ public class ProjectService {
}
public Project findById(Integer id) {
- return projectRepository.findOne(id);
+ return projectRepository.getOne(id);
}
}
diff --git a/src/main/java/ru/ulstu/students/controller/Navigation.java b/src/main/java/ru/ulstu/students/controller/Navigation.java
new file mode 100644
index 0000000..3804a8b
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/controller/Navigation.java
@@ -0,0 +1,16 @@
+package ru.ulstu.students.controller;
+
+import org.springframework.validation.Errors;
+
+public class Navigation {
+ public static final String REDIRECT_TO = "redirect:%s";
+ public static final String TASKS_PAGE = "/students/tasks";
+ public static final String TASK_PAGE = "/students/task";
+
+ public static String hasErrors(Errors errors, String page) {
+ if (errors.hasErrors()) {
+ return page;
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/ru/ulstu/students/controller/TaskController.java b/src/main/java/ru/ulstu/students/controller/TaskController.java
new file mode 100644
index 0000000..50cb052
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/controller/TaskController.java
@@ -0,0 +1,90 @@
+package ru.ulstu.students.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.ModelMap;
+import org.springframework.validation.Errors;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.students.model.Task;
+import ru.ulstu.students.model.TaskDto;
+import ru.ulstu.students.service.TaskService;
+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.students.controller.Navigation.REDIRECT_TO;
+import static ru.ulstu.students.controller.Navigation.TASKS_PAGE;
+import static ru.ulstu.students.controller.Navigation.TASK_PAGE;
+
+@Controller()
+@RequestMapping(value = "/students")
+@ApiIgnore
+public class TaskController {
+
+ private final TaskService taskService;
+
+ public TaskController(TaskService taskService) {
+ this.taskService = taskService;
+ }
+
+ @GetMapping("/tasks")
+ public void getTasks(ModelMap modelMap) {
+ modelMap.put("tasks", taskService.findAllDto());
+ }
+
+ @GetMapping("/dashboard")
+ public void getDashboard(ModelMap modelMap) {
+ modelMap.put("tasks", taskService.findAllDto());
+ }
+
+ @GetMapping("/task")
+ public void getTask(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
+ if (id != null && id > 0) {
+ modelMap.put("taskDto", taskService.findOneDto(id));
+ } else {
+ modelMap.put("taskDto", new TaskDto());
+ }
+ }
+
+ @PostMapping(value = "/task", params = "save")
+ public String save(@Valid TaskDto taskDto, Errors errors) throws IOException {
+ filterEmptyDeadlines(taskDto);
+ if (taskDto.getDeadlines().isEmpty()) {
+ errors.rejectValue("deadlines", "errorCode", "Не может быть пустым");
+ }
+ if (errors.hasErrors()) {
+ return TASK_PAGE;
+ }
+ taskService.save(taskDto);
+ return String.format(REDIRECT_TO, TASKS_PAGE);
+ }
+
+ @PostMapping(value = "/task", params = "addDeadline")
+ public String addDeadline(@Valid TaskDto taskDto, Errors errors) {
+ filterEmptyDeadlines(taskDto);
+ if (errors.hasErrors()) {
+ return TASK_PAGE;
+ }
+ taskDto.getDeadlines().add(new Deadline());
+ return TASK_PAGE;
+ }
+
+ @ModelAttribute("allStatuses")
+ public List getTaskStatuses() {
+ return taskService.getTaskStatuses();
+ }
+
+ private void filterEmptyDeadlines(TaskDto taskDto) {
+ taskDto.setDeadlines(taskDto.getDeadlines().stream()
+ .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
+ .collect(Collectors.toList()));
+ }
+}
diff --git a/src/main/java/ru/ulstu/students/model/Task.java b/src/main/java/ru/ulstu/students/model/Task.java
new file mode 100644
index 0000000..5646ef3
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/model/Task.java
@@ -0,0 +1,130 @@
+package ru.ulstu.students.model;
+
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
+import ru.ulstu.core.model.BaseEntity;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.tags.model.Tag;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinTable;
+import javax.persistence.ManyToMany;
+import javax.persistence.OneToMany;
+import javax.persistence.OrderBy;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
+import javax.validation.constraints.NotBlank;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+@Entity
+public class Task extends BaseEntity {
+
+ public enum TaskStatus {
+ IN_WORK("В работе"),
+ COMPLETED("Завершен"),
+ FAILED("Провалены сроки"),
+ LOADED_FROM_KIAS("Загружен автоматически");
+
+ private String statusName;
+
+ TaskStatus(String name) {
+ this.statusName = name;
+ }
+
+ public String getStatusName() {
+ return statusName;
+ }
+ }
+
+ @NotBlank
+ private String title;
+
+ private String description;
+
+ @Enumerated(value = EnumType.STRING)
+ private ru.ulstu.students.model.Task.TaskStatus status = TaskStatus.IN_WORK;
+
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @JoinColumn(name = "task_id", unique = true)
+ @Fetch(FetchMode.SUBSELECT)
+ @OrderBy("date")
+ private List deadlines = new ArrayList<>();
+
+ @Column(name = "create_date")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date createDate = new Date();
+
+ @Column(name = "update_date")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date updateDate = new Date();
+
+ @ManyToMany(fetch = FetchType.EAGER)
+ @JoinTable(name = "task_tags",
+ joinColumns = {@JoinColumn(name = "task_id")},
+ inverseJoinColumns = {@JoinColumn(name = "tag_id")})
+ private List tags = new ArrayList<>();
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public TaskStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(TaskStatus status) {
+ this.status = status;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public List getDeadlines() {
+ return deadlines;
+ }
+
+ public void setDeadlines(List deadlines) {
+ this.deadlines = deadlines;
+ }
+
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+
+ public Date getUpdateDate() {
+ return updateDate;
+ }
+
+ public void setUpdateDate(Date updateDate) {
+ this.updateDate = updateDate;
+ }
+
+ public List getTags() {
+ return tags;
+ }
+
+ public void setTags(List tags) {
+ this.tags = tags;
+ }
+}
diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java
new file mode 100644
index 0000000..5071dab
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/model/TaskDto.java
@@ -0,0 +1,144 @@
+package ru.ulstu.students.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.commons.lang3.StringUtils;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.tags.model.Tag;
+
+import javax.validation.constraints.NotEmpty;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class TaskDto {
+
+ private final static int MAX_TAGS_LENGTH = 50;
+
+ private Integer id;
+ @NotEmpty
+ private String title;
+ private String description;
+ private Task.TaskStatus status;
+ private List deadlines = new ArrayList<>();
+ private Date createDate;
+ private Date updateDate;
+ private Set tagIds;
+ private List tags;
+
+ public TaskDto() {
+ deadlines.add(new Deadline());
+ }
+
+ @JsonCreator
+ public TaskDto(@JsonProperty("id") Integer id,
+ @JsonProperty("title") String title,
+ @JsonProperty("description") String description,
+ @JsonProperty("createDate") Date createDate,
+ @JsonProperty("updateDate") Date updateDate,
+ @JsonProperty("status") Task.TaskStatus status,
+ @JsonProperty("deadlines") List deadlines,
+ @JsonProperty("tagIds") Set tagIds,
+ @JsonProperty("tags") List tags) {
+ this.id = id;
+ this.title = title;
+ this.status = status;
+ this.deadlines = deadlines;
+ this.createDate = createDate;
+ this.updateDate = updateDate;
+ this.description = description;
+ this.tags = tags;
+ }
+
+ public TaskDto(Task task) {
+ this.id = task.getId();
+ this.title = task.getTitle();
+ this.status = task.getStatus();
+ this.deadlines = task.getDeadlines();
+ this.createDate = task.getCreateDate();
+ this.updateDate = task.getUpdateDate();
+ this.description = task.getDescription();
+ this.tags = task.getTags();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public Task.TaskStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(Task.TaskStatus status) {
+ this.status = status;
+ }
+
+ public List getDeadlines() {
+ return deadlines;
+ }
+
+ public void setDeadlines(List deadlines) {
+ this.deadlines = deadlines;
+ }
+
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+
+ public Date getUpdateDate() {
+ return updateDate;
+ }
+
+ public void setUpdateDate(Date updateDate) {
+ this.updateDate = updateDate;
+ }
+
+ public Set getTagIds() {
+ return tagIds;
+ }
+
+ public void setTagIds(Set tagIds) {
+ this.tagIds = tagIds;
+ }
+
+ public List getTags() {
+ return tags;
+ }
+
+ public void setTags(List tags) {
+ this.tags = tags;
+ }
+
+ public String getTagsString() {
+ return StringUtils.abbreviate(tags
+ .stream()
+ .map(tag -> tag.getTagName())
+ .collect(Collectors.joining(", ")), MAX_TAGS_LENGTH);
+ }
+}
diff --git a/src/main/java/ru/ulstu/students/repository/TaskRepository.java b/src/main/java/ru/ulstu/students/repository/TaskRepository.java
new file mode 100644
index 0000000..6f48d1f
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/repository/TaskRepository.java
@@ -0,0 +1,7 @@
+package ru.ulstu.students.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import ru.ulstu.students.model.Task;
+
+public interface TaskRepository extends JpaRepository {
+}
diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java
new file mode 100644
index 0000000..dac6ef5
--- /dev/null
+++ b/src/main/java/ru/ulstu/students/service/TaskService.java
@@ -0,0 +1,95 @@
+package ru.ulstu.students.service;
+
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import ru.ulstu.deadline.service.DeadlineService;
+import ru.ulstu.students.model.Task;
+import ru.ulstu.students.model.TaskDto;
+import ru.ulstu.students.repository.TaskRepository;
+import ru.ulstu.tags.service.TagService;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import static org.springframework.util.ObjectUtils.isEmpty;
+import static ru.ulstu.core.util.StreamApiUtils.convert;
+import static ru.ulstu.students.model.Task.TaskStatus.IN_WORK;
+
+@Service
+public class TaskService {
+
+ private final static int MAX_DISPLAY_SIZE = 40;
+
+ private final TaskRepository taskRepository;
+ private final DeadlineService deadlineService;
+ private final TagService tagService;
+
+ public TaskService(TaskRepository grantRepository,
+ DeadlineService deadlineService, TagService tagService) {
+ this.taskRepository = grantRepository;
+ this.deadlineService = deadlineService;
+ this.tagService = tagService;
+ }
+
+ public List findAll() {
+ return taskRepository.findAll();
+ }
+
+ public List findAllDto() {
+ List tasks = convert(findAll(), TaskDto::new);
+ tasks.forEach(taskDto -> taskDto.setTitle(StringUtils.abbreviate(taskDto.getTitle(), MAX_DISPLAY_SIZE)));
+ return tasks;
+ }
+
+ public TaskDto findOneDto(Integer id) {
+ return new TaskDto(taskRepository.getOne(id));
+ }
+
+ @Transactional
+ public Integer create(TaskDto taskDto) throws IOException {
+ Task newTask = copyFromDto(new Task(), taskDto);
+ newTask = taskRepository.save(newTask);
+ return newTask.getId();
+ }
+
+ private Task copyFromDto(Task task, TaskDto taskDto) throws IOException {
+ task.setTitle(taskDto.getTitle());
+ task.setDescription(taskDto.getDescription());
+ task.setStatus(taskDto.getStatus() == null ? IN_WORK : taskDto.getStatus());
+ task.setDeadlines(deadlineService.saveOrCreate(taskDto.getDeadlines()));
+ task.setCreateDate(task.getCreateDate() == null ? new Date() : task.getCreateDate());
+ task.setUpdateDate(new Date());
+ task.getTags().clear();
+ task.setTags(tagService.saveOrCreate(taskDto.getTags()));
+ return task;
+ }
+
+ @Transactional
+ public Integer update(TaskDto taskDto) throws IOException {
+ Task task = taskRepository.getOne(taskDto.getId());
+ taskRepository.save(copyFromDto(task, taskDto));
+ return task.getId();
+ }
+
+ @Transactional
+ public void delete(Integer taskId) throws IOException {
+ Task task = taskRepository.getOne(taskId);
+ taskRepository.delete(task);
+ }
+
+ public void save(TaskDto taskDto) throws IOException {
+ if (isEmpty(taskDto.getId())) {
+ create(taskDto);
+ } else {
+ update(taskDto);
+ }
+ }
+
+ public List getTaskStatuses() {
+ return Arrays.asList(Task.TaskStatus.values());
+ }
+
+}
diff --git a/src/main/java/ru/ulstu/tags/model/Tag.java b/src/main/java/ru/ulstu/tags/model/Tag.java
new file mode 100644
index 0000000..460e9b0
--- /dev/null
+++ b/src/main/java/ru/ulstu/tags/model/Tag.java
@@ -0,0 +1,44 @@
+package ru.ulstu.tags.model;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import ru.ulstu.core.model.BaseEntity;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Table;
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.Size;
+
+@Entity
+@Table(name = "tag")
+public class Tag extends BaseEntity {
+
+ @NotEmpty
+ @Size(max = 50)
+ @Column(name = "tag_name")
+ private String tagName;
+
+ public Tag() {
+
+ }
+
+ @JsonCreator
+ public Tag(@JsonProperty("id") Integer id,
+ @JsonProperty("tag_name") String tagName) {
+ this.setId(id);
+ this.tagName = tagName;
+ }
+
+ public Tag(String name) {
+ this.tagName = name;
+ }
+
+ public String getTagName() {
+ return tagName;
+ }
+
+ public void setTagName(String tagName) {
+ this.tagName = tagName;
+ }
+}
diff --git a/src/main/java/ru/ulstu/tags/repository/TagRepository.java b/src/main/java/ru/ulstu/tags/repository/TagRepository.java
new file mode 100644
index 0000000..213abae
--- /dev/null
+++ b/src/main/java/ru/ulstu/tags/repository/TagRepository.java
@@ -0,0 +1,12 @@
+package ru.ulstu.tags.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.tags.model.Tag;
+
+public interface TagRepository extends JpaRepository {
+
+ @Query("SELECT t FROM Tag t WHERE (t.tagName = :tagName)")
+ Tag findByName(@Param("tagName") String tagName);
+}
diff --git a/src/main/java/ru/ulstu/tags/service/TagService.java b/src/main/java/ru/ulstu/tags/service/TagService.java
new file mode 100644
index 0000000..ad5d227
--- /dev/null
+++ b/src/main/java/ru/ulstu/tags/service/TagService.java
@@ -0,0 +1,53 @@
+package ru.ulstu.tags.service;
+
+import org.springframework.stereotype.Service;
+import ru.ulstu.tags.model.Tag;
+import ru.ulstu.tags.repository.TagRepository;
+
+import javax.transaction.Transactional;
+import java.util.List;
+import java.util.stream.Collectors;
+
+@Service
+public class TagService {
+
+ private final TagRepository tagRepository;
+
+
+ public TagService(TagRepository tagRepository) {
+
+ this.tagRepository = tagRepository;
+ }
+
+ public List saveOrCreate(List tags) {
+ return tags
+ .stream()
+ .map(tag -> {
+ if (tag.getId() != null) {
+ return getExistById(tag);
+ } else {
+ Tag existTag = isExistByName(tag.getTagName());
+ return existTag != null ? existTag : create(tag);
+ }
+ }).collect(Collectors.toList());
+ }
+
+ @Transactional
+ public Tag getExistById(Tag tag) {
+ return tagRepository.getOne(tag.getId());
+ }
+
+ @Transactional
+ public Tag isExistByName(String tagName) {
+ return tagRepository.findByName(tagName);
+ }
+
+ @Transactional
+ public Tag create(Tag tag) {
+ Tag newTag = new Tag();
+ newTag.setTagName(tag.getTagName());
+ newTag = tagRepository.save(newTag);
+ return newTag;
+ }
+
+}
diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java
index 290f136..f8fd179 100644
--- a/src/main/java/ru/ulstu/timeline/model/Event.java
+++ b/src/main/java/ru/ulstu/timeline/model/Event.java
@@ -1,7 +1,7 @@
package ru.ulstu.timeline.model;
-import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
+import ru.ulstu.paper.model.Paper;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
@@ -16,6 +16,7 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
@@ -71,6 +72,10 @@ public class Event extends BaseEntity {
@JoinColumn(name = "child_id")
private List parents;
+ @ManyToOne
+ @JoinColumn(name = "paper_id")
+ private Paper paper;
+
public String getTitle() {
return title;
}
@@ -150,4 +155,12 @@ public class Event extends BaseEntity {
public void setParents(List parents) {
this.parents = parents;
}
+
+ public Paper getPaper() {
+ return paper;
+ }
+
+ public void setPaper(Paper paper) {
+ this.paper = paper;
+ }
}
diff --git a/src/main/java/ru/ulstu/timeline/model/EventDto.java b/src/main/java/ru/ulstu/timeline/model/EventDto.java
index 9e70a9d..17e4623 100644
--- a/src/main/java/ru/ulstu/timeline/model/EventDto.java
+++ b/src/main/java/ru/ulstu/timeline/model/EventDto.java
@@ -2,7 +2,8 @@ package ru.ulstu.timeline.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import org.hibernate.validator.constraints.NotBlank;
+import javax.validation.constraints.NotBlank;
+import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotNull;
@@ -23,6 +24,7 @@ public class EventDto {
private final Date updateDate;
private final String description;
private final List recipients;
+ private PaperDto paperDto;
@JsonCreator
public EventDto(@JsonProperty("id") Integer id,
@@ -33,6 +35,7 @@ public class EventDto {
@JsonProperty("createDate") Date createDate,
@JsonProperty("updateDate") Date updateDate,
@JsonProperty("description") String description,
+ @JsonProperty("paperDto") PaperDto paperDto,
@JsonProperty("recipients") List recipients) {
this.id = id;
this.title = title;
@@ -43,6 +46,7 @@ public class EventDto {
this.updateDate = updateDate;
this.description = description;
this.recipients = recipients;
+ this.paperDto = paperDto;
}
public EventDto(Event event) {
@@ -54,6 +58,7 @@ public class EventDto {
this.createDate = event.getCreateDate();
this.updateDate = event.getUpdateDate();
this.description = event.getDescription();
+ this.paperDto = new PaperDto(event.getPaper());
this.recipients = convert(event.getRecipients(), UserDto::new);
}
@@ -92,4 +97,12 @@ public class EventDto {
public Date getExecuteDate() {
return executeDate;
}
+
+ public PaperDto getPaperDto() {
+ return paperDto;
+ }
+
+ public void setPaperDto(PaperDto paperDto) {
+ this.paperDto = paperDto;
+ }
}
diff --git a/src/main/java/ru/ulstu/timeline/model/Timeline.java b/src/main/java/ru/ulstu/timeline/model/Timeline.java
index 8e588cb..06e04bc 100644
--- a/src/main/java/ru/ulstu/timeline/model/Timeline.java
+++ b/src/main/java/ru/ulstu/timeline/model/Timeline.java
@@ -6,6 +6,7 @@ import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
+import java.util.ArrayList;
import java.util.List;
@Entity
@@ -13,7 +14,7 @@ public class Timeline extends BaseEntity {
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "timeline_id")
- private List events;
+ private List events = new ArrayList<>();
public List getEvents() {
return events;
diff --git a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java
index 4848e12..eb5c08b 100644
--- a/src/main/java/ru/ulstu/timeline/repository/EventRepository.java
+++ b/src/main/java/ru/ulstu/timeline/repository/EventRepository.java
@@ -2,6 +2,7 @@ package ru.ulstu.timeline.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
+import ru.ulstu.paper.model.Paper;
import ru.ulstu.timeline.model.Event;
import java.util.List;
@@ -12,4 +13,6 @@ public interface EventRepository extends JpaRepository {
@Query("SELECT e FROM Event e WHERE e.executeDate > CURRENT_DATE ORDER BY e.executeDate")
List findAllFuture();
+
+ List findAllByPaper(Paper paper);
}
diff --git a/src/main/java/ru/ulstu/timeline/service/EventScheduler.java b/src/main/java/ru/ulstu/timeline/service/EventScheduler.java
index 6df7fcb..7899aca 100644
--- a/src/main/java/ru/ulstu/timeline/service/EventScheduler.java
+++ b/src/main/java/ru/ulstu/timeline/service/EventScheduler.java
@@ -34,6 +34,10 @@ public class EventScheduler {
Map variables = ImmutableMap.of("description", event.getDescription());
event.getRecipients()
.forEach(recipient -> mailService.sendEmailFromTemplate(variables, recipient, "eventNotification", event.getTitle()));
+ if (event.getPeriod() == null) {
+ event.setStatus(Event.EventStatus.COMPLETED);
+ eventService.save(event);
+ }
});
}
diff --git a/src/main/java/ru/ulstu/timeline/service/EventService.java b/src/main/java/ru/ulstu/timeline/service/EventService.java
index ca95b9a..a1f54f5 100644
--- a/src/main/java/ru/ulstu/timeline/service/EventService.java
+++ b/src/main/java/ru/ulstu/timeline/service/EventService.java
@@ -1,15 +1,22 @@
package ru.ulstu.timeline.service;
+import org.apache.commons.lang3.time.DateUtils;
+import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.paper.model.Paper;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.timeline.model.EventDto;
+import ru.ulstu.timeline.model.Timeline;
import ru.ulstu.timeline.repository.EventRepository;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.UserService;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
+import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert;
@@ -17,11 +24,14 @@ import static ru.ulstu.core.util.StreamApiUtils.convert;
public class EventService {
private final EventRepository eventRepository;
+ private final TimelineService timelineService;
private final UserService userService;
public EventService(EventRepository eventRepository,
+ @Lazy TimelineService timelineService,
UserService userService) {
this.eventRepository = eventRepository;
+ this.timelineService = timelineService;
this.userService = userService;
}
@@ -52,19 +62,24 @@ public class EventService {
@Transactional
public Integer update(EventDto eventDto) {
- Event event = eventRepository.findOne(eventDto.getId());
+ Event event = eventRepository.getOne(eventDto.getId());
return eventRepository.save(copyFromDto(event, eventDto)).getId();
}
+ @Transactional
+ public Event save(Event event) {
+ return eventRepository.save(event);
+ }
+
@Transactional
public void delete(Integer eventId) {
- Event event = eventRepository.findOne(eventId);
+ Event event = eventRepository.getOne(eventId);
event.setParents(null);
eventRepository.delete(event);
}
public List findByIds(List ids) {
- return eventRepository.findAll(ids);
+ return eventRepository.findAllById(ids);
}
public void createBasedOn(Event event, Date executeDate) {
@@ -79,11 +94,41 @@ public class EventService {
event = eventRepository.save(event);
//set child to parent
- Event parentEvent = eventRepository.findOne(parentEventId);
+ Event parentEvent = eventRepository.getOne(parentEventId);
parentEvent.setChild(event);
eventRepository.save(parentEvent);
}
+ public void createFromPaper(Paper newPaper) {
+ List timelines = timelineService.findAll();
+ Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
+
+ for (Deadline deadline : newPaper.getDeadlines()
+ .stream()
+ .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
+ .collect(Collectors.toList())) {
+ Event newEvent = new Event();
+ newEvent.setTitle("Дедлайн статьи");
+ newEvent.setStatus(Event.EventStatus.NEW);
+ newEvent.setExecuteDate(deadline.getDate());
+ newEvent.setCreateDate(new Date());
+ newEvent.setUpdateDate(new Date());
+ 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);
+ }
+ }
+
+ public void updatePaperDeadlines(Paper paper) {
+ eventRepository.deleteAll(eventRepository.findAllByPaper(paper));
+
+ createFromPaper(paper);
+ }
+
public List findByCurrentDate() {
return eventRepository.findByCurrentDate();
}
diff --git a/src/main/java/ru/ulstu/timeline/service/TimelineService.java b/src/main/java/ru/ulstu/timeline/service/TimelineService.java
index 94388ee..dd5c384 100644
--- a/src/main/java/ru/ulstu/timeline/service/TimelineService.java
+++ b/src/main/java/ru/ulstu/timeline/service/TimelineService.java
@@ -23,15 +23,24 @@ public class TimelineService {
this.eventService = eventService;
}
- public List findAll() {
+ public List findAllDto() {
return convert(timelineRepository.findAll(), TimelineDto::new);
}
+ public List findAll() {
+ return timelineRepository.findAll();
+ }
+
@Transactional
public int create(TimelineDto timelineDto) {
return timelineRepository.save(copyFromDto(new Timeline(), timelineDto)).getId();
}
+ @Transactional
+ public Timeline save(Timeline timeline) {
+ return timelineRepository.save(timeline);
+ }
+
private Timeline copyFromDto(Timeline timeline, TimelineDto timelineDto) {
timeline.setEvents(eventService.findByIds(convert(timelineDto.getEvents(), EventDto::getId)));
return timeline;
@@ -39,13 +48,13 @@ public class TimelineService {
@Transactional
public Integer update(TimelineDto timelineDto) {
- Timeline timeline = timelineRepository.findOne(timelineDto.getId());
+ Timeline timeline = timelineRepository.getOne(timelineDto.getId());
return timelineRepository.save(copyFromDto(timeline, timelineDto)).getId();
}
@Transactional
public void delete(Integer timelineId) {
- Timeline timeline = timelineRepository.findOne(timelineId);
+ Timeline timeline = timelineRepository.getOne(timelineId);
timelineRepository.delete(timeline);
}
}
diff --git a/src/main/java/ru/ulstu/user/model/User.java b/src/main/java/ru/ulstu/user/model/User.java
index 16a873b..fcfd88e 100644
--- a/src/main/java/ru/ulstu/user/model/User.java
+++ b/src/main/java/ru/ulstu/user/model/User.java
@@ -1,18 +1,20 @@
package ru.ulstu.user.model;
import org.hibernate.annotations.BatchSize;
-import org.hibernate.validator.constraints.Email;
import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@@ -24,6 +26,8 @@ import java.util.Set;
@Entity
@Table(name = "users")
public class User extends BaseEntity {
+ private final static String USER_ABBREVIATE_TEMPLATE = "%s %s%s";
+
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@@ -45,6 +49,10 @@ public class User extends BaseEntity {
@Column(name = "last_name", length = 50, nullable = false)
private String lastName;
+ @Size(max = 50)
+ @Column(name = "patronymic", length = 50)
+ private String patronymic;
+
@NotNull
@Email
@Size(min = 5, max = 100)
@@ -79,6 +87,28 @@ public class User extends BaseEntity {
@BatchSize(size = 20)
private Set roles;
+ @Column(name = "birth_date")
+ @Temporal(TemporalType.TIMESTAMP)
+ private Date birthDate;
+
+ public enum UserDegree {
+ CANDIDATE("Кандидат технических наук"),
+ DOCTOR("Доктор технических наук");
+
+ private String degreeName;
+
+ UserDegree(String degreeName) {
+ this.degreeName = degreeName;
+ }
+
+ public String getDegreeName() {
+ return degreeName;
+ }
+ }
+
+ @Enumerated(value = EnumType.STRING)
+ private UserDegree degree;
+
public User() {
roles = new HashSet<>();
activated = false;
@@ -174,4 +204,35 @@ public class User extends BaseEntity {
this.roles.clear();
this.roles.addAll(roles);
}
+
+ public String getPatronymic() {
+ return patronymic;
+ }
+
+ public void setPatronymic(String patronymic) {
+ this.patronymic = patronymic;
+ }
+
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ public UserDegree getDegree() {
+ return degree;
+ }
+
+ public void setDegree(UserDegree degree) {
+ this.degree = degree;
+ }
+
+ public String getUserAbbreviate() {
+ return String.format(USER_ABBREVIATE_TEMPLATE,
+ lastName == null ? "" : lastName,
+ firstName == null ? "" : firstName.substring(0, 1) + ".",
+ patronymic == null ? "" : patronymic.substring(0, 1) + ".");
+ }
}
diff --git a/src/main/java/ru/ulstu/user/model/UserDto.java b/src/main/java/ru/ulstu/user/model/UserDto.java
index c98e0bb..c3f8502 100644
--- a/src/main/java/ru/ulstu/user/model/UserDto.java
+++ b/src/main/java/ru/ulstu/user/model/UserDto.java
@@ -1,8 +1,6 @@
package ru.ulstu.user.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import org.hibernate.validator.constraints.Email;
-import org.hibernate.validator.constraints.NotBlank;
import org.springframework.util.StringUtils;
import ru.ulstu.configuration.Constants;
import ru.ulstu.odin.model.OdinDto;
@@ -12,9 +10,12 @@ import ru.ulstu.odin.model.annotation.OdinString;
import ru.ulstu.odin.model.annotation.OdinVisible;
import ru.ulstu.user.controller.UserController;
+import javax.validation.constraints.Email;
+import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Collection;
+import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
@@ -70,6 +71,10 @@ public class UserDto implements OdinDto {
@Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50)
private String passwordConfirm;
+ private Date birthDate;
+
+ private User.UserDegree degree;
+
public UserDto() {
activated = false;
roles = new LinkedHashSet<>();
@@ -86,6 +91,8 @@ public class UserDto implements OdinDto {
this.roles.addAll(user.getRoles().stream()
.map(UserRoleDto::new)
.collect(Collectors.toList()));
+ this.birthDate = user.getBirthDate();
+ this.degree = user.getDegree();
}
public Integer getId() {
@@ -163,6 +170,22 @@ public class UserDto implements OdinDto {
return passwordConfirm;
}
+ public Date getBirthDate() {
+ return birthDate;
+ }
+
+ public void setBirthDate(Date birthDate) {
+ this.birthDate = birthDate;
+ }
+
+ public User.UserDegree getDegree() {
+ return degree;
+ }
+
+ public void setDegree(User.UserDegree degree) {
+ this.degree = degree;
+ }
+
@JsonIgnore
public boolean isPasswordsValid() {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordConfirm)) {
@@ -188,6 +211,8 @@ public class UserDto implements OdinDto {
", roles=" + roles +
", password='" + password + '\'' +
", passwordConfirm='" + passwordConfirm + '\'' +
+ ", birthDate='" + birthDate + '\'' +
+ ", degree='" + degree + '\'' +
'}';
}
}
diff --git a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java
index 33d84bc..6da2813 100644
--- a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java
+++ b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java
@@ -1,8 +1,8 @@
package ru.ulstu.user.model;
-import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.configuration.Constants;
+import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.Objects;
diff --git a/src/main/java/ru/ulstu/user/model/UserSession.java b/src/main/java/ru/ulstu/user/model/UserSession.java
index 1eb761d..50fec65 100644
--- a/src/main/java/ru/ulstu/user/model/UserSession.java
+++ b/src/main/java/ru/ulstu/user/model/UserSession.java
@@ -2,7 +2,13 @@ package ru.ulstu.user.model;
import ru.ulstu.core.model.BaseEntity;
-import javax.persistence.*;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.Date;
diff --git a/src/main/java/ru/ulstu/user/repository/UserRepository.java b/src/main/java/ru/ulstu/user/repository/UserRepository.java
index 2edc8aa..afcdd69 100644
--- a/src/main/java/ru/ulstu/user/repository/UserRepository.java
+++ b/src/main/java/ru/ulstu/user/repository/UserRepository.java
@@ -2,6 +2,8 @@ package ru.ulstu.user.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
import ru.ulstu.user.model.User;
import java.util.Date;
@@ -25,4 +27,11 @@ public interface UserRepository extends JpaRepository {
@EntityGraph(attributePaths = "roles")
User findOneWithRolesByLogin(String login);
+
+ @Query("SELECT u FROM User u " +
+ "WHERE (YEAR(CURRENT_DATE) - YEAR(u.birthDate) < 35 OR :hasAge = FALSE) " +
+ "AND (u.degree = 'CANDIDATE' OR :hasDegree = FALSE)" +
+ "ORDER BY u.lastName")
+ List filterByAgeAndDegree(@Param("hasAge") boolean hasAge,
+ @Param("hasDegree") boolean hasDegree);
}
diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java
index da1da6d..77be5e7 100644
--- a/src/main/java/ru/ulstu/user/service/MailService.java
+++ b/src/main/java/ru/ulstu/user/service/MailService.java
@@ -8,7 +8,7 @@ import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
-import org.thymeleaf.spring4.SpringTemplateEngine;
+import org.thymeleaf.spring5.SpringTemplateEngine;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.configuration.Constants;
import ru.ulstu.user.model.User;
@@ -19,11 +19,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;
diff --git a/src/main/java/ru/ulstu/user/service/UserMapper.java b/src/main/java/ru/ulstu/user/service/UserMapper.java
index 7359bba..647754b 100644
--- a/src/main/java/ru/ulstu/user/service/UserMapper.java
+++ b/src/main/java/ru/ulstu/user/service/UserMapper.java
@@ -26,7 +26,7 @@ public class UserMapper {
public Set rolesFromDto(Set strings) {
return Optional.ofNullable(strings).orElse(Collections.emptySet()).stream()
.filter(Objects::nonNull)
- .map(role -> userRoleRepository.findOne(role.getId().toString()))
+ .map(role -> userRoleRepository.getOne(role.getId().toString()))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index d8d29a5..f92d2e3 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -1,318 +1,332 @@
-package ru.ulstu.user.service;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Sort;
-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.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 java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.List;
-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 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