Merge branch 'move-to-jdk11' into try-vue

# Conflicts:
#	src/main/java/ru/ulstu/configuration/MvcConfiguration.java
#	src/main/java/ru/ulstu/core/controller/AdviceController.java
#	src/main/java/ru/ulstu/paper/controller/PaperRestController.java
#	src/main/resources/static/papers/paper-status.vue
#	src/main/resources/templates/activate.html
#	src/main/resources/templates/admin/commits.html
#	src/main/resources/templates/admin/userList.html
#	src/main/resources/templates/admin/userSessions.html
#	src/main/resources/templates/conferences/conference.html
#	src/main/resources/templates/conferences/conferences.html
#	src/main/resources/templates/conferences/dashboard.html
#	src/main/resources/templates/default.html
#	src/main/resources/templates/error/403.html
#	src/main/resources/templates/error/404.html
#	src/main/resources/templates/error/500.html
#	src/main/resources/templates/grants/dashboard.html
#	src/main/resources/templates/grants/fragments/grantDashboardFragment.html
#	src/main/resources/templates/grants/fragments/grantLineFragment.html
#	src/main/resources/templates/grants/fragments/grantStatusFragment.html
#	src/main/resources/templates/grants/grant.html
#	src/main/resources/templates/grants/grants.html
#	src/main/resources/templates/index.html
#	src/main/resources/templates/load.html
#	src/main/resources/templates/login.html
#	src/main/resources/templates/papers/dashboard.html
#	src/main/resources/templates/papers/fragments/paperDashboardFragment.html
#	src/main/resources/templates/papers/fragments/paperLineFragment.html
#	src/main/resources/templates/papers/paper.html
#	src/main/resources/templates/papers/papers.html
#	src/main/resources/templates/projects/dashboard.html
#	src/main/resources/templates/projects/fragments/projectStatusFragment.html
#	src/main/resources/templates/projects/project.html
#	src/main/resources/templates/projects/projects.html
#	src/main/resources/templates/reset.html
#	src/main/resources/templates/resetRequest.html
#	src/main/resources/templates/timeline.html
pull/244/head
Anton Romanov 5 years ago
commit e7b84b766f

@ -1,16 +1,16 @@
image: romanov73/is:ng-tracker-container image: romanov73/is:ng-tracker-container-11
variables: variables:
GRADLE_OPTS: "-Dorg.gradle.daemon=false" GRADLE_OPTS: "-Dorg.gradle.daemon=false"
before_script: before_script:
- service postgresql stop - service postgresql stop
- service postgresql start - service postgresql start
- eval $(ssh-agent -s) - eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- mkdir -p ~/.ssh - mkdir -p ~/.ssh
- chmod 700 ~/.ssh - chmod 700 ~/.ssh
- git log --pretty="%cn;%cd;%s" > src/main/resources/commits.log - git log --pretty="%cn;%cd;%s" > src/main/resources/commits.log
build: build:
stage: build stage: build

@ -1,6 +1,6 @@
buildscript { buildscript {
ext { ext {
versionSpringBoot = '1.5.10.RELEASE' versionSpringBoot = '2.1.6.RELEASE'
} }
repositories { repositories {
@ -105,13 +105,14 @@ dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jetty' 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-data-jpa'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf' 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.module', name: 'jackson-module-afterburner'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5' 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: 'com.mattbertolini', name: 'liquibase-slf4j', version: '2.0.0'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7' compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
@ -129,8 +130,11 @@ dependencies {
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0' compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0'
compile group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.35.0'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1'
//testCompile group: 'com.google.guava', name: 'guava', version: '21.0'
testCompile group: 'org.mockito', name: 'mockito-all', version: '1.10.19'
} }

@ -18,6 +18,6 @@ fi
ssh $USERSERVER "cd /tmp && rm -rf $ARTIFACT_NAME*.jar && echo `date` 'killed' >> log_$ARTIFACT_NAME" ssh $USERSERVER "cd /tmp && rm -rf $ARTIFACT_NAME*.jar && echo `date` 'killed' >> log_$ARTIFACT_NAME"
scp build/libs/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar $USERSERVER:/tmp/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar scp build/libs/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar $USERSERVER:/tmp/$ARTIFACT_NAME-0.1.0-SNAPSHOT.jar
ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 --ng-tracker.dev-mode=false >> /home/user/logfile_$ARTIFACT_NAME" & ssh $USERSERVER -f "cd /tmp/ && /opt/jdk1.8.0_192/bin/java -jar $ARTIFACT_NAME-0.1.0-SNAPSHOT.jar -Xms 512m -Xmx 1024m --server.port=8443 --server.http.port=8080 --ng-tracker.base-url=http://193.110.3.124:8080 --ng-tracker.dev-mode=false --ng-tracker.driver-path=/home/user >> /home/user/logfile_$ARTIFACT_NAME" &
sleep 10 sleep 10
echo "is deployed" echo "is deployed"

@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists 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

@ -4,20 +4,17 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.commit.model.CommitListDto; import ru.ulstu.commit.model.CommitListDto;
import ru.ulstu.commit.service.CommitService; import ru.ulstu.commit.service.CommitService;
import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.core.model.response.Response; import ru.ulstu.core.model.response.Response;
import ru.ulstu.odin.controller.OdinController; import ru.ulstu.odin.controller.OdinController;
import ru.ulstu.odin.model.OdinVoid; import ru.ulstu.odin.model.OdinVoid;
import static ru.ulstu.commit.controller.CommitController.URL;
@RestController @RestController
@RequestMapping(URL) @RequestMapping(Constants.API_1_0 + "commits")
public class CommitController extends OdinController<CommitListDto, OdinVoid> { public class CommitController extends OdinController<CommitListDto, OdinVoid> {
public static final String URL = Constants.API_1_0 + "commits";
private final CommitService commitService; private final CommitService commitService;
public CommitController(CommitService commitService) { public CommitController(CommitService commitService) {

@ -2,14 +2,18 @@ package ru.ulstu.conference.model;
import org.hibernate.annotations.Fetch; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType; import javax.persistence.FetchType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
@ -20,15 +24,19 @@ import javax.persistence.OrderBy;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Entity @Entity
@Table(name = "conference") @Table(name = "conference")
public class Conference extends BaseEntity { @DiscriminatorValue("CONFERENCE")
public class Conference extends BaseEntity implements UserActivity, EventSource {
@NotBlank @NotBlank
private String title; private String title;
@ -71,6 +79,19 @@ public class Conference extends BaseEntity {
return title; return title;
} }
@Override
public List<User> getRecipients() {
List<User> list = new ArrayList<>();
getUsers().forEach(conferenceUser -> list.add(conferenceUser.getUser()));
return list;
}
@Override
public void addObjectToEvent(Event event) {
event.setConference(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -147,4 +168,9 @@ public class Conference extends BaseEntity {
.filter(d -> d.getDate().after(new Date())) .filter(d -> d.getDate().after(new Date()))
.findFirst(); .findFirst();
} }
@Override
public Set<User> getActivityUsers() {
return getUsers().stream().map(ConferenceUser::getUser).collect(Collectors.toSet());
}
} }

@ -2,14 +2,15 @@ package ru.ulstu.conference.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.name.NameContainer; import ru.ulstu.name.NameContainer;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -90,8 +91,8 @@ public class ConferenceDto extends NameContainer {
this.beginDate = conference.getBeginDate(); this.beginDate = conference.getBeginDate();
this.endDate = conference.getEndDate(); this.endDate = conference.getEndDate();
this.deadlines = conference.getDeadlines(); this.deadlines = conference.getDeadlines();
this.userIds = convert(conference.getUsers(), user -> user.getId()); this.userIds = convert(conference.getUsers(), BaseEntity::getId);
this.paperIds = convert(conference.getPapers(), paper -> paper.getId()); this.paperIds = convert(conference.getPapers(), BaseEntity::getId);
this.users = conference.getUsers(); this.users = conference.getUsers();
this.papers = conference.getPapers(); this.papers = conference.getPapers();
} }

@ -22,7 +22,7 @@ public class ConferenceUser extends BaseEntity {
INTRAMURAL("Очная"), INTRAMURAL("Очная"),
EXTRAMURAL("Заочная"); EXTRAMURAL("Заочная");
private String participationName; private final String participationName;
Participation(String name) { Participation(String name) {
this.participationName = name; this.participationName = name;
@ -38,7 +38,7 @@ public class ConferenceUser extends BaseEntity {
REPORT("Доклад"), REPORT("Доклад"),
PRESENTATION("Презентация"); PRESENTATION("Презентация");
private String depositName; private final String depositName;
Deposit(String name) { Deposit(String name) {
this.depositName = name; this.depositName = name;

@ -29,4 +29,8 @@ public interface ConferenceRepository extends JpaRepository<Conference, Integer>
@Override @Override
@Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ") @Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
@Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " +
"AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)")
Conference findActiveByUser(@Param("user") User user);
} }

@ -63,7 +63,7 @@ public class ConferenceNotificationService {
public void sendCreateNotification(Conference conference) { public void sendCreateNotification(Conference conference) {
Map<String, Object> variables = ImmutableMap.of("conference", conference); Map<String, Object> variables = ImmutableMap.of("conference", conference);
sendForAllUsers(variables, TEMPLATE_CREATE, String.format(TITLE_CREATE, conference.getTitle())); sendForAllUsers(variables, String.format(TITLE_CREATE, conference.getTitle()));
} }
public void updateDeadlineNotification(Conference conference) { public void updateDeadlineNotification(Conference conference) {
@ -76,8 +76,8 @@ public class ConferenceNotificationService {
sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DATES, String.format(TITLE_UPDATE_DATES, conference.getTitle())); sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DATES, String.format(TITLE_UPDATE_DATES, conference.getTitle()));
} }
private void sendForAllUsers(Map<String, Object> variables, String template, String title) { private void sendForAllUsers(Map<String, Object> variables, String title) {
userService.findAll().forEach(user -> mailService.sendEmailFromTemplate(variables, user, template, title)); userService.findAll().forEach(user -> mailService.sendEmailFromTemplate(variables, user, ConferenceNotificationService.TEMPLATE_CREATE, title));
} }
private void sendForAllParticipants(Map<String, Object> variables, Conference conference, String template, String title) { private void sendForAllParticipants(Map<String, Object> variables, Conference conference, String template, String title) {

@ -16,7 +16,6 @@ import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.name.BaseService; import ru.ulstu.name.BaseService;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.service.PaperService; import ru.ulstu.paper.service.PaperService;
import ru.ulstu.ping.model.Ping;
import ru.ulstu.ping.service.PingService; import ru.ulstu.ping.service.PingService;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
@ -25,6 +24,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -65,7 +65,7 @@ public class ConferenceService extends BaseService {
} }
public ConferenceDto getExistConferenceById(Integer id) { public ConferenceDto getExistConferenceById(Integer id) {
ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.findOne(id)); ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.getOne(id));
conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds())); conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds()));
conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers())); conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers()));
return conferenceDto; return conferenceDto;
@ -96,7 +96,6 @@ public class ConferenceService extends BaseService {
checkUniqueName(conferenceDto, checkUniqueName(conferenceDto,
errors, errors,
conferenceDto.getId(), conferenceDto.getId(),
"title",
"Конференция с таким именем уже существует"); "Конференция с таким именем уже существует");
if (errors.hasErrors()) { if (errors.hasErrors()) {
return false; return false;
@ -116,13 +115,13 @@ public class ConferenceService extends BaseService {
Conference newConference = copyFromDto(new Conference(), conferenceDto); Conference newConference = copyFromDto(new Conference(), conferenceDto);
newConference = conferenceRepository.save(newConference); newConference = conferenceRepository.save(newConference);
conferenceNotificationService.sendCreateNotification(newConference); conferenceNotificationService.sendCreateNotification(newConference);
eventService.createFromConference(newConference); eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции");
return newConference; return newConference;
} }
@Transactional @Transactional
public Conference update(ConferenceDto conferenceDto) throws IOException { private Conference update(ConferenceDto conferenceDto) throws IOException {
Conference conference = conferenceRepository.findOne(conferenceDto.getId()); Conference conference = conferenceRepository.getOne(conferenceDto.getId());
List<Deadline> oldDeadlines = conference.getDeadlines().stream() List<Deadline> oldDeadlines = conference.getDeadlines().stream()
.map(this::copyDeadline) .map(this::copyDeadline)
.collect(Collectors.toList()); .collect(Collectors.toList());
@ -140,9 +139,9 @@ public class ConferenceService extends BaseService {
@Transactional @Transactional
public boolean delete(Integer conferenceId) { public boolean delete(Integer conferenceId) {
if (conferenceRepository.exists(conferenceId)) { if (conferenceRepository.existsById(conferenceId)) {
eventService.removeConferencesEvent(conferenceRepository.findOne(conferenceId)); eventService.removeConferencesEvent(conferenceRepository.getOne(conferenceId));
conferenceRepository.delete(conferenceId); conferenceRepository.deleteById(conferenceId);
return true; return true;
} }
return false; return false;
@ -242,14 +241,13 @@ public class ConferenceService extends BaseService {
} }
@Transactional @Transactional
public Ping ping(ConferenceDto conferenceDto) throws IOException { public void ping(ConferenceDto conferenceDto) throws IOException {
Ping ping = pingService.addPing(findOne(conferenceDto.getId())); pingService.addPing(findOne(conferenceDto.getId()));
conferenceRepository.updatePingConference(conferenceDto.getId()); conferenceRepository.updatePingConference(conferenceDto.getId());
return ping;
} }
private Conference findOne(Integer conferenceId) { private Conference findOne(Integer conferenceId) {
return conferenceRepository.findOne(conferenceId); return conferenceRepository.getOne(conferenceId);
} }
public void setChartData(ModelMap modelMap) { public void setChartData(ModelMap modelMap) {
@ -294,7 +292,7 @@ public class ConferenceService extends BaseService {
return newDeadline; return newDeadline;
} }
public void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) { private void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) {
for (Deadline deadline : conferenceDto.getDeadlines()) { for (Deadline deadline : conferenceDto.getDeadlines()) {
if (deadline.getDate() == null || deadline.getDescription().isEmpty()) { if (deadline.getDate() == null || deadline.getDescription().isEmpty()) {
errors.rejectValue("deadlines", "errorCode", "Все поля дедлайна должны быть заполнены"); errors.rejectValue("deadlines", "errorCode", "Все поля дедлайна должны быть заполнены");
@ -313,4 +311,8 @@ public class ConferenceService extends BaseService {
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public Conference getActiveConferenceByUser(User user) {
return conferenceRepository.findActiveByUser(user);
}
} }

@ -26,8 +26,8 @@ public class ConferenceUserService {
} }
@Transactional @Transactional
public ConferenceUser update(ConferenceUser user) { private ConferenceUser update(ConferenceUser user) {
ConferenceUser updateUser = conferenceUserRepository.findOne(user.getId()); ConferenceUser updateUser = conferenceUserRepository.getOne(user.getId());
updateUser.setDeposit(user.getDeposit()); updateUser.setDeposit(user.getDeposit());
updateUser.setParticipation(user.getParticipation()); updateUser.setParticipation(user.getParticipation());
conferenceUserRepository.save(updateUser); conferenceUserRepository.save(updateUser);
@ -35,7 +35,7 @@ public class ConferenceUserService {
} }
@Transactional @Transactional
public ConferenceUser create(ConferenceUser user) { private ConferenceUser create(ConferenceUser user) {
ConferenceUser newUser = new ConferenceUser(); ConferenceUser newUser = new ConferenceUser();
newUser.setDeposit(user.getDeposit()); newUser.setDeposit(user.getDeposit());
newUser.setParticipation(user.getParticipation()); newUser.setParticipation(user.getParticipation());
@ -43,6 +43,4 @@ public class ConferenceUserService {
newUser = conferenceUserRepository.save(newUser); newUser = conferenceUserRepository.save(newUser);
return newUser; return newUser;
} }
} }

@ -1,10 +1,11 @@
package ru.ulstu.configuration; package ru.ulstu.configuration;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
@Component @Component
@ConfigurationProperties(prefix = "ng-tracker") @ConfigurationProperties(prefix = "ng-tracker")
@Validated @Validated
@ -23,6 +24,8 @@ public class ApplicationProperties {
private String debugEmail; private String debugEmail;
private String driverPath;
public boolean isUseHttps() { public boolean isUseHttps() {
return useHttps; return useHttps;
} }
@ -70,4 +73,12 @@ public class ApplicationProperties {
public void setDebugEmail(String debugEmail) { public void setDebugEmail(String debugEmail) {
this.debugEmail = debugEmail; this.debugEmail = debugEmail;
} }
public String getDriverPath() {
return driverPath;
}
public void setDriverPath(String driverPath) {
this.driverPath = driverPath;
}
} }

@ -2,18 +2,18 @@ package ru.ulstu.configuration;
import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.ServerConnector;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.web.embedded.jetty.JettyServerCustomizer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory; import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.context.embedded.jetty.JettyServerCustomizer; import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
public class HttpListenerConfiguration implements EmbeddedServletContainerCustomizer { public class HttpListenerConfiguration implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
@Value("${server.http.port}") @Value("${server.http.port}")
private int httpPort; private int httpPort;
private void configureJetty(JettyEmbeddedServletContainerFactory jettyFactory) { private void configureJetty(JettyServletWebServerFactory jettyFactory) {
jettyFactory.addServerCustomizers((JettyServerCustomizer) server -> { jettyFactory.addServerCustomizers((JettyServerCustomizer) server -> {
ServerConnector serverConnector = new ServerConnector(server); ServerConnector serverConnector = new ServerConnector(server);
serverConnector.setPort(httpPort); serverConnector.setPort(httpPort);
@ -22,9 +22,9 @@ public class HttpListenerConfiguration implements EmbeddedServletContainerCustom
} }
@Override @Override
public void customize(ConfigurableEmbeddedServletContainer container) { public void customize(ConfigurableWebServerFactory factory) {
if (container instanceof JettyEmbeddedServletContainerFactory) { if (factory instanceof JettyServletWebServerFactory) {
configureJetty((JettyEmbeddedServletContainerFactory) container); configureJetty((JettyServletWebServerFactory) factory);
} }
} }
} }

@ -3,8 +3,8 @@ package ru.ulstu.configuration;
import nz.net.ultraq.thymeleaf.LayoutDialect; import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver; import org.thymeleaf.templateresolver.ITemplateResolver;
@ -22,12 +22,11 @@ public class MailTemplateConfiguration {
return templateEngine; return templateEngine;
} }
public ClassLoaderTemplateResolver emailTemplateResolver() { private ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver(); ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("mail_templates/"); emailTemplateResolver.setPrefix("/mail_templates/");
emailTemplateResolver.setTemplateMode("HTML5"); emailTemplateResolver.setTemplateMode("HTML");
emailTemplateResolver.setSuffix(".html"); emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setOrder(1);
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name()); emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver; return emailTemplateResolver;
} }

@ -13,8 +13,10 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import ru.ulstu.core.model.AuthFailureHandler;
import ru.ulstu.user.controller.UserController; import ru.ulstu.user.controller.UserController;
import ru.ulstu.user.model.UserRoleConstants; import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
@ -35,17 +37,20 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final AuthenticationSuccessHandler authenticationSuccessHandler; private final AuthenticationSuccessHandler authenticationSuccessHandler;
private final LogoutSuccessHandler logoutSuccessHandler; private final LogoutSuccessHandler logoutSuccessHandler;
private final ApplicationProperties applicationProperties; private final ApplicationProperties applicationProperties;
private final AuthenticationFailureHandler authenticationFailureHandler;
public SecurityConfiguration(UserService userService, public SecurityConfiguration(UserService userService,
BCryptPasswordEncoder bCryptPasswordEncoder, BCryptPasswordEncoder bCryptPasswordEncoder,
AuthenticationSuccessHandler authenticationSuccessHandler, AuthenticationSuccessHandler authenticationSuccessHandler,
LogoutSuccessHandler logoutSuccessHandler, LogoutSuccessHandler logoutSuccessHandler,
ApplicationProperties applicationProperties) { ApplicationProperties applicationProperties,
AuthFailureHandler authenticationFailureHandler) {
this.userService = userService; this.userService = userService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder; this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.authenticationSuccessHandler = authenticationSuccessHandler; this.authenticationSuccessHandler = authenticationSuccessHandler;
this.logoutSuccessHandler = logoutSuccessHandler; this.logoutSuccessHandler = logoutSuccessHandler;
this.applicationProperties = applicationProperties; this.applicationProperties = applicationProperties;
this.authenticationFailureHandler = authenticationFailureHandler;
} }
@Override @Override
@ -66,6 +71,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.antMatchers(UserController.ACTIVATE_URL).permitAll() .antMatchers(UserController.ACTIVATE_URL).permitAll()
.antMatchers(Constants.PASSWORD_RESET_REQUEST_PAGE).permitAll() .antMatchers(Constants.PASSWORD_RESET_REQUEST_PAGE).permitAll()
.antMatchers(Constants.PASSWORD_RESET_PAGE).permitAll() .antMatchers(Constants.PASSWORD_RESET_PAGE).permitAll()
.antMatchers("/users/block").permitAll()
.antMatchers(UserController.URL + UserController.REGISTER_URL).permitAll() .antMatchers(UserController.URL + UserController.REGISTER_URL).permitAll()
.antMatchers(UserController.URL + UserController.ACTIVATE_URL).permitAll() .antMatchers(UserController.URL + UserController.ACTIVATE_URL).permitAll()
.antMatchers(UserController.URL + UserController.PASSWORD_RESET_REQUEST_URL).permitAll() .antMatchers(UserController.URL + UserController.PASSWORD_RESET_REQUEST_URL).permitAll()
@ -76,6 +82,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.formLogin() .formLogin()
.loginPage("/login") .loginPage("/login")
.successHandler(authenticationSuccessHandler) .successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.permitAll() .permitAll()
.and() .and()
.logout() .logout()

@ -6,19 +6,19 @@ import org.springframework.data.domain.Sort;
import java.io.Serializable; import java.io.Serializable;
public class OffsetablePageRequest implements Pageable, Serializable { public class OffsetablePageRequest implements Pageable, Serializable {
private final int offset; private final long offset;
private final int count; private final int count;
private final Sort sort; private final Sort sort;
public OffsetablePageRequest(int offset, int count) { public OffsetablePageRequest(long offset, int count) {
this(offset, count, null); 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)); 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) { if (offset < 0) {
throw new IllegalArgumentException("Offset value must not be less than zero!"); throw new IllegalArgumentException("Offset value must not be less than zero!");
} }
@ -42,11 +42,11 @@ public class OffsetablePageRequest implements Pageable, Serializable {
@Override @Override
public int getPageNumber() { public int getPageNumber() {
return offset / count; return (int) (offset / count);
} }
@Override @Override
public int getOffset() { public long getOffset() {
return offset; return offset;
} }
@ -65,7 +65,7 @@ public class OffsetablePageRequest implements Pageable, Serializable {
return hasPrevious() ? previous() : first(); return hasPrevious() ? previous() : first();
} }
public Pageable previous() { private Pageable previous() {
return getOffset() == 0 ? this : new OffsetablePageRequest(getOffset() - getPageSize(), getPageSize(), getSort()); return getOffset() == 0 ? this : new OffsetablePageRequest(getOffset() - getPageSize(), getPageSize(), getSort());
} }
@ -89,9 +89,9 @@ public class OffsetablePageRequest implements Pageable, Serializable {
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; long result = 1;
result = prime * result + offset; result = prime * result + offset;
result = prime * result + count; result = prime * result + count;
return result; return (int) result;
} }
} }

@ -0,0 +1,21 @@
package ru.ulstu.core.model;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import ru.ulstu.user.error.UserBlockedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException {
if (ex.getClass() == UserBlockedException.class) {
response.sendRedirect("/users/block");
}
}
}

@ -5,10 +5,11 @@ import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.MappedSuperclass; import javax.persistence.MappedSuperclass;
import javax.persistence.Version; import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import java.io.Serializable; import java.io.Serializable;
@MappedSuperclass @MappedSuperclass
public abstract class BaseEntity implements Serializable, Comparable { public abstract class BaseEntity implements Serializable, Comparable<BaseEntity> {
@Id @Id
@GeneratedValue(strategy = GenerationType.TABLE) @GeneratedValue(strategy = GenerationType.TABLE)
private Integer id; private Integer id;
@ -16,14 +17,6 @@ public abstract class BaseEntity implements Serializable, Comparable {
@Version @Version
private Integer version; private Integer version;
public BaseEntity() {
}
public BaseEntity(Integer id, Integer version) {
this.id = id;
this.version = version;
}
public Integer getId() { public Integer getId() {
return id; return id;
} }
@ -75,8 +68,8 @@ public abstract class BaseEntity implements Serializable, Comparable {
} }
@Override @Override
public int compareTo(Object o) { public int compareTo(@NotNull BaseEntity o) {
return id != null ? id.compareTo(((BaseEntity) o).getId()) : -1; return id != null ? id.compareTo(o.getId()) : -1;
} }
public void reset() { public void reset() {

@ -16,8 +16,8 @@ public enum ErrorConstants {
FILE_UPLOAD_ERROR(110, "File upload error"), FILE_UPLOAD_ERROR(110, "File upload error"),
USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка"); USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка");
private int code; private final int code;
private String message; private final String message;
ErrorConstants(int code, String message) { ErrorConstants(int code, String message) {
this.code = code; this.code = code;

@ -0,0 +1,17 @@
package ru.ulstu.core.model;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import java.util.List;
public interface EventSource {
List<Deadline> getDeadlines();
String getTitle();
List<User> getRecipients();
void addObjectToEvent(Event event);
}

@ -1,34 +0,0 @@
package ru.ulstu.core.model;
import java.util.ArrayList;
import java.util.List;
public class TreeDto {
private Integer id;
private String text;
private List<TreeDto> children = new ArrayList<>();
public TreeDto() {
}
public <T extends TreeEntity> TreeDto(TreeEntity item) {
this.text = item.toString();
this.id = item.getId();
}
public TreeDto(String rootName) {
this.text = rootName;
}
public String getText() {
return text;
}
public List<TreeDto> getChildren() {
return children;
}
public Integer getId() {
return id;
}
}

@ -1,16 +0,0 @@
package ru.ulstu.core.model;
import java.util.List;
public interface TreeEntity<T> {
Integer getId();
List<T> getChildren();
void setChildren(List<T> children);
T getParent();
void setParent(T parent);
}

@ -0,0 +1,11 @@
package ru.ulstu.core.model;
import ru.ulstu.user.model.User;
import java.util.Set;
public interface UserActivity {
String getTitle();
Set<User> getActivityUsers();
}

@ -1,9 +0,0 @@
package ru.ulstu.core.model;
import ru.ulstu.user.model.User;
import java.util.Set;
public interface UserContainer {
Set<User> getUsers();
}

@ -1,8 +1,8 @@
package ru.ulstu.core.model.response; package ru.ulstu.core.model.response;
class ControllerResponse<D, E> { class ControllerResponse<D, E> {
private D data; private final D data;
private ControllerResponseError<E> error; private final ControllerResponseError<E> error;
ControllerResponse(D data) { ControllerResponse(D data) {
this.data = data; this.data = data;

@ -3,8 +3,8 @@ package ru.ulstu.core.model.response;
import ru.ulstu.core.model.ErrorConstants; import ru.ulstu.core.model.ErrorConstants;
class ControllerResponseError<D> { class ControllerResponseError<D> {
private ErrorConstants description; private final ErrorConstants description;
private D data; private final D data;
ControllerResponseError(ErrorConstants description, D data) { ControllerResponseError(ErrorConstants description, D data) {
this.description = description; this.description = description;

@ -8,7 +8,7 @@ import java.io.Serializable;
public class JpaDetachableRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> public class JpaDetachableRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements JpaDetachableRepository<T, ID> { implements JpaDetachableRepository<T, ID> {
private EntityManager entityManager; private final EntityManager entityManager;
public JpaDetachableRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) { public JpaDetachableRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager); super(entityInformation, entityManager);

@ -16,7 +16,7 @@ public class DateUtils {
public static Date clearTime(Date date) { public static Date clearTime(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(date); calendar.setTime(date);
calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.MILLISECOND, 0);

@ -1,17 +0,0 @@
package ru.ulstu.core.util;
public class NumberUtils {
public static Double ceil(Double number) {
if (number == null) {
return 0.0;
}
return Double.valueOf(Math.ceil(number));
}
public static Double round(Double number) {
if (number == null) {
return 0.0;
}
return Double.valueOf(Math.ceil(number * 100)) / 100;
}
}

@ -11,12 +11,12 @@ public class StreamApiUtils {
public static <T, R> List<T> convert(List<R> entities, Function<R, T> converter) { public static <T, R> List<T> convert(List<R> entities, Function<R, T> converter) {
return entities == null return entities == null
? Collections.emptyList() ? Collections.emptyList()
: entities.stream().map(e -> converter.apply(e)).collect(Collectors.toList()); : entities.stream().map(converter).collect(Collectors.toList());
} }
public static <T, R> Set<T> convert(Set<R> entities, Function<R, T> converter) { public static <T, R> Set<T> convert(Set<R> entities, Function<R, T> converter) {
return entities == null return entities == null
? Collections.emptySet() ? Collections.emptySet()
: entities.stream().map(e -> converter.apply(e)).collect(Collectors.toSet()); : entities.stream().map(converter).collect(Collectors.toSet());
} }
} }

@ -4,11 +4,15 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.model.User;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@ -16,10 +20,15 @@ public class Deadline extends BaseEntity {
private String description; private String description;
@Temporal(value = TemporalType.TIMESTAMP) @Temporal(value = TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date; private Date date;
@OneToMany(targetEntity = User.class, fetch = FetchType.EAGER)
private List<User> executors;
private Boolean done;
public Deadline() { public Deadline() {
} }
@ -28,13 +37,24 @@ public class Deadline extends BaseEntity {
this.description = description; this.description = description;
} }
public Deadline(Date deadlineDate, String description, List<User> executors, Boolean done) {
this.date = deadlineDate;
this.description = description;
this.executors = executors;
this.done = done;
}
@JsonCreator @JsonCreator
public Deadline(@JsonProperty("id") Integer id, public Deadline(@JsonProperty("id") Integer id,
@JsonProperty("description") String description, @JsonProperty("description") String description,
@JsonProperty("date") Date date) { @JsonProperty("date") Date date,
@JsonProperty("executors") List<User> executors,
@JsonProperty("done") Boolean done) {
this.setId(id); this.setId(id);
this.description = description; this.description = description;
this.date = date; this.date = date;
this.executors = executors;
this.done = done;
} }
public String getDescription() { public String getDescription() {
@ -53,6 +73,22 @@ public class Deadline extends BaseEntity {
this.date = date; this.date = date;
} }
public List<User> getExecutors() {
return executors;
}
public void setExecutors(List<User> executors) {
this.executors = executors;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) { if (this == o) {
@ -72,11 +108,13 @@ public class Deadline extends BaseEntity {
} }
return getId().equals(deadline.getId()) && return getId().equals(deadline.getId()) &&
description.equals(deadline.description) && description.equals(deadline.description) &&
date.equals(deadline.date); date.equals(deadline.date) &&
executors.equals(deadline.executors) &&
done.equals(deadline.done);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(super.hashCode(), description, date); return Objects.hash(super.hashCode(), description, date, executors, done);
} }
} }

@ -3,14 +3,13 @@ package ru.ulstu.deadline.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import java.util.Date; import java.util.Date;
public interface DeadlineRepository extends JpaRepository<Deadline, Integer> { public interface DeadlineRepository extends JpaRepository<Deadline, Integer> {
@Query( @Query("SELECT d.date FROM Grant g JOIN g.deadlines d WHERE (g.id = :id) AND (d.date = :date)")
value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", Date findByGrantIdAndDate(@Param("id") Integer grantId, @Param("date") Date date);
nativeQuery = true)
Date findByGrantIdAndDate(Integer grantId, Date date);
} }

@ -26,10 +26,12 @@ public class DeadlineService {
} }
@Transactional @Transactional
public Deadline update(Deadline deadline) { private Deadline update(Deadline deadline) {
Deadline updateDeadline = deadlineRepository.findOne(deadline.getId()); Deadline updateDeadline = deadlineRepository.getOne(deadline.getId());
updateDeadline.setDate(deadline.getDate()); updateDeadline.setDate(deadline.getDate());
updateDeadline.setDescription(deadline.getDescription()); updateDeadline.setDescription(deadline.getDescription());
updateDeadline.setExecutors(deadline.getExecutors());
updateDeadline.setDone(deadline.getDone());
deadlineRepository.save(updateDeadline); deadlineRepository.save(updateDeadline);
return updateDeadline; return updateDeadline;
} }
@ -39,13 +41,15 @@ public class DeadlineService {
Deadline newDeadline = new Deadline(); Deadline newDeadline = new Deadline();
newDeadline.setDate(deadline.getDate()); newDeadline.setDate(deadline.getDate());
newDeadline.setDescription(deadline.getDescription()); newDeadline.setDescription(deadline.getDescription());
newDeadline.setExecutors(deadline.getExecutors());
newDeadline.setDone(deadline.getDone());
newDeadline = deadlineRepository.save(newDeadline); newDeadline = deadlineRepository.save(newDeadline);
return newDeadline; return newDeadline;
} }
@Transactional @Transactional
public void remove(Integer deadlineId) { public void remove(Integer deadlineId) {
deadlineRepository.delete(deadlineId); deadlineRepository.deleteById(deadlineId);
} }
public Date findByGrantIdAndDate(Integer id, Date date) { public Date findByGrantIdAndDate(Integer id, Date date) {

@ -21,13 +21,10 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static ru.ulstu.file.FileController.URL;
@RestController @RestController
@RequestMapping(URL) @RequestMapping(Constants.API_1_0 + "files")
public class FileController { public class FileController {
public static final String URL = Constants.API_1_0 + "files";
private final FileService fileService; private final FileService fileService;
public FileController(FileService fileService) { public FileController(FileService fileService) {
@ -53,6 +50,6 @@ public class FileController {
@PostMapping("/uploadTmpFile") @PostMapping("/uploadTmpFile")
public Response<FileDataDto> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException { public Response<FileDataDto> upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
return new Response(fileService.createFromMultipartFile(multipartFile)); return new Response<>(fileService.createFromMultipartFile(multipartFile));
} }
} }

@ -27,15 +27,15 @@ public class FileService {
private final static int META_FILE_NAME_INDEX = 0; private final static int META_FILE_NAME_INDEX = 0;
private final static int META_FILE_SIZE_INDEX = 1; private final static int META_FILE_SIZE_INDEX = 1;
private String tmpDir; private final String tmpDir;
private FileRepository fileRepository; private final FileRepository fileRepository;
public FileService(FileRepository fileRepository) { public FileService(FileRepository fileRepository) {
tmpDir = System.getProperty("java.io.tmpdir"); tmpDir = System.getProperty("java.io.tmpdir");
this.fileRepository = fileRepository; this.fileRepository = fileRepository;
} }
public FileData createFileFromTmp(String tmpFileName) throws IOException { private FileData createFileFromTmp(String tmpFileName) throws IOException {
FileData fileData = new FileData(); FileData fileData = new FileData();
fileData.setData(getTmpFile(tmpFileName)); fileData.setData(getTmpFile(tmpFileName));
fileData.setSize(getTmpFileSize(tmpFileName)); fileData.setSize(getTmpFileSize(tmpFileName));
@ -43,7 +43,7 @@ public class FileService {
return fileRepository.save(fileData); return fileRepository.save(fileData);
} }
public String uploadToTmpDir(MultipartFile multipartFile) throws IOException { private String uploadToTmpDir(MultipartFile multipartFile) throws IOException {
String tmpFileName = String.valueOf(System.currentTimeMillis()) + UUID.randomUUID(); String tmpFileName = String.valueOf(System.currentTimeMillis()) + UUID.randomUUID();
Files.write(getTmpFilePath(tmpFileName), multipartFile.getBytes()); Files.write(getTmpFilePath(tmpFileName), multipartFile.getBytes());
String meta = multipartFile.getOriginalFilename() + "\n" + multipartFile.getSize(); String meta = multipartFile.getOriginalFilename() + "\n" + multipartFile.getSize();
@ -56,7 +56,7 @@ public class FileService {
.split("\n"); .split("\n");
} }
public long getTmpFileSize(String tmpFileName) throws IOException { private long getTmpFileSize(String tmpFileName) throws IOException {
return Long.valueOf(getMeta(tmpFileName)[META_FILE_SIZE_INDEX]).longValue(); return Long.valueOf(getMeta(tmpFileName)[META_FILE_SIZE_INDEX]).longValue();
} }
@ -69,7 +69,7 @@ public class FileService {
} }
public FileData getFile(Integer fileId) { public FileData getFile(Integer fileId) {
return fileRepository.findOne(fileId); return fileRepository.getOne(fileId);
} }
public void deleteTmpFile(String tmpFileName) throws IOException { public void deleteTmpFile(String tmpFileName) throws IOException {
@ -97,13 +97,13 @@ public class FileService {
} }
@Transactional @Transactional
public FileData update(FileDataDto fileDataDto) { private FileData update(FileDataDto fileDataDto) {
FileData file = fileRepository.findOne(fileDataDto.getId()); FileData file = fileRepository.getOne(fileDataDto.getId());
return fileRepository.save(copyFromDto(file, fileDataDto)); return fileRepository.save(copyFromDto(file, fileDataDto));
} }
@Transactional @Transactional
public FileData create(FileDataDto fileDataDto) throws IOException { private FileData create(FileDataDto fileDataDto) throws IOException {
FileData newFile = createFileFromTmp(fileDataDto.getTmpFileName()); FileData newFile = createFileFromTmp(fileDataDto.getTmpFileName());
copyFromDto(newFile, fileDataDto); copyFromDto(newFile, fileDataDto);
return fileRepository.save(newFile); return fileRepository.save(newFile);
@ -117,7 +117,7 @@ public class FileService {
@Transactional @Transactional
public void delete(Integer fileId) { public void delete(Integer fileId) {
fileRepository.delete(fileRepository.findOne(fileId)); fileRepository.delete(fileRepository.getOne(fileId));
} }
public FileDataDto createFromMultipartFile(MultipartFile multipartFile) throws IOException { public FileDataDto createFromMultipartFile(MultipartFile multipartFile) throws IOException {
@ -134,7 +134,7 @@ public class FileService {
File renamed = getTmpFilePath(fileDataDto.getName()).toFile(); File renamed = getTmpFilePath(fileDataDto.getName()).toFile();
oldFile.renameTo(renamed); oldFile.renameTo(renamed);
} else { } else {
Files.write(getTmpFilePath(fileDataDto.getName()), fileRepository.findOne(fileDataDto.getId()).getData()); Files.write(getTmpFilePath(fileDataDto.getName()), fileRepository.getOne(fileDataDto.getId()).getData());
} }
} }
} }

@ -9,6 +9,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
@ -49,7 +50,7 @@ public class GrantController {
@GetMapping("/grant") @GetMapping("/grant")
public void getGrant(ModelMap modelMap, @RequestParam(value = "id") Integer id) { public void getGrant(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) { if (id != null && id > 0) {
GrantDto grantDto = grantService.findOneDto(id); GrantDto grantDto = grantService.getExistGrantById(id);
attachPaper(grantDto); attachPaper(grantDto);
modelMap.put("grantDto", grantDto); modelMap.put("grantDto", grantDto);
} else { } else {
@ -123,4 +124,10 @@ public class GrantController {
public List<PaperDto> getAllPapers() { public List<PaperDto> getAllPapers() {
return grantService.getAllUncompletedPapers(); return grantService.getAllUncompletedPapers();
} }
@ResponseBody
@PostMapping(value = "/ping")
public void ping(@RequestParam("grantId") int grantId) throws IOException {
grantService.ping(grantId);
}
} }

@ -0,0 +1,29 @@
package ru.ulstu.grant.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.configuration.Constants;
import ru.ulstu.grant.service.GrantService;
import java.io.IOException;
import java.text.ParseException;
import static ru.ulstu.paper.controller.PaperRestController.URL;
@RestController
@RequestMapping(URL)
public class GrantRestController {
public static final String URL = Constants.API_1_0 + "grants";
private final GrantService grantService;
public GrantRestController(GrantService grantService) {
this.grantService = grantService;
}
@GetMapping("/grab")
public void grab() throws IOException, ParseException {
grantService.createFromKias();
}
}

@ -2,9 +2,9 @@ package ru.ulstu.grant.model;
import org.hibernate.annotations.Fetch; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer; import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
@ -13,6 +13,7 @@ import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
@ -24,8 +25,10 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.OrderBy; import javax.persistence.OrderBy;
import javax.persistence.Table; import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -35,7 +38,8 @@ import java.util.Set;
@Entity @Entity
@Table(name = "grants") @Table(name = "grants")
public class Grant extends BaseEntity implements UserContainer { @DiscriminatorValue("GRANT")
public class Grant extends BaseEntity implements UserActivity, EventSource {
public enum GrantStatus { public enum GrantStatus {
APPLICATION("Заявка"), APPLICATION("Заявка"),
ON_COMPETITION("Отправлен на конкурс"), ON_COMPETITION("Отправлен на конкурс"),
@ -46,7 +50,7 @@ public class Grant extends BaseEntity implements UserContainer {
LOADED_FROM_KIAS("Загружен автоматически"), LOADED_FROM_KIAS("Загружен автоматически"),
SKIPPED("Не интересует"); SKIPPED("Не интересует");
private String statusName; private final String statusName;
GrantStatus(String statusName) { GrantStatus(String statusName) {
this.statusName = statusName; this.statusName = statusName;
@ -134,6 +138,16 @@ public class Grant extends BaseEntity implements UserContainer {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return authors != null ? new ArrayList<>(authors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setGrant(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -155,7 +169,7 @@ public class Grant extends BaseEntity implements UserContainer {
} }
@Override @Override
public Set<User> getUsers() { public Set<User> getActivityUsers() {
return getAuthors(); return getAuthors();
} }

@ -3,7 +3,6 @@ package ru.ulstu.grant.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.name.NameContainer; import ru.ulstu.name.NameContainer;
@ -11,6 +10,7 @@ import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;

@ -1,8 +1,9 @@
package ru.ulstu.grant.page; package ru.ulstu.grant.page;
import org.openqa.selenium.By; import com.gargoylesoftware.htmlunit.html.DomNode;
import org.openqa.selenium.WebDriver; import com.gargoylesoftware.htmlunit.html.HtmlElement;
import org.openqa.selenium.WebElement; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -11,16 +12,17 @@ import java.util.List;
public class KiasPage { public class KiasPage {
private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm"; private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm";
private WebDriver driver; private final HtmlPage page;
public KiasPage(WebDriver webDriver) { public KiasPage(HtmlPage page) {
this.driver = webDriver; this.page = page;
} }
public boolean goToNextPage() { public boolean goToNextPage() {
try { try {
if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { HtmlElement nextPageLink = page.getHtmlElementById("js-ctrlNext");
driver.findElement(By.id("js-ctrlNext")).click(); if (nextPageLink.isDisplayed()) {
nextPageLink.click();
return true; return true;
} }
} finally { } finally {
@ -28,23 +30,26 @@ public class KiasPage {
} }
} }
public List<WebElement> getPageOfGrants() { public List<DomNode> getPageOfGrants() {
WebElement listContest = driver.findElement(By.tagName("tBody")); return page.getByXPath("/html/body/div[2]/div/div[2]/main/div[1]/table/tbody/tr");
List<WebElement> grants = listContest.findElements(By.cssSelector("tr.tr"));
return grants;
} }
public String getGrantTitle(WebElement grant) { public String getGrantTitle(DomNode grant) {
return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); return ((DomNode) grant.getFirstByXPath("td[2]")).getTextContent() + " "
+ ((DomNode) grant.getFirstByXPath("td[@class='tertiary']/a")).getTextContent();
} }
public Date parseDeadLineDate(WebElement grantElement) throws ParseException { public Date parseDeadLineDate(DomNode grantElement) throws ParseException {
String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59
SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT); SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT);
return formatter.parse(deadlineDate); return formatter.parse(deadlineDate);
} }
private String getFirstDeadline(WebElement grantElement) { private String getFirstDeadline(DomNode grantElement) {
return grantElement.findElement(By.xpath("./td[5]")).getText(); return ((DomNode) grantElement.getFirstByXPath("td[5]")).getTextContent();
}
public boolean isTableRowGrantLine(DomNode grantElement) {
return !((HtmlTableRow) grantElement).getAttribute("class").contains("pagerSavedHeightSpacer");
} }
} }

@ -14,6 +14,8 @@ public interface GrantRepository extends JpaRepository<Grant, Integer>, BaseRepo
Grant findByTitle(String title); Grant findByTitle(String title);
Grant findGrantById(Integer grantId);
@Override @Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);

@ -27,7 +27,7 @@ public class GrantScheduler {
@Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara")
public void checkDeadlineBeforeWeek() { public void checkDeadlineBeforeWeek() {
log.debug("GrantScheduler.checkDeadlineBeforeWeek started"); log.debug("GrantScheduler.checkDeadlineBeforeWeek started");
grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished");
} }

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
@ -17,7 +18,7 @@ import ru.ulstu.name.BaseService;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.service.PaperService; import ru.ulstu.paper.service.PaperService;
import ru.ulstu.project.model.Project; import ru.ulstu.ping.service.PingService;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.service.ProjectService; import ru.ulstu.project.service.ProjectService;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
@ -52,6 +53,7 @@ public class GrantService extends BaseService {
private final EventService eventService; private final EventService eventService;
private final GrantNotificationService grantNotificationService; private final GrantNotificationService grantNotificationService;
private final KiasService kiasService; private final KiasService kiasService;
private final PingService pingService;
public GrantService(GrantRepository grantRepository, public GrantService(GrantRepository grantRepository,
FileService fileService, FileService fileService,
@ -61,7 +63,8 @@ public class GrantService extends BaseService {
PaperService paperService, PaperService paperService,
EventService eventService, EventService eventService,
GrantNotificationService grantNotificationService, GrantNotificationService grantNotificationService,
KiasService kiasService) { KiasService kiasService,
PingService pingService) {
this.grantRepository = grantRepository; this.grantRepository = grantRepository;
this.kiasService = kiasService; this.kiasService = kiasService;
this.baseRepository = grantRepository; this.baseRepository = grantRepository;
@ -72,6 +75,11 @@ public class GrantService extends BaseService {
this.paperService = paperService; this.paperService = paperService;
this.eventService = eventService; this.eventService = eventService;
this.grantNotificationService = grantNotificationService; this.grantNotificationService = grantNotificationService;
this.pingService = pingService;
}
public GrantDto getExistGrantById(Integer id) {
return new GrantDto(findById(id));
} }
public List<Grant> findAll() { public List<Grant> findAll() {
@ -82,17 +90,13 @@ public class GrantService extends BaseService {
return convert(findAll(), GrantDto::new); return convert(findAll(), GrantDto::new);
} }
public GrantDto findOneDto(Integer id) {
return new GrantDto(grantRepository.findOne(id));
}
@Transactional @Transactional
public Integer create(GrantDto grantDto) throws IOException { public Grant create(GrantDto grantDto) throws IOException {
Grant newGrant = copyFromDto(new Grant(), grantDto); Grant newGrant = copyFromDto(new Grant(), grantDto);
newGrant = grantRepository.save(newGrant); newGrant = grantRepository.save(newGrant);
eventService.createFromGrant(newGrant); eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта");
grantNotificationService.sendCreateNotification(newGrant); grantNotificationService.sendCreateNotification(newGrant);
return newGrant.getId(); return newGrant;
} }
private Grant copyFromDto(Grant grant, GrantDto grantDto) throws IOException { private Grant copyFromDto(Grant grant, GrantDto grantDto) throws IOException {
@ -103,9 +107,11 @@ public class GrantService extends BaseService {
grant.setProject(projectService.findById(grantDto.getProject().getId())); grant.setProject(projectService.findById(grantDto.getProject().getId()));
} }
grant.setDeadlines(deadlineService.saveOrCreate(grantDto.getDeadlines())); grant.setDeadlines(deadlineService.saveOrCreate(grantDto.getDeadlines()));
grant.setFiles(fileService.saveOrCreate(grantDto.getFiles().stream() if (!grant.getFiles().isEmpty()) {
.filter(f -> !f.isDeleted()) grant.setFiles(fileService.saveOrCreate(grantDto.getFiles().stream()
.collect(toList()))); .filter(f -> !f.isDeleted())
.collect(toList())));
}
grant.getAuthors().clear(); grant.getAuthors().clear();
if (grantDto.getAuthorIds() != null && !grantDto.getAuthorIds().isEmpty()) { if (grantDto.getAuthorIds() != null && !grantDto.getAuthorIds().isEmpty()) {
grantDto.getAuthorIds().forEach(authorIds -> grant.getAuthors().add(userService.findById(authorIds))); grantDto.getAuthorIds().forEach(authorIds -> grant.getAuthors().add(userService.findById(authorIds)));
@ -120,14 +126,15 @@ public class GrantService extends BaseService {
return grant; return grant;
} }
public void createProject(GrantDto grantDto) throws IOException { public void createProject(GrantDto grantDto) throws IOException {
grantDto.setProject( grantDto.setProject(
new ProjectDto(projectService.save(new ProjectDto(grantDto.getTitle())))); new ProjectDto(projectService.save(new ProjectDto(grantDto.getTitle()))));
} }
@Transactional @Transactional
public Integer update(GrantDto grantDto) throws IOException { private Integer update(GrantDto grantDto) throws IOException {
Grant grant = grantRepository.findOne(grantDto.getId()); Grant grant = findById(grantDto.getId());
Set<User> oldAuthors = new HashSet<>(grant.getAuthors()); Set<User> oldAuthors = new HashSet<>(grant.getAuthors());
User oldLeader = grant.getLeader(); User oldLeader = grant.getLeader();
for (FileDataDto file : grantDto.getFiles().stream() for (FileDataDto file : grantDto.getFiles().stream()
@ -156,40 +163,25 @@ public class GrantService extends BaseService {
} }
@Transactional @Transactional
public void delete(Integer grantId) throws IOException { public boolean delete(Integer grantId) throws IOException {
Grant grant = grantRepository.findOne(grantId); Grant grant = findById(grantId);
grantRepository.delete(grant); if (grant != null) {
grantRepository.delete(grant);
return true;
}
return false;
} }
public List<Grant.GrantStatus> getGrantStatuses() { public List<Grant.GrantStatus> getGrantStatuses() {
return Arrays.asList(Grant.GrantStatus.values()); return Arrays.asList(Grant.GrantStatus.values());
} }
@Transactional
public Grant create(String title, Project projectId, Date deadlineDate, User user, Paper paper) {
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.getPapers().add(paper);
grant = grantRepository.save(grant);
eventService.createFromGrant(grant);
grantNotificationService.sendCreateNotification(grant);
return grant;
}
public boolean save(GrantDto grantDto, Errors errors) throws IOException { public boolean save(GrantDto grantDto, Errors errors) throws IOException {
grantDto.setName(grantDto.getTitle()); grantDto.setName(grantDto.getTitle());
filterEmptyDeadlines(grantDto); filterEmptyDeadlines(grantDto);
checkEmptyDeadlines(grantDto, errors); checkEmptyDeadlines(grantDto, errors);
checkEmptyLeader(grantDto, errors); checkEmptyLeader(grantDto, errors);
checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); checkUniqueName(grantDto, errors, grantDto.getId(), "Грант с таким именем уже существует");
if (errors.hasErrors()) { if (errors.hasErrors()) {
return false; return false;
} }
@ -201,7 +193,7 @@ public class GrantService extends BaseService {
return true; return true;
} }
public boolean saveFromKias(GrantDto grantDto) throws IOException { private boolean saveFromKias(GrantDto grantDto) throws IOException {
grantDto.setName(grantDto.getTitle()); grantDto.setName(grantDto.getTitle());
String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени
if (title != null) { if (title != null) {
@ -231,11 +223,9 @@ public class GrantService extends BaseService {
} }
private boolean checkSameDeadline(GrantDto grantDto, Integer id) { private boolean checkSameDeadline(GrantDto grantDto, Integer id) {
Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас
if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date));
return true; return foundGrantDate != null && foundGrantDate.compareTo(date) == 0;
}
return false;
} }
public List<User> getGrantAuthors(GrantDto grantDto) { public List<User> getGrantAuthors(GrantDto grantDto) {
@ -273,20 +263,22 @@ public class GrantService extends BaseService {
return paperService.findAllNotCompleted(); return paperService.findAllNotCompleted();
} }
public void attachPaper(GrantDto grantDto) { public List<PaperDto> attachPaper(GrantDto grantDto) {
if (!grantDto.getPaperIds().isEmpty()) { if (!grantDto.getPaperIds().isEmpty()) {
grantDto.getPapers().clear(); grantDto.getPapers().clear();
grantDto.setPapers(getGrantPapers(grantDto.getPaperIds())); grantDto.setPapers(getGrantPapers(grantDto.getPaperIds()));
} else { } else {
grantDto.getPapers().clear(); grantDto.getPapers().clear();
} }
return grantDto.getPapers();
} }
public void removeDeadline(GrantDto grantDto, Integer deadlineId) { public GrantDto removeDeadline(GrantDto grantDto, Integer deadlineId) {
if (grantDto.getDeadlines().get(deadlineId).getId() != null) { if (grantDto.getDeadlines().get(deadlineId).getId() != null) {
grantDto.getRemovedDeadlineIds().add(grantDto.getDeadlines().get(deadlineId).getId()); grantDto.getRemovedDeadlineIds().add(grantDto.getDeadlines().get(deadlineId).getId());
} }
grantDto.getDeadlines().remove((int) deadlineId); grantDto.getDeadlines().remove((int) deadlineId);
return grantDto;
} }
private List<User> getCompletedPapersAuthors(Paper.PaperType type) { private List<User> getCompletedPapersAuthors(Paper.PaperType type) {
@ -312,10 +304,11 @@ public class GrantService extends BaseService {
.collect(toList()); .collect(toList());
} }
public void filterEmptyDeadlines(GrantDto grantDto) { public List<Deadline> filterEmptyDeadlines(GrantDto grantDto) {
grantDto.setDeadlines(grantDto.getDeadlines().stream() grantDto.setDeadlines(grantDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
return grantDto.getDeadlines();
} }
@Transactional @Transactional
@ -333,7 +326,16 @@ public class GrantService extends BaseService {
return convert(findAllActive(), GrantDto::new); return convert(findAllActive(), GrantDto::new);
} }
private List<Grant> findAllActive() { public List<Grant> findAllActive() {
return grantRepository.findAllActive(); return grantRepository.findAllActive();
} }
public Grant findById(Integer id) {
return grantRepository.getOne(id);
}
@Transactional
public void ping(int grantId) throws IOException {
pingService.addPing(findById(grantId));
}
} }

@ -1,14 +1,15 @@
package ru.ulstu.grant.service; package ru.ulstu.grant.service;
import org.openqa.selenium.WebDriver; import com.gargoylesoftware.htmlunit.WebClient;
import org.openqa.selenium.WebElement; import com.gargoylesoftware.htmlunit.html.DomNode;
import org.openqa.selenium.chrome.ChromeDriver; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.page.KiasPage; import ru.ulstu.grant.page.KiasPage;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -21,33 +22,29 @@ public class KiasService {
private final static String CONTEST_STATUS_ID = "1"; private final static String CONTEST_STATUS_ID = "1";
private final static String CONTEST_TYPE = "-1"; private final static String CONTEST_TYPE = "-1";
private final static String DRIVER_LOCATION = "drivers/%s";
private final static String WINDOWS_DRIVER = "chromedriver.exe";
private final static String LINUX_DRIVER = "chromedriver";
private final static String DRIVER_TYPE = "webdriver.chrome.driver";
private final UserService userService; private final UserService userService;
public KiasService(UserService userService) { public KiasService(UserService userService,
ApplicationProperties applicationProperties) {
this.userService = userService; this.userService = userService;
} }
public List<GrantDto> getNewGrantsDto() throws ParseException { public List<GrantDto> getNewGrantsDto() throws ParseException, IOException {
WebDriver webDriver = getDriver();
Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId();
List<GrantDto> grants = new ArrayList<>(); List<GrantDto> grants = new ArrayList<>();
for (Integer year : generateGrantYears()) { try (final WebClient webClient = new WebClient()) {
webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); for (Integer year : generateGrantYears()) {
grants.addAll(getKiasGrants(webDriver)); final HtmlPage page = webClient.getPage(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year));
grants.addAll(getKiasGrants(page));
}
} }
grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); grants.forEach(grantDto -> grantDto.setLeaderId(leaderId));
webDriver.quit();
return grants; return grants;
} }
public List<GrantDto> getKiasGrants(WebDriver webDriver) throws ParseException { private List<GrantDto> getKiasGrants(HtmlPage page) throws ParseException {
List<GrantDto> newGrants = new ArrayList<>(); List<GrantDto> newGrants = new ArrayList<>();
KiasPage kiasPage = new KiasPage(webDriver); KiasPage kiasPage = new KiasPage(page);
do { do {
newGrants.addAll(getGrantsFromPage(kiasPage)); newGrants.addAll(getGrantsFromPage(kiasPage));
} while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами
@ -56,11 +53,13 @@ public class KiasService {
private List<GrantDto> getGrantsFromPage(KiasPage kiasPage) throws ParseException { private List<GrantDto> getGrantsFromPage(KiasPage kiasPage) throws ParseException {
List<GrantDto> grants = new ArrayList<>(); List<GrantDto> grants = new ArrayList<>();
for (WebElement grantElement : kiasPage.getPageOfGrants()) { for (DomNode grantElement : kiasPage.getPageOfGrants()) {
GrantDto grantDto = new GrantDto( if (kiasPage.isTableRowGrantLine(grantElement)) {
kiasPage.getGrantTitle(grantElement), GrantDto grantDto = new GrantDto(
kiasPage.parseDeadLineDate(grantElement)); kiasPage.getGrantTitle(grantElement),
grants.add(grantDto); kiasPage.parseDeadLineDate(grantElement));
grants.add(grantDto);
}
} }
return grants; return grants;
} }
@ -69,24 +68,4 @@ public class KiasService {
return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR), return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.YEAR) + 1); Calendar.getInstance().get(Calendar.YEAR) + 1);
} }
private WebDriver getDriver() {
System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
return new ChromeDriver(chromeOptions);
}
private String getDriverExecutablePath() {
return KiasService.class.getClassLoader().getResource(
String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile();
}
private String getDriverExecutable(boolean isWindows) {
return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER;
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
} }

@ -8,13 +8,13 @@ public abstract class BaseService {
public BaseRepository baseRepository; public BaseRepository baseRepository;
public void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String checkField, String errorMessage) { protected void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String errorMessage) {
if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) {
errors.rejectValue(checkField, "errorCode", errorMessage); errors.rejectValue("title", "errorCode", errorMessage);
} }
} }
public String checkUniqueName(NameContainer nameContainer, Integer id) { protected String checkUniqueName(NameContainer nameContainer, Integer id) {
if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) {
return baseRepository.findByNameAndNotId(nameContainer.getName(), id); return baseRepository.findByNameAndNotId(nameContainer.getName(), id);
} }

@ -9,10 +9,10 @@ import ru.ulstu.odin.service.OdinService;
public abstract class OdinController<L, E extends OdinDto> { public abstract class OdinController<L, E extends OdinDto> {
public static final String META_LIST_URL = "/meta/list"; public static final String META_LIST_URL = "/meta/list";
public static final String META_ELEMENT_URL = "/meta/element"; private static final String META_ELEMENT_URL = "/meta/element";
private Class<L> listDtoClass; private final Class<L> listDtoClass;
private Class<E> elementDtoClass; private final Class<E> elementDtoClass;
@Autowired @Autowired
private OdinService<L, E> odinService; private OdinService<L, E> odinService;

@ -3,6 +3,7 @@ package ru.ulstu.odin.model;
import ru.ulstu.core.error.OdinException; import ru.ulstu.core.error.OdinException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@ -14,9 +15,9 @@ public class OdinCollectionField extends OdinField {
ParameterizedType genericType = (ParameterizedType) field.getGenericType(); ParameterizedType genericType = (ParameterizedType) field.getGenericType();
Type fieldElementClass = genericType.getActualTypeArguments()[0]; Type fieldElementClass = genericType.getActualTypeArguments()[0];
try { try {
OdinDto someInstance = (OdinDto) ((Class) (fieldElementClass)).newInstance(); OdinDto someInstance = (OdinDto) ((Class) (fieldElementClass)).getDeclaredConstructor().newInstance();
this.path = someInstance.getControllerPath(); this.path = someInstance.getControllerPath();
} catch (IllegalAccessException | InstantiationException e) { } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
throw new OdinException(String.format("Can't create new instance, check default constructor of %s", throw new OdinException(String.format("Can't create new instance, check default constructor of %s",
fieldElementClass.getTypeName())); fieldElementClass.getTypeName()));
} }

@ -1,13 +1,13 @@
package ru.ulstu.odin.model; package ru.ulstu.odin.model;
import com.fasterxml.jackson.annotation.JsonProperty; 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.core.error.OdinException;
import ru.ulstu.odin.model.annotation.OdinCaption; import ru.ulstu.odin.model.annotation.OdinCaption;
import ru.ulstu.odin.model.annotation.OdinReadOnly; import ru.ulstu.odin.model.annotation.OdinReadOnly;
import ru.ulstu.odin.model.annotation.OdinVisible; import ru.ulstu.odin.model.annotation.OdinVisible;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -31,15 +31,16 @@ public abstract class OdinField implements Comparable {
return this.name().toLowerCase(); return this.name().toLowerCase();
} }
} }
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) { private final OdinFieldType fieldType;
private final String fieldName;
private final String caption;
private final OdinVisible.OdinVisibleType visible;
private final boolean readOnly;
private final boolean notEmpty;
private final Field field;
OdinField(Field field, OdinFieldType fieldType) {
this.field = field; this.field = field;
this.fieldName = getFieldName(field); this.fieldName = getFieldName(field);
this.caption = Optional.ofNullable(getValueFromAnnotation(OdinCaption.class, "value")) this.caption = Optional.ofNullable(getValueFromAnnotation(OdinCaption.class, "value"))
@ -92,7 +93,7 @@ public abstract class OdinField implements Comparable {
} }
} }
protected <T> T getValue(Class<? extends Annotation> annotationClass, String valueName, Class<T> clazz) { <T> T getValue(Class<? extends Annotation> annotationClass, String valueName, Class<T> clazz) {
if (field.isAnnotationPresent(annotationClass)) { if (field.isAnnotationPresent(annotationClass)) {
return cast(getValueFromAnnotation(annotationClass, valueName), clazz); return cast(getValueFromAnnotation(annotationClass, valueName), clazz);
} }

@ -3,6 +3,7 @@ package ru.ulstu.odin.model;
import ru.ulstu.core.error.OdinException; import ru.ulstu.core.error.OdinException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
public class OdinObjectField extends OdinField { public class OdinObjectField extends OdinField {
@ -12,9 +13,9 @@ public class OdinObjectField extends OdinField {
super(field, OdinFieldType.OBJECT); super(field, OdinFieldType.OBJECT);
Type fieldElementClass = field.getType(); Type fieldElementClass = field.getType();
try { try {
OdinDto someInstance = (OdinDto) ((Class) (fieldElementClass)).newInstance(); OdinDto someInstance = (OdinDto) ((Class) (fieldElementClass)).getDeclaredConstructor().newInstance();
this.path = someInstance.getControllerPath(); this.path = someInstance.getControllerPath();
} catch (IllegalAccessException | InstantiationException e) { } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
throw new OdinException(String.format("Can't create new instance, check default constructor of %s", throw new OdinException(String.format("Can't create new instance, check default constructor of %s",
fieldElementClass.getTypeName())); fieldElementClass.getTypeName()));
} }

@ -1,9 +1,9 @@
package ru.ulstu.odin.model; 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;
import ru.ulstu.odin.model.annotation.OdinString.OdinStringType; import ru.ulstu.odin.model.annotation.OdinString.OdinStringType;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.lang.reflect.Field; import java.lang.reflect.Field;

@ -1,4 +0,0 @@
package ru.ulstu.odinexample.controller;
public class OdinExampleController {
}

@ -1,4 +0,0 @@
package ru.ulstu.odinexample.model;
public class OdinExampleDto {
}

@ -1,103 +0,0 @@
package ru.ulstu.odinexample.model;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.odin.model.annotation.OdinCaption;
import ru.ulstu.odin.model.annotation.OdinDate;
import ru.ulstu.odin.model.annotation.OdinNumeric;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
public class OdinExampleListDto {
@OdinCaption("instant")
@OdinDate(type = OdinDate.OdinDateType.DATETIME)
private Instant instant;
@OdinCaption("date")
private Date date;
@OdinCaption("localdate")
private LocalDate localDate;
@OdinCaption("localtime")
@OdinDate(type = OdinDate.OdinDateType.TIME)
private LocalTime localTime;
@OdinCaption("localdatetime")
@OdinDate(type = OdinDate.OdinDateType.DATETIME)
private LocalDateTime localDateTime;
@OdinCaption("int")
private int intval;
@OdinCaption("int+settings")
@OdinNumeric(precision = 5, scale = 2)
private int intvalset;
@OdinCaption("float")
private float floatval;
@OdinCaption("double")
private double aDouble;
@OdinCaption("double+set")
@OdinNumeric(precision = 5, scale = 3)
private double aDoubles;
@OdinCaption("int+positive")
@OdinNumeric(positiveOnly = true, scale = 2)
private int invalpos;
public OdinExampleListDto() {
this.instant = Instant.now();
this.date = new Date();
this.localDate = LocalDate.now();
this.localTime = LocalTime.now();
this.localDateTime = LocalDateTime.now();
intval = -134;
intvalset = 1343423232;
floatval = 2323.44F;
aDouble = -232323.43434;
aDoubles = 0.456456456;
invalpos = -23232323;
}
public Date getInstant() {
return DateUtils.instantToDate(instant);
}
public Date getDate() {
return date;
}
public Date getLocalDate() {
return DateUtils.localDateToDate(localDate);
}
public Date getLocalTime() {
return DateUtils.localTimeToDate(localTime);
}
public Date getLocalDateTime() {
return DateUtils.localDateTimeToDate(localDateTime);
}
public int getIntval() {
return intval;
}
public int getIntvalset() {
return intvalset;
}
public float getFloatval() {
return floatval;
}
public double getaDouble() {
return aDouble;
}
public double getaDoubles() {
return aDoubles;
}
public int getInvalpos() {
return invalpos;
}
}

@ -1,4 +0,0 @@
package ru.ulstu.odinexample.service;
public class OdinExampleService {
}

@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.response.Response; import ru.ulstu.core.model.response.Response;
@ -47,7 +48,7 @@ public class PaperRestController {
@GetMapping("/{paper-id}") @GetMapping("/{paper-id}")
public Response<PaperDto> getPaper(@PathVariable("paper-id") Integer paperId) { public Response<PaperDto> getPaper(@PathVariable("paper-id") Integer paperId) {
return new Response(paperService.findById(paperId)); return new Response<>(paperService.findById(paperId));
} }
@PostMapping @PostMapping
@ -63,7 +64,7 @@ public class PaperRestController {
@DeleteMapping("/{paper-id}") @DeleteMapping("/{paper-id}")
public Response<Boolean> delete(@PathVariable("paper-id") Integer paperId) throws IOException { public Response<Boolean> delete(@PathVariable("paper-id") Integer paperId) throws IOException {
paperService.delete(paperId); paperService.delete(paperId);
return new Response<>(true); return new Response<>(Boolean.TRUE);
} }
@PostMapping("/filter") @PostMapping("/filter")
@ -81,6 +82,11 @@ public class PaperRestController {
return new Response<>(paperService.getFormattedReference(referenceDto)); return new Response<>(paperService.getFormattedReference(referenceDto));
} }
@PostMapping(value = "/ping")
public void ping(@RequestParam("paperId") int paperId) throws IOException {
paperService.ping(paperId);
}
@GetMapping("/allAuthors") @GetMapping("/allAuthors")
public Response<List<User>> getAllAuthors() { public Response<List<User>> getAllAuthors() {
return new Response<>(paperService.getPaperAuthors()); return new Response<>(paperService.getPaperAuthors());

@ -1,7 +0,0 @@
package ru.ulstu.paper.error;
public class PaperConferenceRelationExistException extends RuntimeException {
public PaperConferenceRelationExistException(String message) {
super(message);
}
}

@ -2,10 +2,10 @@ package ru.ulstu.paper.model;
import org.hibernate.annotations.Fetch; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserContainer; import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
@ -14,6 +14,7 @@ import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
@ -24,6 +25,7 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy; import javax.persistence.OrderBy;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
@ -34,7 +36,8 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
@Entity @Entity
public class Paper extends BaseEntity implements UserContainer { @DiscriminatorValue("PAPER")
public class Paper extends BaseEntity implements UserActivity, EventSource {
public enum PaperStatus { public enum PaperStatus {
ATTENTION("Обратить внимание"), ATTENTION("Обратить внимание"),
ON_PREPARATION("На подготовке"), ON_PREPARATION("На подготовке"),
@ -45,7 +48,7 @@ public class Paper extends BaseEntity implements UserContainer {
DRAFT("Черновик"), DRAFT("Черновик"),
FAILED("Провалены сроки"); FAILED("Провалены сроки");
private String statusName; private final String statusName;
PaperStatus(String name) { PaperStatus(String name) {
this.statusName = name; this.statusName = name;
@ -62,7 +65,7 @@ public class Paper extends BaseEntity implements UserContainer {
SCOPUS("Scopus"), SCOPUS("Scopus"),
WEB_OF_SCIENCE("Web Of Science"); WEB_OF_SCIENCE("Web Of Science");
private String typeName; private final String typeName;
PaperType(String name) { PaperType(String name) {
this.typeName = name; this.typeName = name;
@ -196,6 +199,16 @@ public class Paper extends BaseEntity implements UserContainer {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return new ArrayList<>(authors);
}
@Override
public void addObjectToEvent(Event event) {
event.setPaper(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -249,7 +262,7 @@ public class Paper extends BaseEntity implements UserContainer {
} }
@Override @Override
public Set<User> getUsers() { public Set<User> getActivityUsers() {
return getAuthors(); return getAuthors();
} }

@ -3,11 +3,11 @@ package ru.ulstu.paper.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;

@ -8,7 +8,7 @@ public class ReferenceDto {
ARTICLE("Статья"), ARTICLE("Статья"),
BOOK("Книга"); BOOK("Книга");
private String typeName; private final String typeName;
ReferenceType(String name) { ReferenceType(String name) {
this.typeName = name; this.typeName = name;
@ -23,7 +23,7 @@ public class ReferenceDto {
GOST("ГОСТ"), GOST("ГОСТ"),
SPRINGER("Springer"); SPRINGER("Springer");
private String standardName; private final String standardName;
FormatStandard(String name) { FormatStandard(String name) {
this.standardName = name; this.standardName = name;

@ -12,11 +12,11 @@ import java.nio.file.Files;
@Service @Service
public class LatexService { public class LatexService {
private final String pdfLatexError = "Errors occurred while executing pdfLaTeX."; private static final String PDF_LATEX_ERROR = "Errors occurred while executing pdfLaTeX.";
private final String bibtexError = "Errors occurred while executing bibtex."; private static final String BIBTEX_ERROR = "Errors occurred while executing bibtex.";
private String errorMessage; private String errorMessage;
private File pdfFile; private File pdfFile;
private FileService fileService; private final FileService fileService;
public LatexService(FileService fileService) { public LatexService(FileService fileService) {
this.fileService = fileService; this.fileService = fileService;
@ -42,8 +42,9 @@ public class LatexService {
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream()); InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
while ((bufferedReader.readLine()) != null) { String line = bufferedReader.readLine();
// while (line != null) {
line = bufferedReader.readLine();
} }
} }
@ -55,9 +56,9 @@ public class LatexService {
} }
private boolean generate(String filename, File dir) throws IOException, InterruptedException { private boolean generate(String filename, File dir) throws IOException, InterruptedException {
startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, pdfLatexError); startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, PDF_LATEX_ERROR);
startProcess(new String[]{"bibtex", filename}, dir, bibtexError); startProcess(new String[]{"bibtex", filename}, dir, BIBTEX_ERROR);
if (startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, pdfLatexError) != 0) { if (startProcess(new String[]{"pdflatex", filename, "--interaction=nonstopmode"}, dir, PDF_LATEX_ERROR) != 0) {
return false; return false;
} }
return checkPdf(filename, dir); return checkPdf(filename, dir);

@ -11,12 +11,13 @@ import ru.ulstu.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperListDto; import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.Reference;
import ru.ulstu.paper.model.PaperStatusDto; import ru.ulstu.paper.model.PaperStatusDto;
import ru.ulstu.paper.model.PaperTypeDto; import ru.ulstu.paper.model.PaperTypeDto;
import ru.ulstu.paper.model.Reference;
import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.repository.PaperRepository; import ru.ulstu.paper.repository.PaperRepository;
import ru.ulstu.paper.repository.ReferenceRepository; import ru.ulstu.paper.repository.ReferenceRepository;
import ru.ulstu.ping.service.PingService;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
@ -56,6 +57,7 @@ public class PaperService {
private final FileService fileService; private final FileService fileService;
private final EventService eventService; private final EventService eventService;
private final ReferenceRepository referenceRepository; private final ReferenceRepository referenceRepository;
private final PingService pingService;
public PaperService(PaperRepository paperRepository, public PaperService(PaperRepository paperRepository,
ReferenceRepository referenceRepository, ReferenceRepository referenceRepository,
@ -63,7 +65,8 @@ public class PaperService {
PaperNotificationService paperNotificationService, PaperNotificationService paperNotificationService,
UserService userService, UserService userService,
DeadlineService deadlineService, DeadlineService deadlineService,
EventService eventService) { EventService eventService,
PingService pingService) {
this.paperRepository = paperRepository; this.paperRepository = paperRepository;
this.referenceRepository = referenceRepository; this.referenceRepository = referenceRepository;
this.fileService = fileService; this.fileService = fileService;
@ -71,6 +74,7 @@ public class PaperService {
this.userService = userService; this.userService = userService;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
this.eventService = eventService; this.eventService = eventService;
this.pingService = pingService;
} }
public List<Paper> findAll() { public List<Paper> findAll() {
@ -83,7 +87,7 @@ public class PaperService {
return papers; return papers;
} }
public List<Paper> findAllActive() { private List<Paper> findAllActive() {
return findAll() return findAll()
.stream() .stream()
.filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED) .filter(paper -> paper.getStatus() != COMPLETED && paper.getStatus() != FAILED)
@ -95,7 +99,7 @@ public class PaperService {
} }
public PaperDto findOneDto(Integer id) { public PaperDto findOneDto(Integer id) {
return new PaperDto(paperRepository.findOne(id)); return new PaperDto(paperRepository.getOne(id));
} }
@Transactional @Transactional
@ -137,7 +141,7 @@ public class PaperService {
return paper; return paper;
} }
public List<Reference> saveOrCreateReferences(List<ReferenceDto> references) { private List<Reference> saveOrCreateReferences(List<ReferenceDto> references) {
return references return references
.stream() .stream()
.filter(reference -> !reference.getDeleted()) .filter(reference -> !reference.getDeleted())
@ -146,15 +150,15 @@ public class PaperService {
} }
@Transactional @Transactional
public Reference updateReference(ReferenceDto referenceDto) { private Reference updateReference(ReferenceDto referenceDto) {
Reference updateReference = referenceRepository.findOne(referenceDto.getId()); Reference updateReference = referenceRepository.getOne(referenceDto.getId());
copyFromDto(updateReference, referenceDto); copyFromDto(updateReference, referenceDto);
referenceRepository.save(updateReference); referenceRepository.save(updateReference);
return updateReference; return updateReference;
} }
@Transactional @Transactional
public Reference createReference(ReferenceDto referenceDto) { private Reference createReference(ReferenceDto referenceDto) {
Reference newReference = new Reference(); Reference newReference = new Reference();
copyFromDto(newReference, referenceDto); copyFromDto(newReference, referenceDto);
newReference = referenceRepository.save(newReference); newReference = referenceRepository.save(newReference);
@ -174,7 +178,7 @@ public class PaperService {
@Transactional @Transactional
public Integer update(PaperDto paperDto) throws IOException { public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.findOne(paperDto.getId()); Paper paper = paperRepository.getOne(paperDto.getId());
Paper.PaperStatus oldStatus = paper.getStatus(); Paper.PaperStatus oldStatus = paper.getStatus();
Set<User> oldAuthors = new HashSet<>(paper.getAuthors()); Set<User> oldAuthors = new HashSet<>(paper.getAuthors());
@ -206,7 +210,7 @@ public class PaperService {
@Transactional @Transactional
public void delete(Integer paperId) { public void delete(Integer paperId) {
Paper paper = paperRepository.findOne(paperId); Paper paper = paperRepository.getOne(paperId);
paperRepository.delete(paper); paperRepository.delete(paper);
} }
@ -291,11 +295,11 @@ public class PaperService {
} }
public PaperDto findById(Integer paperId) { public PaperDto findById(Integer paperId) {
return new PaperDto(paperRepository.findOne(paperId)); return new PaperDto(paperRepository.getOne(paperId));
} }
public Paper findPaperById(Integer paperId) { public Paper findPaperById(Integer paperId) {
return paperRepository.findOne(paperId); return paperRepository.getOne(paperId);
} }
public List<Paper> findAllNotSelect(List<Integer> paperIds) { public List<Paper> findAllNotSelect(List<Integer> paperIds) {
@ -356,7 +360,7 @@ public class PaperService {
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public String getGostReference(ReferenceDto referenceDto) { private String getGostReference(ReferenceDto referenceDto) {
return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationTitle(), referenceDto.getPublicationTitle(),
@ -366,7 +370,7 @@ public class PaperService {
StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + ".");
} }
public String getSpringerReference(ReferenceDto referenceDto) { private String getSpringerReference(ReferenceDto referenceDto) {
return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "",
@ -388,4 +392,9 @@ public class PaperService {
autoCompleteData.setPublishers(referenceRepository.findDistinctPublishers()); autoCompleteData.setPublishers(referenceRepository.findDistinctPublishers());
return autoCompleteData; return autoCompleteData;
} }
@Transactional
public void ping(int paperId) throws IOException {
pingService.addPing(findPaperById(paperId));
}
} }

@ -1,12 +1,20 @@
package ru.ulstu.ping.model; package ru.ulstu.ping.model;
import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.annotations.Any;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
@ -25,9 +33,24 @@ public class Ping extends BaseEntity {
@JoinColumn(name = "users_id") @JoinColumn(name = "users_id")
private User user; private User user;
@ManyToOne(optional = false) @Column(name = "activity_type", insertable = false, updatable = false)
@JoinColumn(name = "conference_id") private String activityType;
private Conference conference;
@Any(
metaColumn = @Column(name = "activity_type"),
fetch = FetchType.LAZY
)
@AnyMetaDef(
idType = "integer", metaType = "string",
metaValues = {
@MetaValue(targetEntity = Conference.class, value = "CONFERENCE"),
@MetaValue(targetEntity = Paper.class, value = "PAPER"),
@MetaValue(targetEntity = Project.class, value = "PROJECT"),
@MetaValue(targetEntity = Grant.class, value = "GRANT")
}
)
@JoinColumn(name = "activity_id")
private UserActivity activity;
public Ping() { public Ping() {
} }
@ -37,16 +60,6 @@ public class Ping extends BaseEntity {
this.user = user; this.user = user;
} }
public Ping(@JsonProperty("id") Integer id,
@JsonProperty("date") Date date,
@JsonProperty("user") User user,
@JsonProperty("conference") Conference conference) {
setId(id);
this.date = date;
this.user = user;
this.conference = conference;
}
public Date getDate() { public Date getDate() {
return date; return date;
} }
@ -63,11 +76,11 @@ public class Ping extends BaseEntity {
this.user = user; this.user = user;
} }
public Conference getConference() { public UserActivity getActivity() {
return conference; return this.activity;
} }
public void setConference(Conference conference) { public void setActivity(UserActivity activity) {
this.conference = conference; this.activity = activity;
} }
} }

@ -0,0 +1,35 @@
package ru.ulstu.ping.model;
import ru.ulstu.user.model.User;
import java.util.ArrayList;
import java.util.List;
public class PingInfo {
private User user;
private List<Ping> pings = new ArrayList<>();
public PingInfo(User user) {
this.user = user;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Ping> getPings() {
return pings;
}
public void setPings(List<Ping> pings) {
this.pings = pings;
}
public void addPing(Ping ping) {
this.pings.add(ping);
}
}

@ -6,8 +6,17 @@ import org.springframework.data.repository.query.Param;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.ping.model.Ping; import ru.ulstu.ping.model.Ping;
import java.util.Date;
import java.util.List;
public interface PingRepository extends JpaRepository<Ping, Integer> { public interface PingRepository extends JpaRepository<Ping, Integer> {
@Query("SELECT count(*) FROM Ping p WHERE (DAY(p.date) = :day) AND (MONTH(p.date) = :month) AND (YEAR(p.date) = :year) AND (p.conference = :conference)") @Query("SELECT count(*) FROM Ping p WHERE (DAY(p.date) = :day) AND (MONTH(p.date) = :month) AND (YEAR(p.date) = :year) AND (p.activityType = 'conference') AND (p.activity = :conference)")
long countByConferenceAndDate(@Param("conference") Conference conference, @Param("day") Integer day, @Param("month") Integer month, @Param("year") Integer year); long countByConferenceAndDate(@Param("conference") Conference conference, @Param("day") Integer day, @Param("month") Integer month, @Param("year") Integer year);
@Query("SELECT p FROM Ping p WHERE (:activity = '' OR p.activityType = :activity)")
List<Ping> getPings(@Param("activity") String activity);
@Query("SELECT p FROM Ping p WHERE (:dateFrom < date)")
List<Ping> findByDate(@Param("dateFrom") Date dateFrom);
} }

@ -0,0 +1,58 @@
package ru.ulstu.ping.service;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.ping.model.Ping;
import ru.ulstu.ping.model.PingInfo;
import ru.ulstu.ping.repository.PingRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.MailService;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service
public class PingScheduler {
private final Logger log = LoggerFactory.getLogger(PingScheduler.class);
private final PingRepository pingRepository;
private final MailService mailService;
private final static String PING_MAIL_SUBJECT = "Ping статистика";
public PingScheduler(PingRepository pingRepository, MailService mailService) {
this.pingRepository = pingRepository;
this.mailService = mailService;
}
@Scheduled(cron = "0 0 * * 1 ?")
public void sendPingsInfo() {
log.debug("Scheduler.sendPingsInfo started");
List<PingInfo> pingInfos = new ArrayList<>();
for (Ping ping : pingRepository.findByDate(java.sql.Date.valueOf(LocalDate.now().minusWeeks(1)))) {
UserActivity pingActivity = ping.getActivity();
Set<User> users = pingActivity.getActivityUsers();
for (User user : users) {
PingInfo userPing = pingInfos.stream().filter(u -> u.getUser() == user).findFirst().orElse(null);
if (userPing == null) {
userPing = new PingInfo(user);
pingInfos.add(userPing);
}
userPing.addPing(ping);
}
}
for (PingInfo pingInfo : pingInfos) {
mailService.sendEmailFromTemplate(ImmutableMap.of("pings", pingInfo.getPings()),
pingInfo.getUser(), "pingsInfoWeekEmail", PING_MAIL_SUBJECT);
}
}
}

@ -3,6 +3,7 @@ package ru.ulstu.ping.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.ping.model.Ping; import ru.ulstu.ping.model.Ping;
import ru.ulstu.ping.repository.PingRepository; import ru.ulstu.ping.repository.PingRepository;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
@ -10,6 +11,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List;
@Service @Service
public class PingService { public class PingService {
@ -17,15 +19,16 @@ public class PingService {
private final UserService userService; private final UserService userService;
public PingService(PingRepository pingRepository, public PingService(PingRepository pingRepository,
UserService userService) { UserService userService,
PingScheduler pingScheduler) {
this.pingRepository = pingRepository; this.pingRepository = pingRepository;
this.userService = userService; this.userService = userService;
} }
@Transactional @Transactional
public Ping addPing(Conference conference) throws IOException { public Ping addPing(UserActivity activity) throws IOException {
Ping newPing = new Ping(new Date(), userService.getCurrentUser()); Ping newPing = new Ping(new Date(), userService.getCurrentUser());
newPing.setConference(conference); newPing.setActivity(activity);
return pingRepository.save(newPing); return pingRepository.save(newPing);
} }
@ -33,4 +36,8 @@ public class PingService {
return Math.toIntExact(pingRepository.countByConferenceAndDate(conference, calendar.get(Calendar.DAY_OF_MONTH), return Math.toIntExact(pingRepository.countByConferenceAndDate(conference, calendar.get(Calendar.DAY_OF_MONTH),
calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR))); calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.YEAR)));
} }
public List<Ping> getPings(String activity) {
return pingRepository.getPings(activity);
}
} }

@ -9,10 +9,13 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.project.model.Project; import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.service.ProjectService; import ru.ulstu.project.service.ProjectService;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid; import javax.validation.Valid;
@ -45,6 +48,8 @@ public class ProjectController {
@GetMapping("/project") @GetMapping("/project")
public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) { public void getProject(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) { if (id != null && id > 0) {
ProjectDto projectDto = projectService.findOneDto(id);
attachGrant(projectDto);
modelMap.put("projectDto", projectService.findOneDto(id)); modelMap.put("projectDto", projectService.findOneDto(id));
} else { } else {
modelMap.put("projectDto", new ProjectDto()); modelMap.put("projectDto", new ProjectDto());
@ -69,6 +74,12 @@ public class ProjectController {
return String.format("redirect:%s", "/projects/projects"); return String.format("redirect:%s", "/projects/projects");
} }
@PostMapping(value = "/project", params = "attachGrant")
public String attachGrant(ProjectDto projectDto) {
projectService.attachGrant(projectDto);
return "/projects/project";
}
@PostMapping(value = "/project", params = "addDeadline") @PostMapping(value = "/project", params = "addDeadline")
public String addDeadline(@Valid ProjectDto projectDto, Errors errors) { public String addDeadline(@Valid ProjectDto projectDto, Errors errors) {
filterEmptyDeadlines(projectDto); filterEmptyDeadlines(projectDto);
@ -79,15 +90,38 @@ public class ProjectController {
return "/projects/project"; return "/projects/project";
} }
@PostMapping(value = "/project", params = "removeDeadline")
public String removeDeadline(ProjectDto projectDto,
@RequestParam(value = "removeDeadline") Integer deadlineId) {
projectService.removeDeadline(projectDto, deadlineId);
return "/projects/project";
}
@GetMapping("/delete/{project-id}") @GetMapping("/delete/{project-id}")
public String delete(@PathVariable("project-id") Integer projectId) throws IOException { public String delete(@PathVariable("project-id") Integer projectId) throws IOException {
projectService.delete(projectId); projectService.delete(projectId);
return String.format("redirect:%s", "/projects/projects"); return String.format("redirect:%s", "/projects/projects");
} }
@ModelAttribute("allExecutors")
public List<User> getAllExecutors(ProjectDto projectDto) {
return projectService.getProjectExecutors(projectDto);
}
@ModelAttribute("allGrants")
public List<GrantDto> getAllGrants() {
return projectService.getAllGrants();
}
private void filterEmptyDeadlines(ProjectDto projectDto) { private void filterEmptyDeadlines(ProjectDto projectDto) {
projectDto.setDeadlines(projectDto.getDeadlines().stream() projectDto.setDeadlines(projectDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
@ResponseBody
@PostMapping(value = "/ping")
public void ping(@RequestParam("projectId") int projectId) throws IOException {
projectService.ping(projectId);
}
} }

@ -1,33 +1,48 @@
package ru.ulstu.project.model; package ru.ulstu.project.model;
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData; import ru.ulstu.file.model.FileData;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.EnumType; import javax.persistence.EnumType;
import javax.persistence.Enumerated; import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
@Entity @Entity
public class Project extends BaseEntity { @DiscriminatorValue("PROJECT")
public class Project extends BaseEntity implements UserActivity, EventSource {
public enum ProjectStatus { public enum ProjectStatus {
APPLICATION("Заявка"), TECHNICAL_TASK("Техническое задание"),
ON_COMPETITION("Отправлен на конкурс"), OPEN("Открыт"),
SUCCESSFUL_PASSAGE("Успешное прохождение"),
IN_WORK("В работе"), IN_WORK("В работе"),
COMPLETED("Завершен"), CERTIFICATE_ISSUED("Оформление свидетельства"),
CLOSED("Закрыт"),
FAILED("Провалены сроки"); FAILED("Провалены сроки");
private String statusName; private final String statusName;
ProjectStatus(String statusName) { ProjectStatus(String statusName) {
this.statusName = statusName; this.statusName = statusName;
@ -42,7 +57,7 @@ public class Project extends BaseEntity {
private String title; private String title;
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private ProjectStatus status = ProjectStatus.APPLICATION; private ProjectStatus status = ProjectStatus.TECHNICAL_TASK;
@NotNull @NotNull
private String description; private String description;
@ -58,14 +73,39 @@ public class Project extends BaseEntity {
@NotNull @NotNull
private String repository; private String repository;
@ManyToOne @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "file_id") @JoinColumn(name = "project_id", unique = true)
private FileData application; @Fetch(FetchMode.SUBSELECT)
private List<FileData> files = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "project_id")
private List<Event> events = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
private List<User> executors = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "project_grants",
joinColumns = {@JoinColumn(name = "project_id")},
inverseJoinColumns = {@JoinColumn(name = "grants_id")})
@Fetch(FetchMode.SUBSELECT)
private List<Grant> grants = new ArrayList<>();
public String getTitle() { public String getTitle() {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return executors != null ? new ArrayList<>(executors) : Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setProject(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -110,11 +150,44 @@ public class Project extends BaseEntity {
this.deadlines = deadlines; this.deadlines = deadlines;
} }
public FileData getApplication() { public List<FileData> getFiles() {
return application; return files;
}
public void setFiles(List<FileData> files) {
this.files = files;
}
public List<Event> getEvents() {
return events;
}
public void setEvents(List<Event> events) {
this.events = events;
}
public List<User> getExecutors() {
return executors;
}
public void setExecutors(List<User> executors) {
this.executors = executors;
}
public Set<User> getUsers() {
return new HashSet<>(getExecutors());
}
@Override
public Set<User> getActivityUsers() {
return new HashSet<>();
}
public List<Grant> getGrants() {
return grants;
} }
public void setApplication(FileData application) { public void setGrants(List<Grant> grants) {
this.application = application; this.grants = grants;
} }
} }

@ -2,12 +2,21 @@ package ru.ulstu.project.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty; import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert;
public class ProjectDto { public class ProjectDto {
private Integer id; private Integer id;
@ -19,7 +28,14 @@ public class ProjectDto {
private List<Deadline> deadlines = new ArrayList<>(); private List<Deadline> deadlines = new ArrayList<>();
private GrantDto grant; private GrantDto grant;
private String repository; private String repository;
private String applicationFileName; private List<FileDataDto> files = new ArrayList<>();
private List<Integer> removedDeadlineIds = new ArrayList<>();
private Set<Integer> executorIds;
private List<UserDto> executors;
private List<Integer> grantIds;
private List<GrantDto> grants;
private final static int MAX_EXECUTORS_LENGTH = 40;
public ProjectDto() { public ProjectDto() {
} }
@ -35,7 +51,12 @@ public class ProjectDto {
@JsonProperty("description") String description, @JsonProperty("description") String description,
@JsonProperty("grant") GrantDto grant, @JsonProperty("grant") GrantDto grant,
@JsonProperty("repository") String repository, @JsonProperty("repository") String repository,
@JsonProperty("deadlines") List<Deadline> deadlines) { @JsonProperty("files") List<FileDataDto> files,
@JsonProperty("deadlines") List<Deadline> deadlines,
@JsonProperty("executorIds") Set<Integer> executorIds,
@JsonProperty("executors") List<UserDto> executors,
@JsonProperty("grantIds") List<Integer> grantIds,
@JsonProperty("grants") List<GrantDto> grants) {
this.id = id; this.id = id;
this.title = title; this.title = title;
this.status = status; this.status = status;
@ -43,19 +64,28 @@ public class ProjectDto {
this.grant = grant; this.grant = grant;
this.repository = repository; this.repository = repository;
this.deadlines = deadlines; this.deadlines = deadlines;
this.applicationFileName = null; this.files = files;
this.executorIds = executorIds;
this.executors = executors;
this.grantIds = grantIds;
this.grants = grants;
} }
public ProjectDto(Project project) { public ProjectDto(Project project) {
Set<User> users = new HashSet<User>(project.getExecutors());
this.id = project.getId(); this.id = project.getId();
this.title = project.getTitle(); this.title = project.getTitle();
this.status = project.getStatus(); this.status = project.getStatus();
this.description = project.getDescription(); this.description = project.getDescription();
this.applicationFileName = project.getApplication() == null ? null : project.getApplication().getName(); this.files = convert(project.getFiles(), FileDataDto::new);
this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant()); this.grant = project.getGrant() == null ? null : new GrantDto(project.getGrant());
this.repository = project.getRepository(); this.repository = project.getRepository();
this.deadlines = project.getDeadlines(); this.deadlines = project.getDeadlines();
this.executorIds = convert(users, user -> user.getId());
this.executors = convert(project.getExecutors(), UserDto::new);
this.grantIds = convert(project.getGrants(), grant -> grant.getId());
this.grants = convert(project.getGrants(), GrantDto::new);
} }
public Integer getId() { public Integer getId() {
@ -114,11 +144,58 @@ public class ProjectDto {
this.deadlines = deadlines; this.deadlines = deadlines;
} }
public String getApplicationFileName() { public List<FileDataDto> getFiles() {
return applicationFileName; return files;
}
public void setFiles(List<FileDataDto> files) {
this.files = files;
}
public List<Integer> getRemovedDeadlineIds() {
return removedDeadlineIds;
}
public void setRemovedDeadlineIds(List<Integer> removedDeadlineIds) {
this.removedDeadlineIds = removedDeadlineIds;
}
public Set<Integer> getExecutorIds() {
return executorIds;
}
public void setExecutorIds(Set<Integer> executorIds) {
this.executorIds = executorIds;
}
public List<UserDto> getExecutors() {
return executors;
}
public void setExecutors(List<UserDto> executors) {
this.executors = executors;
}
public String getExecutorsString() {
return StringUtils.abbreviate(executors
.stream()
.map(executor -> executor.getLastName())
.collect(Collectors.joining(", ")), MAX_EXECUTORS_LENGTH);
}
public List<Integer> getGrantIds() {
return grantIds;
}
public void setGrantIds(List<Integer> grantIds) {
this.grantIds = grantIds;
}
public List<GrantDto> getGrants() {
return grants;
} }
public void setApplicationFileName(String applicationFileName) { public void setGrants(List<GrantDto> grants) {
this.applicationFileName = applicationFileName; this.grants = grants;
} }
} }

@ -4,19 +4,27 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils; import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService; import ru.ulstu.file.service.FileService;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.repository.GrantRepository; import ru.ulstu.grant.repository.GrantRepository;
import ru.ulstu.ping.service.PingService;
import ru.ulstu.project.model.Project; import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto; import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.repository.ProjectRepository; import ru.ulstu.project.repository.ProjectRepository;
import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty; import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.core.util.StreamApiUtils.convert;
import static ru.ulstu.project.model.Project.ProjectStatus.APPLICATION; import static ru.ulstu.project.model.Project.ProjectStatus.TECHNICAL_TASK;
@Service @Service
public class ProjectService { public class ProjectService {
@ -26,15 +34,24 @@ public class ProjectService {
private final DeadlineService deadlineService; private final DeadlineService deadlineService;
private final GrantRepository grantRepository; private final GrantRepository grantRepository;
private final FileService fileService; private final FileService fileService;
private final EventService eventService;
private final UserService userService;
private final PingService pingService;
public ProjectService(ProjectRepository projectRepository, public ProjectService(ProjectRepository projectRepository,
DeadlineService deadlineService, DeadlineService deadlineService,
GrantRepository grantRepository, GrantRepository grantRepository,
FileService fileService) { FileService fileService,
EventService eventService,
UserService userService,
PingService pingService) {
this.projectRepository = projectRepository; this.projectRepository = projectRepository;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
this.grantRepository = grantRepository; this.grantRepository = grantRepository;
this.fileService = fileService; this.fileService = fileService;
this.eventService = eventService;
this.userService = userService;
this.pingService = pingService;
} }
public List<Project> findAll() { public List<Project> findAll() {
@ -48,7 +65,7 @@ public class ProjectService {
} }
public ProjectDto findOneDto(Integer id) { public ProjectDto findOneDto(Integer id) {
return new ProjectDto(projectRepository.findOne(id)); return new ProjectDto(projectRepository.getOne(id));
} }
public List<Project.ProjectStatus> getProjectStatuses() { public List<Project.ProjectStatus> getProjectStatuses() {
@ -59,39 +76,48 @@ public class ProjectService {
public Project create(ProjectDto projectDto) throws IOException { public Project create(ProjectDto projectDto) throws IOException {
Project newProject = copyFromDto(new Project(), projectDto); Project newProject = copyFromDto(new Project(), projectDto);
newProject = projectRepository.save(newProject); newProject = projectRepository.save(newProject);
eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта");
return newProject; return newProject;
} }
@Transactional @Transactional
public Project update(ProjectDto projectDto) throws IOException { private Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.findOne(projectDto.getId()); Project project = projectRepository.getOne(projectDto.getId());
if (projectDto.getApplicationFileName() != null && project.getApplication() != null) {
fileService.deleteFile(project.getApplication());
}
projectRepository.save(copyFromDto(project, projectDto)); projectRepository.save(copyFromDto(project, projectDto));
eventService.updateProjectDeadlines(project);
for (FileDataDto file : projectDto.getFiles().stream()
.filter(f -> f.isDeleted() && f.getId() != null)
.collect(toList())) {
fileService.delete(file.getId());
}
return project; return project;
} }
@Transactional @Transactional
public void delete(Integer projectId) throws IOException { public boolean delete(Integer projectId) throws IOException {
Project project = projectRepository.findOne(projectId); if (projectRepository.existsById(projectId)) {
if (project.getApplication() != null) { Project project = projectRepository.getOne(projectId);
fileService.deleteFile(project.getApplication()); projectRepository.delete(project);
return true;
} }
projectRepository.delete(project); return false;
} }
private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException { private Project copyFromDto(Project project, ProjectDto projectDto) throws IOException {
project.setDescription(projectDto.getDescription()); project.setDescription(projectDto.getDescription());
project.setStatus(projectDto.getStatus() == null ? APPLICATION : projectDto.getStatus()); project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus());
project.setTitle(projectDto.getTitle()); project.setTitle(projectDto.getTitle());
if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) {
project.setGrant(grantRepository.findOne(projectDto.getGrant().getId())); project.setGrant(grantRepository.getOne(projectDto.getGrant().getId()));
} }
project.setRepository(projectDto.getRepository()); project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
if (projectDto.getApplicationFileName() != null) { project.setFiles(fileService.saveOrCreate(projectDto.getFiles().stream()
project.setApplication(fileService.createFileFromTmp(projectDto.getApplicationFileName())); .filter(f -> !f.isDeleted())
.collect(toList())));
project.getGrants().clear();
if (projectDto.getGrantIds() != null && !projectDto.getGrantIds().isEmpty()) {
projectDto.getGrantIds().forEach(grantIds -> project.getGrants().add(grantRepository.findGrantById(grantIds)));
} }
return project; return project;
} }
@ -104,8 +130,42 @@ public class ProjectService {
} }
} }
public ProjectDto removeDeadline(ProjectDto projectDto, Integer deadlineId) {
if (deadlineId != null) {
projectDto.getRemovedDeadlineIds().add(deadlineId);
}
projectDto.getDeadlines().remove((int) deadlineId);
return projectDto;
}
public Project findById(Integer id) { public Project findById(Integer id) {
return projectRepository.findOne(id); return projectRepository.getOne(id);
}
public List<User> getProjectExecutors(ProjectDto projectDto) {
return userService.findAll();
}
@Transactional
public void ping(int projectId) throws IOException {
pingService.addPing(findById(projectId));
}
public List<GrantDto> getAllGrants() {
return convert(grantRepository.findAll(), GrantDto::new);
}
private List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAllById(grantIds), GrantDto::new);
}
public void attachGrant(ProjectDto projectDto) {
if (!projectDto.getGrantIds().isEmpty()) {
projectDto.getGrants().clear();
projectDto.setGrants(getProjectGrants(projectDto.getGrantIds()));
} else {
projectDto.getGrants().clear();
}
} }
} }

@ -1,21 +1,21 @@
package ru.ulstu.strategy.api; package ru.ulstu.strategy.api;
import ru.ulstu.core.model.UserContainer; import ru.ulstu.core.model.UserActivity;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public abstract class EntityCreateStrategy<T extends UserContainer> { public abstract class EntityCreateStrategy<T extends UserActivity> {
protected abstract List<T> getActiveEntities(); protected abstract List<T> getActiveEntities();
protected abstract void createEntity(User user); protected abstract void createEntity(User user);
protected void createDefaultEntityIfNeed(List<User> allUsers, List<? extends UserContainer> entities) { private void createDefaultEntityIfNeed(List<User> allUsers, List<? extends UserActivity> entities) {
allUsers.forEach(user -> { allUsers.forEach(user -> {
if (entities if (entities
.stream() .stream()
.filter(entity -> entity.getUsers().contains(user)) .filter(entity -> entity.getActivityUsers().contains(user))
.collect(Collectors.toSet()).isEmpty()) { .collect(Collectors.toSet()).isEmpty()) {
createEntity(user); createEntity(user);
} }

@ -2,7 +2,7 @@ package ru.ulstu.students.controller;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
public class Navigation { class Navigation {
public static final String REDIRECT_TO = "redirect:%s"; public static final String REDIRECT_TO = "redirect:%s";
public static final String TASKS_PAGE = "/students/tasks"; public static final String TASKS_PAGE = "/students/tasks";
public static final String TASK_PAGE = "/students/task"; public static final String TASK_PAGE = "/students/task";

@ -2,10 +2,12 @@ package ru.ulstu.students.model;
import org.hibernate.annotations.Fetch; import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.tags.model.Tag; import ru.ulstu.tags.model.Tag;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
@ -20,12 +22,14 @@ import javax.persistence.OneToMany;
import javax.persistence.OrderBy; import javax.persistence.OrderBy;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@Entity @Entity
public class Task extends BaseEntity { public class Task extends BaseEntity implements EventSource {
public enum TaskStatus { public enum TaskStatus {
IN_WORK("В работе"), IN_WORK("В работе"),
@ -33,7 +37,7 @@ public class Task extends BaseEntity {
FAILED("Провалены сроки"), FAILED("Провалены сроки"),
LOADED_FROM_KIAS("Загружен автоматически"); LOADED_FROM_KIAS("Загружен автоматически");
private String statusName; private final String statusName;
TaskStatus(String name) { TaskStatus(String name) {
this.statusName = name; this.statusName = name;
@ -49,6 +53,10 @@ public class Task extends BaseEntity {
private String description; private String description;
public Task() {
}
@Enumerated(value = EnumType.STRING) @Enumerated(value = EnumType.STRING)
private TaskStatus status = TaskStatus.IN_WORK; private TaskStatus status = TaskStatus.IN_WORK;
@ -77,6 +85,16 @@ public class Task extends BaseEntity {
return title; return title;
} }
@Override
public List<User> getRecipients() {
return Collections.emptyList();
}
@Override
public void addObjectToEvent(Event event) {
event.setTask(this);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }

@ -3,10 +3,10 @@ package ru.ulstu.students.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.tags.model.Tag; import ru.ulstu.tags.model.Tag;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;

@ -38,8 +38,8 @@ public class SchedulerService {
@Transactional @Transactional
private void delete(Integer schedulerId) { private void delete(Integer schedulerId) {
if (schedulerRepository.exists(schedulerId)) { if (schedulerRepository.existsById(schedulerId)) {
schedulerRepository.delete(schedulerId); schedulerRepository.deleteById(schedulerId);
} }
} }

@ -21,6 +21,7 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -64,7 +65,7 @@ public class TaskService {
} }
public TaskDto findOneDto(Integer id) { public TaskDto findOneDto(Integer id) {
return new TaskDto(taskRepository.findOne(id)); return new TaskDto(taskRepository.getOne(id));
} }
public List<TaskDto> filter(TaskFilterDto filterDto) { public List<TaskDto> filter(TaskFilterDto filterDto) {
@ -83,7 +84,7 @@ public class TaskService {
public Integer create(TaskDto taskDto) throws IOException { public Integer create(TaskDto taskDto) throws IOException {
Task newTask = copyFromDto(new Task(), taskDto); Task newTask = copyFromDto(new Task(), taskDto);
newTask = taskRepository.save(newTask); newTask = taskRepository.save(newTask);
eventService.createFromTask(newTask); eventService.createFromObject(newTask, Collections.emptyList(), true, "задачи");
return newTask.getId(); return newTask.getId();
} }
@ -100,8 +101,8 @@ public class TaskService {
} }
@Transactional @Transactional
public Integer update(TaskDto taskDto) throws IOException { private Integer update(TaskDto taskDto) throws IOException {
Task task = taskRepository.findOne(taskDto.getId()); Task task = taskRepository.getOne(taskDto.getId());
taskRepository.save(copyFromDto(task, taskDto)); taskRepository.save(copyFromDto(task, taskDto));
eventService.updateTaskDeadlines(task); eventService.updateTaskDeadlines(task);
return task.getId(); return task.getId();
@ -109,13 +110,13 @@ public class TaskService {
@Transactional @Transactional
public boolean delete(Integer taskId) throws IOException { public boolean delete(Integer taskId) throws IOException {
if (taskRepository.exists(taskId)) { if (taskRepository.existsById(taskId)) {
Task scheduleTask = taskRepository.findOne(taskId); Task scheduleTask = taskRepository.getOne(taskId);
Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); Scheduler sch = schedulerRepository.findOneByTask(scheduleTask);
if (sch != null) { if (sch != null) {
schedulerRepository.delete(sch.getId()); schedulerRepository.deleteById(sch.getId());
} }
taskRepository.delete(taskId); taskRepository.deleteById(taskId);
return true; return true;
} }
return false; return false;

@ -2,12 +2,12 @@ package ru.ulstu.tags.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Table; import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.Objects; import java.util.Objects;

@ -33,17 +33,17 @@ public class TagService {
} }
@Transactional @Transactional
public Tag getExistById(Tag tag) { private Tag getExistById(Tag tag) {
return tagRepository.findOne(tag.getId()); return tagRepository.getOne(tag.getId());
} }
@Transactional @Transactional
public Tag isExistByName(String tagName) { private Tag isExistByName(String tagName) {
return tagRepository.findByName(tagName); return tagRepository.findByName(tagName);
} }
@Transactional @Transactional
public Tag create(Tag tag) { private Tag create(Tag tag) {
Tag newTag = new Tag(); Tag newTag = new Tag();
newTag.setTagName(tag.getTagName()); newTag.setTagName(tag.getTagName());
newTag = tagRepository.save(newTag); newTag = tagRepository.save(newTag);
@ -55,7 +55,7 @@ public class TagService {
} }
public Tag findById(Integer tagId) { public Tag findById(Integer tagId) {
return tagRepository.findOne(tagId); return tagRepository.getOne(tagId);
} }
} }

@ -16,12 +16,9 @@ import ru.ulstu.timeline.service.EventService;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List; import java.util.List;
import static ru.ulstu.timeline.controller.EventController.URL;
@RestController @RestController
@RequestMapping(URL) @RequestMapping(Constants.API_1_0 + "events")
public class EventController { public class EventController {
public static final String URL = Constants.API_1_0 + "events";
private final EventService eventService; private final EventService eventService;
@ -40,18 +37,18 @@ public class EventController {
} }
@PostMapping @PostMapping
public Response createEvent(@RequestBody @Valid EventDto timelineDto) { public Response<Integer> createEvent(@RequestBody @Valid EventDto timelineDto) {
return new Response(eventService.create(timelineDto)); return new Response<>(eventService.create(timelineDto));
} }
@PutMapping @PutMapping
public Response updateEvent(@RequestBody @Valid EventDto eventDto) { public Response<Integer> updateEvent(@RequestBody @Valid EventDto eventDto) {
return new Response(eventService.update(eventDto)); return new Response<>(eventService.update(eventDto));
} }
@DeleteMapping("/{event-id}") @DeleteMapping("/{event-id}")
public Response delete(@PathVariable("event-id") Integer eventId) { public Response<Boolean> delete(@PathVariable("event-id") Integer eventId) {
eventService.delete(eventId); eventService.delete(eventId);
return new Response(true); return new Response<>(Boolean.TRUE);
} }
} }

@ -1,10 +1,10 @@
package ru.ulstu.timeline.model; package ru.ulstu.timeline.model;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
@ -20,6 +20,7 @@ import javax.persistence.ManyToOne;
import javax.persistence.OneToMany; import javax.persistence.OneToMany;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
@ -30,7 +31,7 @@ public class Event extends BaseEntity {
public enum EventStatus { public enum EventStatus {
POSSIBLE("Возможное"), NEW("Новое"), IN_PROGRESS("В процессе"), COMPLETED("Завершено"); POSSIBLE("Возможное"), NEW("Новое"), IN_PROGRESS("В процессе"), COMPLETED("Завершено");
private String name; private final String name;
EventStatus(String name) { EventStatus(String name) {
this.name = name; this.name = name;
@ -88,6 +89,10 @@ public class Event extends BaseEntity {
@JoinColumn(name = "grant_id") @JoinColumn(name = "grant_id")
private Grant grant; private Grant grant;
@ManyToOne
@JoinColumn(name = "project_id")
private Project project;
@ManyToOne @ManyToOne
@JoinColumn(name = "task_id") @JoinColumn(name = "task_id")
private Task task; private Task task;
@ -196,6 +201,14 @@ public class Event extends BaseEntity {
this.grant = grant; this.grant = grant;
} }
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public Task getTask() { public Task getTask() {
return task; return task;
} }

@ -2,13 +2,14 @@ package ru.ulstu.timeline.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.students.model.TaskDto; import ru.ulstu.students.model.TaskDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -30,6 +31,7 @@ public class EventDto {
private PaperDto paperDto; private PaperDto paperDto;
private ConferenceDto conferenceDto; private ConferenceDto conferenceDto;
private GrantDto grantDto; private GrantDto grantDto;
private ProjectDto projectDto;
private TaskDto taskDto; private TaskDto taskDto;
@JsonCreator @JsonCreator
@ -45,6 +47,7 @@ public class EventDto {
@JsonProperty("recipients") List<UserDto> recipients, @JsonProperty("recipients") List<UserDto> recipients,
@JsonProperty("conferenceDto") ConferenceDto conferenceDto, @JsonProperty("conferenceDto") ConferenceDto conferenceDto,
@JsonProperty("grantDto") GrantDto grantDto, @JsonProperty("grantDto") GrantDto grantDto,
@JsonProperty("projectDto") ProjectDto projectDto,
@JsonProperty("taskDto") TaskDto taskDto) { @JsonProperty("taskDto") TaskDto taskDto) {
this.id = id; this.id = id;
this.title = title; this.title = title;
@ -58,6 +61,7 @@ public class EventDto {
this.paperDto = paperDto; this.paperDto = paperDto;
this.conferenceDto = conferenceDto; this.conferenceDto = conferenceDto;
this.grantDto = grantDto; this.grantDto = grantDto;
this.projectDto = projectDto;
this.taskDto = taskDto; this.taskDto = taskDto;
} }
@ -80,6 +84,9 @@ public class EventDto {
if (grantDto != null) { if (grantDto != null) {
this.grantDto = new GrantDto(event.getGrant()); this.grantDto = new GrantDto(event.getGrant());
} }
if (projectDto != null) {
this.projectDto = new ProjectDto(event.getProject());
}
if (taskDto != null) { if (taskDto != null) {
this.taskDto = new TaskDto(event.getTask()); this.taskDto = new TaskDto(event.getTask());
} }
@ -145,6 +152,14 @@ public class EventDto {
this.grantDto = grantDto; this.grantDto = grantDto;
} }
public ProjectDto getProjectDto() {
return projectDto;
}
public void setProjectDto(ProjectDto projectDto) {
this.projectDto = projectDto;
}
public TaskDto getTaskDto() { public TaskDto getTaskDto() {
return taskDto; return taskDto;
} }

@ -1,19 +0,0 @@
package ru.ulstu.timeline.model;
public class EventStatusDto {
private final String id;
private final String name;
public EventStatusDto(Event.EventStatus status) {
this.id = status.name();
this.name = status.getName();
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}

@ -8,8 +8,8 @@ public enum PeriodEvent {
EVERY_WEEK(Period.ofWeeks(1), "Каждую неделю"), EVERY_WEEK(Period.ofWeeks(1), "Каждую неделю"),
EVERY_DAY(Period.ofDays(1), "Каждый день"); EVERY_DAY(Period.ofDays(1), "Каждый день");
private Period period; private final Period period;
private String message; private final String message;
PeriodEvent(Period period, String message) { PeriodEvent(Period period, String message) {
this.period = period; this.period = period;

@ -5,6 +5,7 @@ import org.springframework.data.jpa.repository.Query;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
@ -23,5 +24,7 @@ public interface EventRepository extends JpaRepository<Event, Integer> {
List<Event> findAllByGrant(Grant grant); List<Event> findAllByGrant(Grant grant);
List<Event> findAllByProject(Project project);
List<Event> findAllByTask(Task task); List<Event> findAllByTask(Task task);
} }

@ -5,9 +5,11 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
import ru.ulstu.timeline.model.EventDto; import ru.ulstu.timeline.model.EventDto;
@ -16,7 +18,7 @@ import ru.ulstu.timeline.repository.EventRepository;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.util.ArrayList; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -47,7 +49,7 @@ public class EventService {
} }
@Transactional @Transactional
public int create(EventDto eventDto) { public Integer create(EventDto eventDto) {
return eventRepository.save(copyFromDto(new Event(), eventDto)).getId(); return eventRepository.save(copyFromDto(new Event(), eventDto)).getId();
} }
@ -65,7 +67,7 @@ public class EventService {
@Transactional @Transactional
public Integer update(EventDto eventDto) { public Integer update(EventDto eventDto) {
Event event = eventRepository.findOne(eventDto.getId()); Event event = eventRepository.getOne(eventDto.getId());
return eventRepository.save(copyFromDto(event, eventDto)).getId(); return eventRepository.save(copyFromDto(event, eventDto)).getId();
} }
@ -76,13 +78,13 @@ public class EventService {
@Transactional @Transactional
public void delete(Integer eventId) { public void delete(Integer eventId) {
Event event = eventRepository.findOne(eventId); Event event = eventRepository.getOne(eventId);
event.setParents(null); event.setParents(null);
eventRepository.delete(event); eventRepository.delete(event);
} }
public List<Event> findByIds(List<Integer> ids) { public List<Event> findByIds(List<Integer> ids) {
return eventRepository.findAll(ids); return eventRepository.findAllById(ids);
} }
public void createBasedOn(Event event, Date executeDate) { public void createBasedOn(Event event, Date executeDate) {
@ -97,46 +99,53 @@ public class EventService {
event = eventRepository.save(event); event = eventRepository.save(event);
//set child to parent //set child to parent
Event parentEvent = eventRepository.findOne(parentEventId); Event parentEvent = eventRepository.getOne(parentEventId);
parentEvent.setChild(event); parentEvent.setChild(event);
eventRepository.save(parentEvent); eventRepository.save(parentEvent);
} }
public void createFromPaper(Paper newPaper) { public void createFromPaper(Paper newPaper) {
createFromObject(newPaper, Collections.emptyList(), false, "статьи");
}
public void createFromObject(EventSource eventSource, List<Event> events, Boolean addCurrentUser, String suffix) {
List<Timeline> timelines = timelineService.findAll(); List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newPaper.getDeadlines() timeline.getEvents().removeAll(events);
for (Deadline deadline : eventSource.getDeadlines()
.stream() .stream()
.filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date())) .filter(d -> d.getDate().after(new Date()) || DateUtils.isSameDay(d.getDate(), new Date()))
.collect(Collectors.toList())) { .collect(Collectors.toList())) {
Event newEvent = new Event(); Event newEvent = new Event();
newEvent.setTitle("Дедлайн статьи"); newEvent.setTitle("Дедлайн " + suffix);
newEvent.setStatus(Event.EventStatus.NEW); newEvent.setStatus(Event.EventStatus.NEW);
newEvent.setExecuteDate(deadline.getDate()); newEvent.setExecuteDate(deadline.getDate());
newEvent.setCreateDate(new Date()); newEvent.setCreateDate(new Date());
newEvent.setUpdateDate(new Date()); newEvent.setUpdateDate(new Date());
newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' cтатьи '" + newPaper.getTitle() + "'"); newEvent.setDescription("Дедлайн '" + deadline.getDescription() + "' " + suffix + " '"
newEvent.setRecipients(new ArrayList(newPaper.getAuthors())); + eventSource.getTitle() + "'");
newEvent.setPaper(newPaper); if (addCurrentUser) {
eventRepository.save(newEvent); newEvent.getRecipients().add(userService.getCurrentUser());
}
timeline.getEvents().add(newEvent); newEvent.setRecipients(eventSource.getRecipients());
timelineService.save(timeline); eventSource.addObjectToEvent(newEvent);
timeline.getEvents().add(eventRepository.save(newEvent));
} }
timelineService.save(timeline);
} }
public void updatePaperDeadlines(Paper paper) { public void updatePaperDeadlines(Paper paper) {
eventRepository.delete(eventRepository.findAllByPaper(paper)); List<Event> foundEvents = eventRepository.findAllByPaper(paper);
eventRepository.deleteAll(foundEvents);
createFromPaper(paper); createFromObject(paper, foundEvents, false, "статьи");
} }
public List<Event> findByCurrentDate() { public List<Event> findByCurrentDate() {
return eventRepository.findByCurrentDate(); return eventRepository.findByCurrentDate();
} }
public List<Event> findAllFuture() { private List<Event> findAllFuture() {
return eventRepository.findAllFuture(); return eventRepository.findAllFuture();
} }
@ -144,98 +153,28 @@ public class EventService {
return convert(findAllFuture(), EventDto::new); return convert(findAllFuture(), EventDto::new);
} }
public void createFromConference(Conference newConference) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newConference.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() + "' конференции '" + newConference.getTitle() + "'");
newConference.getUsers().forEach(conferenceUser -> newEvent.getRecipients().add(conferenceUser.getUser()));
newEvent.setConference(newConference);
save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
}
public void updateConferenceDeadlines(Conference conference) { public void updateConferenceDeadlines(Conference conference) {
eventRepository.delete(eventRepository.findAllByConference(conference)); eventRepository.deleteAll(eventRepository.findAllByConference(conference));
createFromConference(conference); createFromObject(conference, Collections.emptyList(), false, "конференции");
} }
public void createFromGrant(Grant newGrant) { public void updateGrantDeadlines(Grant grant) {
List<Timeline> timelines = timelineService.findAll(); eventRepository.deleteAll(eventRepository.findAllByGrant(grant));
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0); createFromObject(grant, Collections.emptyList(), false, "гранта");
for (Deadline deadline : newGrant.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() + "' гранта '" + newGrant.getTitle() + "'");
if (newGrant.getAuthors() != null) {
newEvent.setRecipients(new ArrayList(newGrant.getAuthors()));
}
newEvent.getRecipients().add(newGrant.getLeader());
newEvent.setGrant(newGrant);
eventRepository.save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
} }
public void updateGrantDeadlines(Grant grant) { public void updateProjectDeadlines(Project project) {
eventRepository.delete(eventRepository.findAllByGrant(grant)); eventRepository.deleteAll(eventRepository.findAllByProject(project));
createFromGrant(grant); createFromObject(project, Collections.emptyList(), false, "проекта");
} }
public void removeConferencesEvent(Conference conference) { public void removeConferencesEvent(Conference conference) {
List<Event> eventList = eventRepository.findAllByConference(conference); List<Event> eventList = eventRepository.findAllByConference(conference);
eventList.forEach(event -> eventRepository.delete(event.getId())); eventList.forEach(event -> eventRepository.deleteById(event.getId()));
}
public void createFromTask(Task newTask) {
List<Timeline> timelines = timelineService.findAll();
Timeline timeline = timelines.isEmpty() ? new Timeline() : timelines.get(0);
for (Deadline deadline : newTask.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() + "' задачи '" + newTask.getTitle() + "'");
newEvent.getRecipients().add(userService.getCurrentUser());
newEvent.setTask(newTask);
eventRepository.save(newEvent);
timeline.getEvents().add(newEvent);
timelineService.save(timeline);
}
} }
public void updateTaskDeadlines(Task task) { public void updateTaskDeadlines(Task task) {
eventRepository.delete(eventRepository.findAllByTask(task)); eventRepository.deleteAll(eventRepository.findAllByTask(task));
createFromTask(task); createFromObject(task, Collections.emptyList(), true, "задачи");
} }
} }

@ -48,13 +48,13 @@ public class TimelineService {
@Transactional @Transactional
public Integer update(TimelineDto timelineDto) { public Integer update(TimelineDto timelineDto) {
Timeline timeline = timelineRepository.findOne(timelineDto.getId()); Timeline timeline = timelineRepository.getOne(timelineDto.getId());
return timelineRepository.save(copyFromDto(timeline, timelineDto)).getId(); return timelineRepository.save(copyFromDto(timeline, timelineDto)).getId();
} }
@Transactional @Transactional
public void delete(Integer timelineId) { public void delete(Integer timelineId) {
Timeline timeline = timelineRepository.findOne(timelineId); Timeline timeline = timelineRepository.getOne(timelineId);
timelineRepository.delete(timeline); timelineRepository.delete(timeline);
} }
} }

@ -4,7 +4,7 @@ import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
public final class IpAddressResolver { final class IpAddressResolver {
private static final String CLIENT_IP_HEADER = "Client-IP"; private static final String CLIENT_IP_HEADER = "Client-IP";
private static final String FORWARDED_FOR_HEADER = "X-Forwarded-For"; private static final String FORWARDED_FOR_HEADER = "X-Forwarded-For";

@ -3,7 +3,6 @@ package ru.ulstu.user.controller;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.annotation.Secured;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -33,7 +32,6 @@ import ru.ulstu.user.service.UserSessionService;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.Map; import java.util.Map;
import static ru.ulstu.user.controller.UserController.URL; import static ru.ulstu.user.controller.UserController.URL;
@ -43,9 +41,9 @@ import static ru.ulstu.user.controller.UserController.URL;
public class UserController extends OdinController<UserListDto, UserDto> { public class UserController extends OdinController<UserListDto, UserDto> {
public static final String URL = Constants.API_1_0 + "users"; public static final String URL = Constants.API_1_0 + "users";
public static final String ROLES_URL = "/roles"; public static final String ROLES_URL = "/roles";
public static final String ROLES_META_URL = ROLES_URL + OdinController.META_LIST_URL; private static final String ROLES_META_URL = ROLES_URL + OdinController.META_LIST_URL;
public static final String SESSIONS_URL = "/sessions"; private static final String SESSIONS_URL = "/sessions";
public static final String SESSIONS_META_URL = SESSIONS_URL + OdinController.META_LIST_URL; private static final String SESSIONS_META_URL = SESSIONS_URL + OdinController.META_LIST_URL;
public static final String REGISTER_URL = "/register"; public static final String REGISTER_URL = "/register";
public static final String ACTIVATE_URL = "/activate"; public static final String ACTIVATE_URL = "/activate";
public static final String PASSWORD_RESET_REQUEST_URL = "/password-reset-request"; public static final String PASSWORD_RESET_REQUEST_URL = "/password-reset-request";
@ -171,4 +169,15 @@ public class UserController extends OdinController<UserListDto, UserDto> {
public void inviteUser(@RequestParam("email") String email) { public void inviteUser(@RequestParam("email") String email) {
userService.inviteUser(email); userService.inviteUser(email);
} }
@GetMapping("/activities/pings")
public Response<Map<String, Integer>> getActivitesStats(@RequestParam(value = "userId", required = false) Integer userId,
@RequestParam(value = "activity", required = false) String activity) {
return new Response<>(userService.getActivitiesPings(userId, activity));
}
@PostMapping("/block")
public void blockUser(@RequestParam("userId") Integer userId) {
userService.blockUser(userId);
}
} }

@ -1,22 +1,26 @@
package ru.ulstu.user.controller; package ru.ulstu.user.controller;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import ru.ulstu.odin.controller.OdinController; import ru.ulstu.odin.controller.OdinController;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import ru.ulstu.user.service.UserSessionService; import ru.ulstu.user.service.UserSessionService;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
@Controller @Controller
@RequestMapping(value = "/users") @RequestMapping(value = "/users")
@ -48,4 +52,23 @@ public class UserMvcController extends OdinController<UserListDto, UserDto> {
User user = userSessionService.getUserBySessionId(sessionId); User user = userSessionService.getUserBySessionId(sessionId);
modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
} }
@GetMapping("/dashboard")
public void getUsersDashboard(ModelMap modelMap) {
modelMap.addAllAttributes(userService.getUsersInfo());
}
@ModelAttribute("allUsers")
public List<User> getAllUsers() {
return userService.findAll();
}
@ModelAttribute("allActivities")
public Map<String, String> getAllActivites() {
return ImmutableMap.of("PAPER", "Статьи",
"GRANT", "Гранты",
"PROJECT", "Проекты",
"CONFERENCE", "Конференции");
}
} }

@ -0,0 +1,9 @@
package ru.ulstu.user.error;
import org.springframework.security.core.AuthenticationException;
public class UserBlockedException extends AuthenticationException {
public UserBlockedException(String message) {
super(message);
}
}

@ -1,7 +1,6 @@
package ru.ulstu.user.model; package ru.ulstu.user.model;
import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.BatchSize;
import org.hibernate.validator.constraints.Email;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
@ -12,9 +11,11 @@ import javax.persistence.Enumerated;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.JoinTable; import javax.persistence.JoinTable;
import javax.persistence.ManyToMany; import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern; import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
@ -91,11 +92,15 @@ public class User extends BaseEntity {
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
private Date birthDate; private Date birthDate;
@ManyToOne()
@JoinColumn(name = "blocker_id")
private User blocker;
public enum UserDegree { public enum UserDegree {
CANDIDATE("Кандидат технических наук"), CANDIDATE("Кандидат технических наук"),
DOCTOR("Доктор технических наук"); DOCTOR("Доктор технических наук");
private String degreeName; private final String degreeName;
UserDegree(String degreeName) { UserDegree(String degreeName) {
this.degreeName = degreeName; this.degreeName = degreeName;
@ -229,6 +234,14 @@ public class User extends BaseEntity {
this.degree = degree; this.degree = degree;
} }
public User getBlocker() {
return blocker;
}
public void setBlocker(User blocker) {
this.blocker = blocker;
}
public String getUserAbbreviate() { public String getUserAbbreviate() {
return String.format(USER_ABBREVIATE_TEMPLATE, return String.format(USER_ABBREVIATE_TEMPLATE,
lastName == null ? "" : lastName, lastName == null ? "" : lastName,

@ -1,8 +1,6 @@
package ru.ulstu.user.model; package ru.ulstu.user.model;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import ru.ulstu.odin.model.OdinDto; import ru.ulstu.odin.model.OdinDto;
@ -12,6 +10,8 @@ import ru.ulstu.odin.model.annotation.OdinString;
import ru.ulstu.odin.model.annotation.OdinVisible; import ru.ulstu.odin.model.annotation.OdinVisible;
import ru.ulstu.user.controller.UserController; 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.Pattern;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.Collection; import java.util.Collection;
@ -53,7 +53,7 @@ public class UserDto implements OdinDto {
private boolean activated; private boolean activated;
@OdinCaption("Роли") @OdinCaption("Роли")
private LinkedHashSet<UserRoleDto> roles; private final LinkedHashSet<UserRoleDto> roles;
@OdinString(type = PASSWORD) @OdinString(type = PASSWORD)
@OdinVisible(type = OdinVisible.OdinVisibleType.ON_UPDATE) @OdinVisible(type = OdinVisible.OdinVisibleType.ON_UPDATE)
@ -189,9 +189,9 @@ public class UserDto implements OdinDto {
@JsonIgnore @JsonIgnore
public boolean isPasswordsValid() { public boolean isPasswordsValid() {
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordConfirm)) { if (StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordConfirm)) {
return false; return true;
} }
return Objects.equals(password, passwordConfirm); return !Objects.equals(password, passwordConfirm);
} }
@JsonIgnore @JsonIgnore

@ -0,0 +1,50 @@
package ru.ulstu.user.model;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.utils.timetable.model.Lesson;
public class UserInfoNow {
private Lesson lesson;
private Conference conference;
private User user;
private boolean isOnline;
public UserInfoNow(Lesson lesson, Conference conference, User user, boolean isOnline) {
this.lesson = lesson;
this.conference = conference;
this.user = user;
this.isOnline = isOnline;
}
public Lesson getLesson() {
return lesson;
}
public void setLesson(Lesson lesson) {
this.lesson = lesson;
}
public Conference getConference() {
return conference;
}
public void setConference(Conference conference) {
this.conference = conference;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isOnline() {
return isOnline;
}
public void setOnline(boolean online) {
isOnline = online;
}
}

@ -11,19 +11,19 @@ import java.util.Optional;
public class UserListDto implements OdinDto { public class UserListDto implements OdinDto {
@OdinVisible(type = OdinVisible.OdinVisibleType.NONE) @OdinVisible(type = OdinVisible.OdinVisibleType.NONE)
private int id; private final int id;
@OdinCaption("Логин") @OdinCaption("Логин")
private String login; private final String login;
@OdinCaption("Имя") @OdinCaption("Имя")
private String firstName; private final String firstName;
@OdinCaption("Фамилия") @OdinCaption("Фамилия")
private String lastName; private final String lastName;
@OdinCaption("E-Mail") @OdinCaption("E-Mail")
private String email; private final String email;
@OdinCaption("Аккаунт активен") @OdinCaption("Аккаунт активен")
private boolean activated; private final boolean activated;
@OdinCaption("Права администратора") @OdinCaption("Права администратора")
private boolean admin; private final boolean admin;
public UserListDto(User user) { public UserListDto(User user) {
this.id = user.getId(); this.id = user.getId();

@ -1,8 +1,8 @@
package ru.ulstu.user.model; package ru.ulstu.user.model;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import java.util.Objects; import java.util.Objects;

@ -7,19 +7,19 @@ import java.util.Date;
public class UserSessionListDto { public class UserSessionListDto {
@OdinCaption("Сессия") @OdinCaption("Сессия")
private String sessionId; private final String sessionId;
@OdinCaption("Пользователь") @OdinCaption("Пользователь")
private String login; private final String login;
@OdinCaption("IP адрес") @OdinCaption("IP адрес")
private String ipAddress; private final String ipAddress;
@OdinCaption("Хост") @OdinCaption("Хост")
private String host; private final String host;
@OdinCaption("Вход") @OdinCaption("Вход")
@OdinDate(type = OdinDate.OdinDateType.DATETIME) @OdinDate(type = OdinDate.OdinDateType.DATETIME)
private Date loginTime; private final Date loginTime;
@OdinCaption("Выход") @OdinCaption("Выход")
@OdinDate(type = OdinDate.OdinDateType.DATETIME) @OdinDate(type = OdinDate.OdinDateType.DATETIME)
private Date logoutTime; private final Date logoutTime;
public UserSessionListDto(UserSession userSession) { public UserSessionListDto(UserSession userSession) {
this.sessionId = userSession.getSessionId(); this.sessionId = userSession.getSessionId();

@ -1,6 +1,7 @@
package ru.ulstu.user.repository; package ru.ulstu.user.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserSession; import ru.ulstu.user.model.UserSession;
import java.util.Date; import java.util.Date;
@ -10,4 +11,6 @@ public interface UserSessionRepository extends JpaRepository<UserSession, Intege
UserSession findOneBySessionId(String sessionId); UserSession findOneBySessionId(String sessionId);
List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date); List<UserSession> findAllByLogoutTimeIsNullAndLoginTimeBefore(Date date);
List<UserSession> findAllByUserAndLogoutTimeIsNullAndLoginTimeBefore(User user, Date date);
} }

@ -10,7 +10,7 @@ import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context; import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring5.SpringTemplateEngine;
import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.configuration.Constants; import ru.ulstu.configuration.Constants;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
@ -39,7 +39,7 @@ public class MailService {
} }
@Async @Async
public void sendEmail(String to, String subject, String content) throws MessagingException, MailException { private void sendEmail(String to, String subject, String content) throws MessagingException, MailException {
log.debug("Send email to '{}' with subject '{}'", to, subject); log.debug("Send email to '{}' with subject '{}'", to, subject);
MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name()); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name());
@ -60,7 +60,7 @@ public class MailService {
} }
@Async @Async
public void sendEmailFromTemplate(User user, String templateName, String subject) { private void sendEmailFromTemplate(User user, String templateName, String subject) {
Context context = new Context(); Context context = new Context();
context.setVariable(USER, user); context.setVariable(USER, user);
context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); context.setVariable(BASE_URL, applicationProperties.getBaseUrl());
@ -99,7 +99,7 @@ public class MailService {
} }
@Async @Async
public void sendEmailFromTemplate(Map<String, Object> variables, String templateName, String subject, String email) private void sendEmailFromTemplate(Map<String, Object> variables, String templateName, String subject, String email)
throws MessagingException { throws MessagingException {
Context context = new Context(); Context context = new Context();
variables.entrySet().forEach(entry -> context.setVariable(entry.getKey(), entry.getValue())); variables.entrySet().forEach(entry -> context.setVariable(entry.getKey(), entry.getValue()));

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save