diff --git a/build.gradle b/build.gradle index 38de2c7..71c9977 100644 --- a/build.gradle +++ b/build.gradle @@ -126,6 +126,6 @@ dependencies { compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test' - testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' + compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1' } \ No newline at end of file diff --git a/deploy/gdccloud/deploy.sh b/deploy/gdccloud/deploy.sh index 26604b7..de785fd 100644 --- a/deploy/gdccloud/deploy.sh +++ b/deploy/gdccloud/deploy.sh @@ -18,6 +18,6 @@ fi 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 -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 >> /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 >> /home/user/logfile_$ARTIFACT_NAME" & sleep 10 echo "is deployed" \ No newline at end of file diff --git a/src/main/java/ru/ulstu/conference/model/Conference.java b/src/main/java/ru/ulstu/conference/model/Conference.java index 7e18ac0..4df1a1f 100644 --- a/src/main/java/ru/ulstu/conference/model/Conference.java +++ b/src/main/java/ru/ulstu/conference/model/Conference.java @@ -42,12 +42,12 @@ public class Conference extends BaseEntity { @Column(name = "begin_date") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd") - private Date beginDate; + private Date beginDate = new Date(); @Column(name = "end_date") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd") - private Date endDate; + private Date endDate = new Date(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "conference_id", unique = true) diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java index 9c9b37a..5759f4e 100644 --- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java +++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java @@ -14,6 +14,7 @@ import javax.validation.constraints.Size; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import static ru.ulstu.core.util.StreamApiUtils.convert; @@ -219,4 +220,33 @@ public class ConferenceDto extends NameContainer { return BEGIN_DATE + beginDate.toString().split(" ")[0] + " " + END_DATE + endDate.toString().split(" ")[0]; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConferenceDto that = (ConferenceDto) o; + return ping == that.ping && + disabledTakePart == that.disabledTakePart && + Objects.equals(id, that.id) && + Objects.equals(title, that.title) && + Objects.equals(description, that.description) && + Objects.equals(url, that.url) && + Objects.equals(deadlines, that.deadlines) && + Objects.equals(removedDeadlineIds, that.removedDeadlineIds) && + Objects.equals(userIds, that.userIds) && + Objects.equals(paperIds, that.paperIds) && + Objects.equals(papers, that.papers) && + Objects.equals(notSelectedPapers, that.notSelectedPapers) && + Objects.equals(users, that.users); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, description, url, ping, beginDate, endDate, deadlines, removedDeadlineIds, + userIds, paperIds, papers, notSelectedPapers, users, disabledTakePart); + } } diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java index 7a36e47..4ee4198 100644 --- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java +++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java @@ -16,6 +16,7 @@ import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.name.BaseService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.service.PaperService; +import ru.ulstu.ping.model.Ping; import ru.ulstu.ping.service.PingService; import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; @@ -64,7 +65,7 @@ public class ConferenceService extends BaseService { } public ConferenceDto getExistConferenceById(Integer id) { - ConferenceDto conferenceDto = findOneDto(id); + ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.findOne(id)); conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds())); conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers())); return conferenceDto; @@ -72,7 +73,7 @@ public class ConferenceService extends BaseService { public ConferenceDto getNewConference() { ConferenceDto conferenceDto = new ConferenceDto(); - conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList())); + conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList<>())); return conferenceDto; } @@ -87,14 +88,11 @@ public class ConferenceService extends BaseService { return conferences; } - public ConferenceDto findOneDto(Integer id) { - return new ConferenceDto(conferenceRepository.findOne(id)); - } - public boolean save(ConferenceDto conferenceDto, Errors errors) throws IOException { conferenceDto.setName(conferenceDto.getTitle()); filterEmptyDeadlines(conferenceDto); checkEmptyFieldsOfDeadline(conferenceDto, errors); + checkEmptyFieldsOfDates(conferenceDto, errors); checkUniqueName(conferenceDto, errors, conferenceDto.getId(), @@ -114,16 +112,16 @@ public class ConferenceService extends BaseService { } @Transactional - public Integer create(ConferenceDto conferenceDto) throws IOException { + public Conference create(ConferenceDto conferenceDto) throws IOException { Conference newConference = copyFromDto(new Conference(), conferenceDto); newConference = conferenceRepository.save(newConference); conferenceNotificationService.sendCreateNotification(newConference); eventService.createFromConference(newConference); - return newConference.getId(); + return newConference; } @Transactional - public Integer update(ConferenceDto conferenceDto) throws IOException { + public Conference update(ConferenceDto conferenceDto) throws IOException { Conference conference = conferenceRepository.findOne(conferenceDto.getId()); List oldDeadlines = conference.getDeadlines().stream() .map(this::copyDeadline) @@ -137,50 +135,56 @@ public class ConferenceService extends BaseService { conferenceNotificationService.updateConferencesDatesNotification(conference, oldBeginDate, oldEndDate); } conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove); - return conference.getId(); + return conference; } @Transactional - public void delete(Integer conferenceId) { + public boolean delete(Integer conferenceId) { if (conferenceRepository.exists(conferenceId)) { eventService.removeConferencesEvent(conferenceRepository.findOne(conferenceId)); conferenceRepository.delete(conferenceId); + return true; } + return false; } - public void addDeadline(ConferenceDto conferenceDto) { + public ConferenceDto addDeadline(ConferenceDto conferenceDto) { conferenceDto.getDeadlines().add(new Deadline()); + return conferenceDto; } - public void removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException { + public ConferenceDto removeDeadline(ConferenceDto conferenceDto, Integer deadlineIndex) throws IOException { if (conferenceDto.getDeadlines().get(deadlineIndex).getId() != null) { conferenceDto.getRemovedDeadlineIds().add(conferenceDto.getDeadlines().get(deadlineIndex).getId()); } conferenceDto.getDeadlines().remove((int) deadlineIndex); + return conferenceDto; } - public void addPaper(ConferenceDto conferenceDto) { + public ConferenceDto addPaper(ConferenceDto conferenceDto) { Paper paper = new Paper(); paper.setTitle(userService.getCurrentUser().getLastName() + "_" + conferenceDto.getTitle() + "_" + (new Date()).getTime()); paper.setStatus(Paper.PaperStatus.DRAFT); - conferenceDto.getPapers().add(paper); + return conferenceDto; } - public void removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { + public ConferenceDto removePaper(ConferenceDto conferenceDto, Integer paperIndex) throws IOException { Paper removedPaper = conferenceDto.getPapers().remove((int) paperIndex); if (removedPaper.getId() != null) { conferenceDto.getNotSelectedPapers().add(removedPaper); } + return conferenceDto; } - public void takePart(ConferenceDto conferenceDto) throws IOException { + public ConferenceDto takePart(ConferenceDto conferenceDto) throws IOException { conferenceDto.getUsers().add(new ConferenceUser(userService.getCurrentUser())); conferenceDto.setDisabledTakePart(true); + return conferenceDto; } - public List getNotSelectPapers(List paperIds) { + private List getNotSelectPapers(List paperIds) { return paperService.findAllNotSelect(paperIds); } @@ -214,7 +218,7 @@ public class ConferenceService extends BaseService { } - public boolean isCurrentUserParticipant(List conferenceUsers) { + private boolean isCurrentUserParticipant(List conferenceUsers) { return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser())); } @@ -229,7 +233,7 @@ public class ConferenceService extends BaseService { return convert(findAllActive(), ConferenceDto::new); } - public List findAllActive() { + private List findAllActive() { return conferenceRepository.findAllActive(new Date()); } @@ -238,12 +242,13 @@ public class ConferenceService extends BaseService { } @Transactional - public void ping(ConferenceDto conferenceDto) throws IOException { - pingService.addPing(findOne(conferenceDto.getId())); + public Ping ping(ConferenceDto conferenceDto) throws IOException { + Ping ping = pingService.addPing(findOne(conferenceDto.getId())); conferenceRepository.updatePingConference(conferenceDto.getId()); + return ping; } - public Conference findOne(Integer conferenceId) { + private Conference findOne(Integer conferenceId) { return conferenceRepository.findOne(conferenceId); } @@ -269,7 +274,7 @@ public class ConferenceService extends BaseService { modelMap.addAttribute("offshoreSales", offshoreSales); } - public void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { + private void sendNotificationAfterUpdateDeadlines(Conference conference, List oldDeadlines) { if (oldDeadlines.size() != conference.getDeadlines().size()) { conferenceNotificationService.updateDeadlineNotification(conference); return; @@ -283,9 +288,8 @@ public class ConferenceService extends BaseService { } } - public Deadline copyDeadline(Deadline oldDeadline) { - Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription(), - oldDeadline.getExecutor(), oldDeadline.getDone()); + private Deadline copyDeadline(Deadline oldDeadline) { + Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription()); newDeadline.setId(oldDeadline.getId()); return newDeadline; } @@ -298,6 +302,12 @@ public class ConferenceService extends BaseService { } } + private void checkEmptyFieldsOfDates(ConferenceDto conferenceDto, Errors errors) { + if (conferenceDto.getBeginDate() == null || conferenceDto.getEndDate() == null) { + errors.rejectValue("beginDate", "errorCode", "Даты должны быть заполнены"); + } + } + public void filterEmptyDeadlines(ConferenceDto conferenceDto) { conferenceDto.setDeadlines(conferenceDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java index f75f53f..49efac4 100644 --- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java +++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java @@ -21,6 +21,8 @@ public class ApplicationProperties { private boolean checkRun; + private String debugEmail; + public boolean isUseHttps() { return useHttps; } @@ -60,4 +62,12 @@ public class ApplicationProperties { public void setCheckRun(boolean checkRun) { this.checkRun = checkRun; } + + public String getDebugEmail() { + return debugEmail; + } + + public void setDebugEmail(String debugEmail) { + this.debugEmail = debugEmail; + } } diff --git a/src/main/java/ru/ulstu/configuration/Constants.java b/src/main/java/ru/ulstu/configuration/Constants.java index 0a2268a..77a9a4d 100644 --- a/src/main/java/ru/ulstu/configuration/Constants.java +++ b/src/main/java/ru/ulstu/configuration/Constants.java @@ -5,7 +5,11 @@ public class Constants { public static final String MAIL_ACTIVATE = "Account activation"; public static final String MAIL_RESET = "Password reset"; + public static final String MAIL_INVITE = "Account registration"; + public static final String MAIL_CHANGE_PASSWORD = "Password has been changed"; + public static final int MIN_PASSWORD_LENGTH = 6; + public static final int MAX_PASSWORD_LENGTH = 32; public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$"; @@ -17,4 +21,5 @@ public class Constants { public static final String PASSWORD_RESET_REQUEST_PAGE = "/resetRequest"; public static final String PASSWORD_RESET_PAGE = "/reset"; + public static final int RESET_KEY_LENGTH = 6; } \ No newline at end of file diff --git a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java index 591fa0c..894cf39 100644 --- a/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java +++ b/src/main/java/ru/ulstu/configuration/SecurityConfiguration.java @@ -104,7 +104,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .antMatchers("/css/**") .antMatchers("/js/**") .antMatchers("/templates/**") - .antMatchers("/webjars/**"); + .antMatchers("/webjars/**") + .antMatchers("/img/**"); } @Autowired diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java index 27ba6c9..f89001a 100644 --- a/src/main/java/ru/ulstu/core/controller/AdviceController.java +++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java @@ -20,6 +20,7 @@ import ru.ulstu.user.error.UserNotActivatedException; import ru.ulstu.user.error.UserNotFoundException; import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; import ru.ulstu.user.service.UserService; import java.util.Set; @@ -34,11 +35,6 @@ public class AdviceController { this.userService = userService; } - @ModelAttribute("currentUser") - public String getCurrentUser() { - return userService.getCurrentUser().getUserAbbreviate(); - } - @ModelAttribute("flashMessage") public String getFlashMessage() { return null; @@ -112,4 +108,9 @@ public class AdviceController { public ResponseExtended handleUserIsUndeadException(Throwable e) { return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage()); } + + @ExceptionHandler(UserSendingMailException.class) + public ResponseExtended handleUserSendingMailException(Throwable e) { + return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage()); + } } diff --git a/src/main/java/ru/ulstu/core/model/ErrorConstants.java b/src/main/java/ru/ulstu/core/model/ErrorConstants.java index ad69b86..017725a 100644 --- a/src/main/java/ru/ulstu/core/model/ErrorConstants.java +++ b/src/main/java/ru/ulstu/core/model/ErrorConstants.java @@ -6,14 +6,15 @@ public enum ErrorConstants { VALIDATION_ERROR(2, "Validation error"), USER_ID_EXISTS(100, "New user can't have id"), USER_ACTIVATION_ERROR(101, "Invalid activation key"), - USER_EMAIL_EXISTS(102, "User with same email already exists"), - USER_LOGIN_EXISTS(103, "User with same login already exists"), - USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "User passwords is not valid or not match"), - USER_NOT_FOUND(105, "User is not found"), + USER_EMAIL_EXISTS(102, "Пользователь с таким почтовым ящиком уже существует"), + USER_LOGIN_EXISTS(103, "Пользователь с таким логином уже существует"), + USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH(104, "Пароли введены неверно"), + USER_NOT_FOUND(105, "Аккаунт не найден"), USER_NOT_ACTIVATED(106, "User is not activated"), - USER_RESET_ERROR(107, "Invalid reset key"), + USER_RESET_ERROR(107, "Некорректный ключ подтверждения"), USER_UNDEAD_ERROR(108, "Can't edit/delete that user"), - FILE_UPLOAD_ERROR(110, "File upload error"); + FILE_UPLOAD_ERROR(110, "File upload error"), + USER_SENDING_MAIL_EXCEPTION(111, "Во время отправки приглашения пользователю произошла ошибка"); private int code; private String message; diff --git a/src/main/java/ru/ulstu/core/model/response/Response.java b/src/main/java/ru/ulstu/core/model/response/Response.java index 4722010..7c57168 100644 --- a/src/main/java/ru/ulstu/core/model/response/Response.java +++ b/src/main/java/ru/ulstu/core/model/response/Response.java @@ -11,6 +11,6 @@ public class Response extends ResponseEntity { } public Response(ErrorConstants error) { - super(new ControllerResponse(new ControllerResponseError<>(error, null)), HttpStatus.OK); + super(new ControllerResponse(new ControllerResponseError<>(error, null)), HttpStatus.BAD_REQUEST); } } diff --git a/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java b/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java index 1829622..568e9b5 100644 --- a/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java +++ b/src/main/java/ru/ulstu/core/model/response/ResponseExtended.java @@ -7,6 +7,6 @@ import ru.ulstu.core.model.ErrorConstants; public class ResponseExtended extends ResponseEntity { public ResponseExtended(ErrorConstants error, E errorData) { - super(new ControllerResponse(new ControllerResponseError(error, errorData)), HttpStatus.OK); + super(new ControllerResponse(new ControllerResponseError(error, errorData)), HttpStatus.BAD_REQUEST); } } diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java index 4dfebef..3a54bec 100644 --- a/src/main/java/ru/ulstu/deadline/model/Deadline.java +++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java @@ -95,6 +95,11 @@ public class Deadline extends BaseEntity { return false; } Deadline deadline = (Deadline) o; + if (getId() == null && deadline.getId() == null && + description == null && deadline.description == null && + date == null && deadline.date == null) { + return true; + } return getId().equals(deadline.getId()) && description.equals(deadline.description) && date.equals(deadline.date) && diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java index f26c572..3f237e4 100644 --- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java +++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java @@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import ru.ulstu.deadline.model.Deadline; +import java.util.Date; + public interface DeadlineRepository extends JpaRepository { + @Query( + value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)", + nativeQuery = true) + Date findByGrantIdAndDate(Integer grantId, Date date); } diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java index 6002c86..83f1afb 100644 --- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java +++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java @@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.repository.DeadlineRepository; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -50,4 +51,8 @@ public class DeadlineService { public void remove(Integer deadlineId) { deadlineRepository.delete(deadlineId); } + + public Date findByGrantIdAndDate(Integer id, Date date) { + return deadlineRepository.findByGrantIdAndDate(id, date); + } } diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java index ad5e992..a9c01ed 100644 --- a/src/main/java/ru/ulstu/grant/controller/GrantController.java +++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java @@ -20,9 +20,7 @@ import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.io.IOException; import java.util.List; -import java.util.stream.Collectors; -import static org.springframework.util.StringUtils.isEmpty; import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE; import static ru.ulstu.core.controller.Navigation.GRANT_PAGE; import static ru.ulstu.core.controller.Navigation.REDIRECT_TO; @@ -45,7 +43,7 @@ public class GrantController { @GetMapping("/dashboard") public void getDashboard(ModelMap modelMap) { - modelMap.put("grants", grantService.findAllDto()); + modelMap.put("grants", grantService.findAllActiveDto()); } @GetMapping("/grant") @@ -62,17 +60,9 @@ public class GrantController { @PostMapping(value = "/grant", params = "save") public String save(@Valid GrantDto grantDto, Errors errors) throws IOException { - filterEmptyDeadlines(grantDto); - if (grantDto.getDeadlines().isEmpty()) { - errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); - } - if (grantDto.getLeaderId().equals(-1)) { - errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); - } - if (errors.hasErrors()) { + if (!grantService.save(grantDto, errors)) { return GRANT_PAGE; } - grantService.save(grantDto); return String.format(REDIRECT_TO, GRANTS_PAGE); } @@ -89,7 +79,7 @@ public class GrantController { @PostMapping(value = "/grant", params = "addDeadline") public String addDeadline(@Valid GrantDto grantDto, Errors errors) { - filterEmptyDeadlines(grantDto); + grantService.filterEmptyDeadlines(grantDto); if (errors.hasErrors()) { return GRANT_PAGE; } @@ -133,10 +123,4 @@ public class GrantController { public List getAllPapers() { return grantService.getAllUncompletedPapers(); } - - private void filterEmptyDeadlines(GrantDto grantDto) { - grantDto.setDeadlines(grantDto.getDeadlines().stream() - .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) - .collect(Collectors.toList())); - } } diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java index e0cd9be..369568f 100644 --- a/src/main/java/ru/ulstu/grant/model/Grant.java +++ b/src/main/java/ru/ulstu/grant/model/Grant.java @@ -43,7 +43,8 @@ public class Grant extends BaseEntity implements UserContainer { IN_WORK("В работе"), COMPLETED("Завершен"), FAILED("Провалены сроки"), - LOADED_FROM_KIAS("Загружен автоматически"); + LOADED_FROM_KIAS("Загружен автоматически"), + SKIPPED("Не интересует"); private String statusName; @@ -62,14 +63,14 @@ public class Grant extends BaseEntity implements UserContainer { @Enumerated(value = EnumType.STRING) private GrantStatus status = GrantStatus.APPLICATION; - @OneToMany(cascade = CascadeType.ALL) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "grant_id") @OrderBy("date") private List deadlines = new ArrayList<>(); private String comment; - @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "grant_id", unique = true) @Fetch(FetchMode.SUBSELECT) private List files = new ArrayList<>(); diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java index 203d306..9e59d86 100644 --- a/src/main/java/ru/ulstu/grant/model/GrantDto.java +++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java @@ -6,18 +6,20 @@ import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.file.model.FileDataDto; +import ru.ulstu.name.NameContainer; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.project.model.ProjectDto; import ru.ulstu.user.model.UserDto; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static ru.ulstu.core.util.StreamApiUtils.convert; -public class GrantDto { +public class GrantDto extends NameContainer { private final static int MAX_AUTHORS_LENGTH = 60; private Integer id; @@ -95,6 +97,12 @@ public class GrantDto { this.papers = convert(grant.getPapers(), PaperDto::new); } + public GrantDto(String grantTitle, Date deadLineDate) { + this.title = grantTitle; + deadlines.add(new Deadline(deadLineDate, "Окончание приёма заявок")); + status = Grant.GrantStatus.LOADED_FROM_KIAS; + } + public Integer getId() { return id; } diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java new file mode 100644 index 0000000..631f5db --- /dev/null +++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java @@ -0,0 +1,50 @@ +package ru.ulstu.grant.page; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +public class KiasPage { + private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm"; + private WebDriver driver; + + public KiasPage(WebDriver webDriver) { + this.driver = webDriver; + } + + public boolean goToNextPage() { + try { + if (driver.findElements(By.id("js-ctrlNext")).size() > 0) { + driver.findElement(By.id("js-ctrlNext")).click(); + return true; + } + } finally { + return false; + } + } + + public List getPageOfGrants() { + WebElement listContest = driver.findElement(By.tagName("tBody")); + List grants = listContest.findElements(By.cssSelector("tr.tr")); + return grants; + } + + public String getGrantTitle(WebElement grant) { + return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText(); + } + + public Date parseDeadLineDate(WebElement grantElement) throws ParseException { + String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59 + SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT); + return formatter.parse(deadlineDate); + } + + private String getFirstDeadline(WebElement grantElement) { + return grantElement.findElement(By.xpath("./td[5]")).getText(); + } +} diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java index 44c2cc0..876a8c1 100644 --- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java +++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java @@ -1,11 +1,23 @@ package ru.ulstu.grant.repository; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import ru.ulstu.grant.model.Grant; +import ru.ulstu.name.BaseRepository; import java.util.List; -public interface GrantRepository extends JpaRepository { +public interface GrantRepository extends JpaRepository, BaseRepository { List findByStatus(Grant.GrantStatus status); + + Grant findByTitle(String title); + + @Override + @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ") + String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id); + + @Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')") + List findAllActive(); } diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java index 1c38c4a..a2950a6 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java +++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java @@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import java.io.IOException; +import java.text.ParseException; + @Service public class GrantScheduler { private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; @@ -27,4 +30,15 @@ public class GrantScheduler { grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); } + + @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara") + public void loadGrantsFromKias() { + log.debug("GrantScheduler.loadGrantsFromKias started"); + try { + grantService.createFromKias(); + } catch (ParseException | IOException e) { + e.printStackTrace(); + } + log.debug("GrantScheduler.loadGrantsFromKias finished"); + } } diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java index 45f9b2f..86f8f1b 100644 --- a/src/main/java/ru/ulstu/grant/service/GrantService.java +++ b/src/main/java/ru/ulstu/grant/service/GrantService.java @@ -1,8 +1,11 @@ package ru.ulstu.grant.service; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.Errors; import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; @@ -10,6 +13,7 @@ import ru.ulstu.file.service.FileService; import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.repository.GrantRepository; +import ru.ulstu.name.BaseService; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.service.PaperService; @@ -21,12 +25,14 @@ import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; import java.io.IOException; +import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; import static org.springframework.util.ObjectUtils.isEmpty; @@ -34,8 +40,8 @@ import static ru.ulstu.core.util.StreamApiUtils.convert; import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION; @Service -public class GrantService { - private final static int MAX_DISPLAY_SIZE = 50; +public class GrantService extends BaseService { + private final Logger log = LoggerFactory.getLogger(GrantService.class); private final GrantRepository grantRepository; private final ProjectService projectService; @@ -45,6 +51,7 @@ public class GrantService { private final PaperService paperService; private final EventService eventService; private final GrantNotificationService grantNotificationService; + private final KiasService kiasService; public GrantService(GrantRepository grantRepository, FileService fileService, @@ -53,8 +60,11 @@ public class GrantService { UserService userService, PaperService paperService, EventService eventService, - GrantNotificationService grantNotificationService) { + GrantNotificationService grantNotificationService, + KiasService kiasService) { this.grantRepository = grantRepository; + this.kiasService = kiasService; + this.baseRepository = grantRepository; this.fileService = fileService; this.deadlineService = deadlineService; this.projectService = projectService; @@ -69,9 +79,7 @@ public class GrantService { } public List findAllDto() { - List grants = convert(findAll(), GrantDto::new); - grants.forEach(grantDto -> grantDto.setTitle(StringUtils.abbreviate(grantDto.getTitle(), MAX_DISPLAY_SIZE))); - return grants; + return convert(findAll(), GrantDto::new); } public GrantDto findOneDto(Integer id) { @@ -176,12 +184,58 @@ public class GrantService { return grant; } - public void save(GrantDto grantDto) throws IOException { + public boolean save(GrantDto grantDto, Errors errors) throws IOException { + grantDto.setName(grantDto.getTitle()); + filterEmptyDeadlines(grantDto); + checkEmptyDeadlines(grantDto, errors); + checkEmptyLeader(grantDto, errors); + checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); + if (errors.hasErrors()) { + return false; + } if (isEmpty(grantDto.getId())) { create(grantDto); } else { update(grantDto); } + return true; + } + + public boolean saveFromKias(GrantDto grantDto) throws IOException { + grantDto.setName(grantDto.getTitle()); + String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени + if (title != null) { + Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд + if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают + return false; + } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать + create(grantDto); + return true; + } + } else { //иначе такого гранта ещё нет, поэтому надо создать + create(grantDto); + return true; + } + } + + private void checkEmptyLeader(GrantDto grantDto, Errors errors) { + if (grantDto.getLeaderId().equals(-1)) { + errors.rejectValue("leaderId", "errorCode", "Укажите руководителя"); + } + } + + private void checkEmptyDeadlines(GrantDto grantDto, Errors errors) { + if (grantDto.getDeadlines().isEmpty()) { + errors.rejectValue("deadlines", "errorCode", "Не может быть пусто"); + } + } + + private boolean checkSameDeadline(GrantDto grantDto, Integer id) { + Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас + if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой + return true; + } + return false; } public List getGrantAuthors(GrantDto grantDto) { @@ -216,11 +270,7 @@ public class GrantService { } public List getAllUncompletedPapers() { - List papers = paperService.findAllNotCompleted(); - papers.stream() - .forEach(paper -> - paper.setTitle(StringUtils.abbreviate(paper.getTitle(), MAX_DISPLAY_SIZE))); - return papers; + return paperService.findAllNotCompleted(); } public void attachPaper(GrantDto grantDto) { @@ -261,4 +311,29 @@ public class GrantService { .filter(author -> Collections.frequency(authors, author) > 3) .collect(toList()); } + + public void filterEmptyDeadlines(GrantDto grantDto) { + grantDto.setDeadlines(grantDto.getDeadlines().stream() + .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) + .collect(Collectors.toList())); + } + + @Transactional + public void createFromKias() throws IOException, ParseException { + for (GrantDto grantDto : kiasService.getNewGrantsDto()) { + if (saveFromKias(grantDto)) { + log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded"); + } else { + log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists"); + } + } + } + + public List findAllActiveDto() { + return convert(findAllActive(), GrantDto::new); + } + + private List findAllActive() { + return grantRepository.findAllActive(); + } } diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java new file mode 100644 index 0000000..618e83c --- /dev/null +++ b/src/main/java/ru/ulstu/grant/service/KiasService.java @@ -0,0 +1,92 @@ +package ru.ulstu.grant.service; + +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.springframework.stereotype.Service; +import ru.ulstu.grant.model.GrantDto; +import ru.ulstu.grant.page.KiasPage; +import ru.ulstu.user.service.UserService; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.List; + +@Service +public class KiasService { + private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s"; + private final static String CONTEST_STATUS_ID = "1"; + private final static String CONTEST_TYPE = "-1"; + + private final static 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; + + public KiasService(UserService userService) { + this.userService = userService; + } + + public List getNewGrantsDto() throws ParseException { + WebDriver webDriver = getDriver(); + Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId(); + List grants = new ArrayList<>(); + for (Integer year : generateGrantYears()) { + webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year)); + grants.addAll(getKiasGrants(webDriver)); + } + grants.forEach(grantDto -> grantDto.setLeaderId(leaderId)); + webDriver.quit(); + return grants; + } + + public List getKiasGrants(WebDriver webDriver) throws ParseException { + List newGrants = new ArrayList<>(); + KiasPage kiasPage = new KiasPage(webDriver); + do { + newGrants.addAll(getGrantsFromPage(kiasPage)); + } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами + return newGrants; + } + + private List getGrantsFromPage(KiasPage kiasPage) throws ParseException { + List grants = new ArrayList<>(); + for (WebElement grantElement : kiasPage.getPageOfGrants()) { + GrantDto grantDto = new GrantDto( + kiasPage.getGrantTitle(grantElement), + kiasPage.parseDeadLineDate(grantElement)); + grants.add(grantDto); + } + return grants; + } + + private List generateGrantYears() { + return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR), + Calendar.getInstance().get(Calendar.YEAR) + 1); + } + + 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"); + } +} diff --git a/src/main/java/ru/ulstu/name/BaseService.java b/src/main/java/ru/ulstu/name/BaseService.java index 6619385..fd63cbf 100644 --- a/src/main/java/ru/ulstu/name/BaseService.java +++ b/src/main/java/ru/ulstu/name/BaseService.java @@ -13,4 +13,11 @@ public abstract class BaseService { errors.rejectValue(checkField, "errorCode", errorMessage); } } + + public String checkUniqueName(NameContainer nameContainer, Integer id) { + if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) { + return baseRepository.findByNameAndNotId(nameContainer.getName(), id); + } + return null; + } } diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java index 41d5586..29da57d 100644 --- a/src/main/java/ru/ulstu/paper/controller/PaperController.java +++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java @@ -13,9 +13,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import ru.ulstu.conference.service.ConferenceService; import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.service.LatexService; import ru.ulstu.paper.service.PaperService; import ru.ulstu.user.model.User; @@ -105,6 +107,15 @@ public class PaperController { return "/papers/paper"; } + @PostMapping(value = "/paper", params = "addReference") + public String addReference(@Valid PaperDto paperDto, Errors errors) { + if (errors.hasErrors()) { + return "/papers/paper"; + } + paperDto.getReferences().add(new ReferenceDto()); + return "/papers/paper"; + } + @ModelAttribute("allStatuses") public List getPaperStatuses() { return paperService.getPaperStatuses(); @@ -129,6 +140,16 @@ public class PaperController { return years; } + @ModelAttribute("allFormatStandards") + public List getFormatStandards() { + return paperService.getFormatStandards(); + } + + @ModelAttribute("allReferenceTypes") + public List getReferenceTypes() { + return paperService.getReferenceTypes(); + } + @PostMapping("/generatePdf") public ResponseEntity getPdfFile(PaperDto paper) throws IOException, InterruptedException { HttpHeaders headers = new HttpHeaders(); @@ -137,6 +158,16 @@ public class PaperController { return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK); } + @PostMapping("/getFormattedReferences") + public ResponseEntity getFormattedReferences(PaperDto paperDto) { + return new ResponseEntity<>(paperService.getFormattedReferences(paperDto), new HttpHeaders(), HttpStatus.OK); + } + + @ModelAttribute("autocompleteData") + public AutoCompleteData getAutocompleteData() { + return paperService.getAutoCompleteData(); + } + private void filterEmptyDeadlines(PaperDto paperDto) { paperDto.setDeadlines(paperDto.getDeadlines().stream() .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) diff --git a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java new file mode 100644 index 0000000..91c3bf4 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java @@ -0,0 +1,43 @@ +package ru.ulstu.paper.model; + +import java.util.ArrayList; +import java.util.List; + +public class AutoCompleteData { + private List authors = new ArrayList<>(); + private List publicationTitles = new ArrayList<>(); + private List publishers = new ArrayList<>(); + private List journalOrCollectionTitles = new ArrayList<>(); + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public List getPublicationTitles() { + return publicationTitles; + } + + public void setPublicationTitles(List publicationTitles) { + this.publicationTitles = publicationTitles; + } + + public List getPublishers() { + return publishers; + } + + public void setPublishers(List publishers) { + this.publishers = publishers; + } + + public List getJournalOrCollectionTitles() { + return journalOrCollectionTitles; + } + + public void setJournalOrCollectionTitles(List journalOrCollectionTitles) { + this.journalOrCollectionTitles = journalOrCollectionTitles; + } +} diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java index 4536ce5..413c5db 100644 --- a/src/main/java/ru/ulstu/paper/model/Paper.java +++ b/src/main/java/ru/ulstu/paper/model/Paper.java @@ -29,6 +29,7 @@ import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -122,6 +123,11 @@ public class Paper extends BaseEntity implements UserContainer { @ManyToMany(mappedBy = "papers") private List grants; + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "paper_id", unique = true) + @Fetch(FetchMode.SUBSELECT) + private List references = new ArrayList<>(); + public PaperStatus getStatus() { return status; } @@ -247,6 +253,14 @@ public class Paper extends BaseEntity implements UserContainer { return getAuthors(); } + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + public Optional getNextDeadline() { return deadlines .stream() @@ -264,4 +278,36 @@ public class Paper extends BaseEntity implements UserContainer { .findAny() .isPresent(); } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + if (!super.equals(o)) { + return false; + } + Paper paper = (Paper) o; + return Objects.equals(title, paper.title) && + status == paper.status && + type == paper.type && + Objects.equals(deadlines, paper.deadlines) && + Objects.equals(comment, paper.comment) && + Objects.equals(url, paper.url) && + Objects.equals(locked, paper.locked) && + Objects.equals(events, paper.events) && + Objects.equals(files, paper.files) && + Objects.equals(authors, paper.authors) && + Objects.equals(latexText, paper.latexText) && + Objects.equals(conferences, paper.conferences) && + Objects.equals(grants, paper.grants); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), title, status, type, createDate, updateDate, deadlines, comment, url, locked, events, files, authors, latexText, conferences, grants); + } } diff --git a/src/main/java/ru/ulstu/paper/model/PaperDto.java b/src/main/java/ru/ulstu/paper/model/PaperDto.java index 11d6dfc..8474a34 100644 --- a/src/main/java/ru/ulstu/paper/model/PaperDto.java +++ b/src/main/java/ru/ulstu/paper/model/PaperDto.java @@ -38,6 +38,8 @@ public class PaperDto { private Set authors; private Integer filterAuthorId; private String latexText; + private List references = new ArrayList<>(); + private ReferenceDto.FormatStandard formatStandard = ReferenceDto.FormatStandard.GOST; public PaperDto() { deadlines.add(new Deadline()); @@ -57,7 +59,9 @@ public class PaperDto { @JsonProperty("locked") Boolean locked, @JsonProperty("files") List files, @JsonProperty("authorIds") Set authorIds, - @JsonProperty("authors") Set authors) { + @JsonProperty("authors") Set authors, + @JsonProperty("references") List references, + @JsonProperty("formatStandard") ReferenceDto.FormatStandard formatStandard) { this.id = id; this.title = title; this.status = status; @@ -71,6 +75,8 @@ public class PaperDto { this.locked = locked; this.files = files; this.authors = authors; + this.references = references; + this.formatStandard = formatStandard; } public PaperDto(Paper paper) { @@ -88,6 +94,7 @@ public class PaperDto { this.files = convert(paper.getFiles(), FileDataDto::new); this.authorIds = convert(paper.getAuthors(), user -> user.getId()); this.authors = convert(paper.getAuthors(), UserDto::new); + this.references = convert(paper.getReferences(), ReferenceDto::new); } public Integer getId() { @@ -216,4 +223,20 @@ public class PaperDto { public void setFilterAuthorId(Integer filterAuthorId) { this.filterAuthorId = filterAuthorId; } + + public List getReferences() { + return references; + } + + public void setReferences(List references) { + this.references = references; + } + + public ReferenceDto.FormatStandard getFormatStandard() { + return formatStandard; + } + + public void setFormatStandard(ReferenceDto.FormatStandard formatStandard) { + this.formatStandard = formatStandard; + } } diff --git a/src/main/java/ru/ulstu/paper/model/Reference.java b/src/main/java/ru/ulstu/paper/model/Reference.java new file mode 100644 index 0000000..289cdc1 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/model/Reference.java @@ -0,0 +1,88 @@ +package ru.ulstu.paper.model; + +import ru.ulstu.core.model.BaseEntity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; + +@Entity +public class Reference extends BaseEntity { + + private String authors; + + @Column(name = "publication_title") + private String publicationTitle; + + @Column(name = "publication_year") + private Integer publicationYear; + + private String publisher; + + private String pages; + + @Column(name = "journal_or_collection_title") + private String journalOrCollectionTitle; + + @Enumerated(value = EnumType.STRING) + @Column(name = "reference_type") + private ReferenceDto.ReferenceType referenceType = ReferenceDto.ReferenceType.ARTICLE; + + public String getAuthors() { + return authors; + } + + public void setAuthors(String authors) { + this.authors = authors; + } + + public String getPublicationTitle() { + return publicationTitle; + } + + public void setPublicationTitle(String publicationTitle) { + this.publicationTitle = publicationTitle; + } + + public Integer getPublicationYear() { + return publicationYear; + } + + public void setPublicationYear(Integer publicationYear) { + this.publicationYear = publicationYear; + } + + public String getPublisher() { + return publisher; + } + + public void setPublisher(String publisher) { + this.publisher = publisher; + } + + public String getPages() { + return pages; + } + + public void setPages(String pages) { + this.pages = pages; + } + + public String getJournalOrCollectionTitle() { + return journalOrCollectionTitle; + } + + public void setJournalOrCollectionTitle(String journalOrCollectionTitle) { + this.journalOrCollectionTitle = journalOrCollectionTitle; + } + + public ReferenceDto.ReferenceType getReferenceType() { + return referenceType; + } + + public void setReferenceType(ReferenceDto.ReferenceType referenceType) { + this.referenceType = referenceType; + } + +} diff --git a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java index 8d71ae5..1705e08 100644 --- a/src/main/java/ru/ulstu/paper/model/ReferenceDto.java +++ b/src/main/java/ru/ulstu/paper/model/ReferenceDto.java @@ -34,6 +34,7 @@ public class ReferenceDto { } } + private Integer id; private String authors; private String publicationTitle; private Integer publicationYear; @@ -42,9 +43,11 @@ public class ReferenceDto { private String journalOrCollectionTitle; private ReferenceType referenceType; private FormatStandard formatStandard; + private boolean deleted; @JsonCreator public ReferenceDto( + @JsonProperty("id") Integer id, @JsonProperty("authors") String authors, @JsonProperty("publicationTitle") String publicationTitle, @JsonProperty("publicationYear") Integer publicationYear, @@ -52,7 +55,9 @@ public class ReferenceDto { @JsonProperty("pages") String pages, @JsonProperty("journalOrCollectionTitle") String journalOrCollectionTitle, @JsonProperty("referenceType") ReferenceType referenceType, - @JsonProperty("formatStandard") FormatStandard formatStandard) { + @JsonProperty("formatStandard") FormatStandard formatStandard, + @JsonProperty("isDeleted") boolean deleted) { + this.id = id; this.authors = authors; this.publicationTitle = publicationTitle; this.publicationYear = publicationYear; @@ -61,6 +66,22 @@ public class ReferenceDto { this.journalOrCollectionTitle = journalOrCollectionTitle; this.referenceType = referenceType; this.formatStandard = formatStandard; + this.deleted = deleted; + } + + public ReferenceDto(Reference reference) { + this.id = reference.getId(); + this.authors = reference.getAuthors(); + this.publicationTitle = reference.getPublicationTitle(); + this.publicationYear = reference.getPublicationYear(); + this.publisher = reference.getPublisher(); + this.pages = reference.getPages(); + this.journalOrCollectionTitle = reference.getJournalOrCollectionTitle(); + this.referenceType = reference.getReferenceType(); + } + + public ReferenceDto() { + referenceType = ReferenceType.ARTICLE; } public String getAuthors() { @@ -126,4 +147,20 @@ public class ReferenceDto { public void setFormatStandard(FormatStandard formatStandard) { this.formatStandard = formatStandard; } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public boolean getDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } } diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java new file mode 100644 index 0000000..942a5b8 --- /dev/null +++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java @@ -0,0 +1,23 @@ +package ru.ulstu.paper.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import ru.ulstu.paper.model.Reference; + +import java.util.List; + +public interface ReferenceRepository extends JpaRepository { + void deleteById(Integer id); + + @Query("SELECT DISTINCT r.authors FROM Reference r") + List findDistinctAuthors(); + + @Query("SELECT DISTINCT r.publicationTitle FROM Reference r") + List findDistinctPublicationTitles(); + + @Query("SELECT DISTINCT r.publisher FROM Reference r") + List findDistinctPublishers(); + + @Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''") + List findDistinctJournalOrCollectionTitles(); +} diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java index db810f5..2393af4 100644 --- a/src/main/java/ru/ulstu/paper/service/PaperService.java +++ b/src/main/java/ru/ulstu/paper/service/PaperService.java @@ -7,11 +7,14 @@ import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.service.FileService; +import ru.ulstu.paper.model.AutoCompleteData; import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperListDto; +import ru.ulstu.paper.model.Reference; import ru.ulstu.paper.model.ReferenceDto; import ru.ulstu.paper.repository.PaperRepository; +import ru.ulstu.paper.repository.ReferenceRepository; import ru.ulstu.timeline.service.EventService; import ru.ulstu.user.model.User; import ru.ulstu.user.service.UserService; @@ -39,6 +42,7 @@ import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.ARTICLE; import static ru.ulstu.paper.model.ReferenceDto.ReferenceType.BOOK; @Service +@Transactional public class PaperService { private final static int MAX_DISPLAY_SIZE = 40; private final static String PAPER_FORMATTED_TEMPLATE = "%s %s"; @@ -49,14 +53,17 @@ public class PaperService { private final DeadlineService deadlineService; private final FileService fileService; private final EventService eventService; + private final ReferenceRepository referenceRepository; public PaperService(PaperRepository paperRepository, + ReferenceRepository referenceRepository, FileService fileService, PaperNotificationService paperNotificationService, UserService userService, DeadlineService deadlineService, EventService eventService) { this.paperRepository = paperRepository; + this.referenceRepository = referenceRepository; this.fileService = fileService; this.paperNotificationService = paperNotificationService; this.userService = userService; @@ -117,6 +124,7 @@ public class PaperService { paper.setTitle(paperDto.getTitle()); paper.setUpdateDate(new Date()); paper.setDeadlines(deadlineService.saveOrCreate(paperDto.getDeadlines())); + paper.setReferences(saveOrCreateReferences(paperDto.getReferences())); paper.setFiles(fileService.saveOrCreate(paperDto.getFiles().stream() .filter(f -> !f.isDeleted()) .collect(toList()))); @@ -127,6 +135,41 @@ public class PaperService { return paper; } + public List saveOrCreateReferences(List references) { + return references + .stream() + .filter(reference -> !reference.getDeleted()) + .map(reference -> reference.getId() != null ? updateReference(reference) : createReference(reference)) + .collect(Collectors.toList()); + } + + @Transactional + public Reference updateReference(ReferenceDto referenceDto) { + Reference updateReference = referenceRepository.findOne(referenceDto.getId()); + copyFromDto(updateReference, referenceDto); + referenceRepository.save(updateReference); + return updateReference; + } + + @Transactional + public Reference createReference(ReferenceDto referenceDto) { + Reference newReference = new Reference(); + copyFromDto(newReference, referenceDto); + newReference = referenceRepository.save(newReference); + return newReference; + } + + private Reference copyFromDto(Reference reference, ReferenceDto referenceDto) { + reference.setAuthors(referenceDto.getAuthors()); + reference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle()); + reference.setPages(referenceDto.getPages()); + reference.setPublicationTitle(referenceDto.getPublicationTitle()); + reference.setPublicationYear(referenceDto.getPublicationYear()); + reference.setPublisher(referenceDto.getPublisher()); + reference.setReferenceType(referenceDto.getReferenceType()); + return reference; + } + @Transactional public Integer update(PaperDto paperDto) throws IOException { Paper paper = paperRepository.findOne(paperDto.getId()); @@ -139,6 +182,11 @@ public class PaperService { fileService.delete(file.getId()); } paperRepository.save(copyFromDto(paper, paperDto)); + for (ReferenceDto referenceDto : paperDto.getReferences().stream() + .filter(f -> f.getDeleted() && f.getId() != null) + .collect(toList())) { + referenceRepository.deleteById(referenceDto.getId()); + } eventService.updatePaperDeadlines(paper); paper.getAuthors().forEach(author -> { @@ -168,6 +216,14 @@ public class PaperService { return Arrays.asList(Paper.PaperType.values()); } + public List getFormatStandards() { + return Arrays.asList(ReferenceDto.FormatStandard.values()); + } + + public List getReferenceTypes() { + return Arrays.asList(ReferenceDto.ReferenceType.values()); + } + @Transactional public Paper create(String title, User user, Date deadlineDate) { Paper paper = new Paper(); @@ -287,12 +343,23 @@ public class PaperService { : getSpringerReference(referenceDto); } + public String getFormattedReferences(PaperDto paperDto) { + return String.join("\r\n", paperDto.getReferences() + .stream() + .filter(r -> !r.getDeleted()) + .map(r -> { + r.setFormatStandard(paperDto.getFormatStandard()); + return getFormattedReference(r); + }) + .collect(Collectors.toList())); + } + public String getGostReference(ReferenceDto referenceDto) { return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", referenceDto.getAuthors(), referenceDto.getPublicationTitle(), StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", - referenceDto.getPublicationYear().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPages(), StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); } @@ -300,7 +367,7 @@ public class PaperService { public String getSpringerReference(ReferenceDto referenceDto) { return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", referenceDto.getAuthors(), - referenceDto.getPublicationYear().toString(), + referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPublicationTitle(), referenceDto.getReferenceType() == ARTICLE ? " " + referenceDto.getJournalOrCollectionTitle() + "," : "", StringUtils.isEmpty(referenceDto.getPublisher()) ? "" : referenceDto.getPublisher() + ", ", @@ -310,4 +377,13 @@ public class PaperService { public List findAllCompletedByType(Paper.PaperType type) { return paperRepository.findByTypeAndStatus(type, Paper.PaperStatus.COMPLETED); } + + public AutoCompleteData getAutoCompleteData() { + AutoCompleteData autoCompleteData = new AutoCompleteData(); + autoCompleteData.setAuthors(referenceRepository.findDistinctAuthors()); + autoCompleteData.setJournalOrCollectionTitles(referenceRepository.findDistinctJournalOrCollectionTitles()); + autoCompleteData.setPublicationTitles(referenceRepository.findDistinctPublicationTitles()); + autoCompleteData.setPublishers(referenceRepository.findDistinctPublishers()); + return autoCompleteData; + } } diff --git a/src/main/java/ru/ulstu/ping/service/PingService.java b/src/main/java/ru/ulstu/ping/service/PingService.java index f7156f0..6666fdd 100644 --- a/src/main/java/ru/ulstu/ping/service/PingService.java +++ b/src/main/java/ru/ulstu/ping/service/PingService.java @@ -23,10 +23,10 @@ public class PingService { } @Transactional - public void addPing(Conference conference) throws IOException { + public Ping addPing(Conference conference) throws IOException { Ping newPing = new Ping(new Date(), userService.getCurrentUser()); newPing.setConference(conference); - pingRepository.save(newPing); + return pingRepository.save(newPing); } public Integer countPingYesterday(Conference conference, Calendar calendar) { diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java index 8d52e01..2df691f 100644 --- a/src/main/java/ru/ulstu/students/model/TaskDto.java +++ b/src/main/java/ru/ulstu/students/model/TaskDto.java @@ -10,6 +10,7 @@ import ru.ulstu.tags.model.Tag; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -135,6 +136,29 @@ public class TaskDto { this.tags = tags; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TaskDto taskDto = (TaskDto) o; + return Objects.equals(id, taskDto.id) && + Objects.equals(title, taskDto.title) && + Objects.equals(description, taskDto.description) && + status == taskDto.status && + Objects.equals(deadlines, taskDto.deadlines) && + Objects.equals(tagIds, taskDto.tagIds) && + Objects.equals(tags, taskDto.tags); + } + + @Override + public int hashCode() { + return Objects.hash(id, title, description, status, deadlines, createDate, updateDate, tagIds, tags); + } + public String getTagsString() { return StringUtils.abbreviate(tags .stream() diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java index 2be44cb..e89aedf 100644 --- a/src/main/java/ru/ulstu/students/service/TaskService.java +++ b/src/main/java/ru/ulstu/students/service/TaskService.java @@ -108,7 +108,7 @@ public class TaskService { } @Transactional - public void delete(Integer taskId) throws IOException { + public boolean delete(Integer taskId) throws IOException { if (taskRepository.exists(taskId)) { Task scheduleTask = taskRepository.findOne(taskId); Scheduler sch = schedulerRepository.findOneByTask(scheduleTask); @@ -116,7 +116,9 @@ public class TaskService { schedulerRepository.delete(sch.getId()); } taskRepository.delete(taskId); + return true; } + return false; } @@ -128,14 +130,14 @@ public class TaskService { } } - public void copyMainPart(Task newTask, Task task) { + private void copyMainPart(Task newTask, Task task) { newTask.setTitle(task.getTitle()); newTask.setTags(tagService.saveOrCreate(task.getTags())); newTask.setCreateDate(new Date()); newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); } - public Task copyTaskWithNewDates(Task task) { + private Task copyTaskWithNewDates(Task task) { Task newTask = new Task(); copyMainPart(newTask, task); Calendar cal1 = DateUtils.getCalendar(newTask.getCreateDate()); @@ -157,7 +159,7 @@ public class TaskService { }).collect(Collectors.toList()); } - public Task copyTaskWithNewYear(Task task) { + private Task copyTaskWithNewYear(Task task) { Task newTask = new Task(); copyMainPart(newTask, task); newTask.setDeadlines(newYearDeadlines(task.getDeadlines())); @@ -184,7 +186,7 @@ public class TaskService { } @Transactional - public void generateYearTasks() { + public List generateYearTasks() { Set tags = checkRepeatingTags(false); List tasks = new ArrayList<>(); tags.forEach(tag -> { @@ -200,7 +202,9 @@ public class TaskService { Task newTask = copyTaskWithNewYear(task); taskRepository.save(newTask); }); + return tasks; } + return null; } @@ -245,8 +249,9 @@ public class TaskService { } @Transactional - public void createPeriodTask(Scheduler scheduler) { + public Task createPeriodTask(Scheduler scheduler) { Task newTask = copyTaskWithNewDates(scheduler.getTask()); taskRepository.save(newTask); + return newTask; } } diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java index e56c91c..8038f0b 100644 --- a/src/main/java/ru/ulstu/timeline/model/Event.java +++ b/src/main/java/ru/ulstu/timeline/model/Event.java @@ -65,8 +65,8 @@ public class Event extends BaseEntity { private String description; - @ManyToMany(fetch = FetchType.EAGER) - private List recipients = new ArrayList(); + @ManyToMany(fetch = FetchType.LAZY) + private List recipients = new ArrayList<>(); @ManyToOne @JoinColumn(name = "child_id") diff --git a/src/main/java/ru/ulstu/user/controller/UserController.java b/src/main/java/ru/ulstu/user/controller/UserController.java index d7db909..c40ed8f 100644 --- a/src/main/java/ru/ulstu/user/controller/UserController.java +++ b/src/main/java/ru/ulstu/user/controller/UserController.java @@ -3,6 +3,7 @@ package ru.ulstu.user.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -19,6 +20,7 @@ import ru.ulstu.odin.controller.OdinController; import ru.ulstu.odin.model.OdinMetadata; import ru.ulstu.odin.model.OdinVoid; import ru.ulstu.odin.service.OdinService; +import ru.ulstu.user.model.User; import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserListDto; import ru.ulstu.user.model.UserResetPasswordDto; @@ -28,8 +30,12 @@ import ru.ulstu.user.model.UserSessionListDto; import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserSessionService; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import javax.validation.Valid; +import java.util.Map; + import static ru.ulstu.user.controller.UserController.URL; @RestController @@ -141,30 +147,28 @@ public class UserController extends OdinController { return new Response<>(userService.activateUser(activationKey)); } - // TODO: add page for user edit (user-profile) - @PostMapping("/change-information") - public Response changeInformation(@Valid @RequestBody UserDto userDto) { - log.debug("REST: UserController.changeInformation( {} )", userDto.getLogin()); - return new Response<>(userService.updateUserInformation(userDto)); - } - - // TODO: add page for user password change (user-profile) - @PostMapping("/change-password") - public Response changePassword(@Valid @RequestBody UserDto userDto) { - log.debug("REST: UserController.changePassword( {} )", userDto.getLogin()); - return new Response<>(userService.changeUserPassword(userDto)); - } - @PostMapping(PASSWORD_RESET_REQUEST_URL) - public Response requestPasswordReset(@RequestParam("email") String email) { + public void requestPasswordReset(@RequestParam("email") String email) { log.debug("REST: UserController.requestPasswordReset( {} )", email); - return new Response<>(userService.requestUserPasswordReset(email)); + userService.requestUserPasswordReset(email); } @PostMapping(PASSWORD_RESET_URL) - public Response finishPasswordReset(@RequestParam("key") String key, - @RequestBody UserResetPasswordDto userResetPasswordDto) { - log.debug("REST: UserController.requestPasswordReset( {} )", key); - return new Response<>(userService.completeUserPasswordReset(key, userResetPasswordDto)); + public Response finishPasswordReset(@RequestBody UserResetPasswordDto userResetPasswordDto) { + log.debug("REST: UserController.requestPasswordReset( {} )", userResetPasswordDto.getResetKey()); + return new Response<>(userService.completeUserPasswordReset(userResetPasswordDto)); + } + + @PostMapping("/changePassword") + public void changePassword(@RequestBody Map payload, HttpServletRequest request) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + User user = userSessionService.getUserBySessionId(sessionId); + userService.changeUserPassword(user, payload); + } + + @PostMapping("/invite") + public void inviteUser(@RequestParam("email") String email) { + userService.inviteUser(email); } } diff --git a/src/main/java/ru/ulstu/user/controller/UserMvcController.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java new file mode 100644 index 0000000..5bcbd13 --- /dev/null +++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java @@ -0,0 +1,51 @@ +package ru.ulstu.user.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import ru.ulstu.configuration.Constants; +import ru.ulstu.odin.controller.OdinController; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.service.UserService; +import ru.ulstu.user.service.UserSessionService; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +@Controller +@RequestMapping(value = "/users") +public class UserMvcController extends OdinController { + + private final Logger log = LoggerFactory.getLogger(UserMvcController.class); + + private final UserService userService; + private final UserSessionService userSessionService; + + public UserMvcController(UserService userService, + UserSessionService userSessionService) { + super(UserListDto.class, UserDto.class); + this.userService = userService; + this.userSessionService = userSessionService; + } + + @GetMapping("/profile") + public void getUserProfile(ModelMap modelMap, HttpServletRequest request) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + modelMap.addAttribute("userDto", new UserDto(userSessionService.getUserBySessionId(sessionId))); + } + + @PostMapping("/profile") + public void updateUserProfile(ModelMap modelMap, HttpServletRequest request, UserDto userDto) { + HttpSession session = request.getSession(false); + final String sessionId = session.getAttribute(Constants.SESSION_ID_ATTR).toString(); + User user = userSessionService.getUserBySessionId(sessionId); + modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto)); + } +} diff --git a/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java b/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java index 088f999..3edc1fa 100644 --- a/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java +++ b/src/main/java/ru/ulstu/user/error/UserPasswordsNotValidOrNotMatchException.java @@ -1,6 +1,7 @@ package ru.ulstu.user.error; public class UserPasswordsNotValidOrNotMatchException extends RuntimeException { - public UserPasswordsNotValidOrNotMatchException() { + public UserPasswordsNotValidOrNotMatchException(String message) { + super(message); } } diff --git a/src/main/java/ru/ulstu/user/error/UserSendingMailException.java b/src/main/java/ru/ulstu/user/error/UserSendingMailException.java new file mode 100644 index 0000000..576e834 --- /dev/null +++ b/src/main/java/ru/ulstu/user/error/UserSendingMailException.java @@ -0,0 +1,7 @@ +package ru.ulstu.user.error; + +public class UserSendingMailException extends RuntimeException { + public UserSendingMailException(String message) { + super(message); + } +} diff --git a/src/main/java/ru/ulstu/user/model/User.java b/src/main/java/ru/ulstu/user/model/User.java index 7946f04..520b439 100644 --- a/src/main/java/ru/ulstu/user/model/User.java +++ b/src/main/java/ru/ulstu/user/model/User.java @@ -26,7 +26,7 @@ import java.util.Set; @Entity @Table(name = "users") public class User extends BaseEntity { - private final static String USER_ABBREVIATE_TEMPLATE = "%s %s%s"; + private final static String USER_ABBREVIATE_TEMPLATE = "%s %s %s"; @NotNull @Pattern(regexp = Constants.LOGIN_REGEX) @@ -232,7 +232,7 @@ public class User extends BaseEntity { public String getUserAbbreviate() { return String.format(USER_ABBREVIATE_TEMPLATE, lastName == null ? "" : lastName, - firstName == null ? "" : firstName.substring(0, 1) + ".", - patronymic == null ? "" : patronymic.substring(0, 1) + "."); + firstName == null ? "" : firstName.substring(0, 1), + patronymic == null ? "" : patronymic.substring(0, 1)); } } diff --git a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java index 33d84bc..58e7462 100644 --- a/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java +++ b/src/main/java/ru/ulstu/user/model/UserResetPasswordDto.java @@ -14,6 +14,10 @@ public class UserResetPasswordDto { @Size(min = Constants.MIN_PASSWORD_LENGTH, max = 50) private String passwordConfirm; + @NotEmpty + @Size(min = Constants.RESET_KEY_LENGTH) + private String resetKey; + public String getPassword() { return password; } @@ -25,4 +29,8 @@ public class UserResetPasswordDto { public boolean isPasswordsValid() { return Objects.equals(password, passwordConfirm); } + + public String getResetKey() { + return resetKey; + } } diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java index da1da6d..3724792 100644 --- a/src/main/java/ru/ulstu/user/service/MailService.java +++ b/src/main/java/ru/ulstu/user/service/MailService.java @@ -1,8 +1,10 @@ package ru.ulstu.user.service; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.mail.MailProperties; +import org.springframework.mail.MailException; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; @@ -13,17 +15,16 @@ import ru.ulstu.configuration.ApplicationProperties; import ru.ulstu.configuration.Constants; import ru.ulstu.user.model.User; +import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.nio.charset.StandardCharsets; import java.util.Map; @Service public class MailService { - private final Logger log = LoggerFactory.getLogger(MailService.class); - private static final String USER = "user"; private static final String BASE_URL = "baseUrl"; - + private final Logger log = LoggerFactory.getLogger(MailService.class); private final JavaMailSender javaMailSender; private final SpringTemplateEngine templateEngine; private final MailProperties mailProperties; @@ -38,23 +39,23 @@ public class MailService { } @Async - public void sendEmail(String to, String subject, String content) { + public void sendEmail(String to, String subject, String content) throws MessagingException, MailException { log.debug("Send email to '{}' with subject '{}'", to, subject); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); - try { - MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name()); - message.setTo(to); - message.setFrom(mailProperties.getUsername()); - message.setSubject(subject); - message.setText(content, true); - javaMailSender.send(mimeMessage); - log.debug("Sent email to User '{}'", to); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.warn("Email could not be sent to user '{}'", to, e); - } else { - log.warn("Email could not be sent to user '{}': {}", to, e.getMessage()); - } + MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, StandardCharsets.UTF_8.name()); + message.setTo(to); + message.setFrom(mailProperties.getUsername()); + message.setSubject(subject); + message.setText(content, true); + modifyForDebug(message, subject); + javaMailSender.send(mimeMessage); + log.debug("Sent email to User '{}'", to); + } + + private void modifyForDebug(MimeMessageHelper message, String originalSubject) throws MessagingException { + if (!StringUtils.isEmpty(applicationProperties.getDebugEmail())) { + message.setTo(applicationProperties.getDebugEmail()); + message.setSubject("To " + applicationProperties.getDebugEmail() + "; " + originalSubject); } } @@ -64,7 +65,17 @@ public class MailService { context.setVariable(USER, user); context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); String content = templateEngine.process(templateName, context); - sendEmail(user.getEmail(), subject, content); + try { + sendEmail(user.getEmail(), subject, content); + } catch ( + Exception e) { + if (log.isDebugEnabled()) { + log.warn("Email could not be sent to user '{}'", user.getEmail(), e); + } else { + log.warn("Email could not be sent to user '{}': {}", user.getEmail(), e.getMessage()); + } + } + } //Todo: выделить сервис нотификаций @@ -75,7 +86,26 @@ public class MailService { context.setVariable(USER, user); context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); String content = templateEngine.process(templateName, context); - sendEmail(user.getEmail(), subject, content); + try { + sendEmail(user.getEmail(), subject, content); + } catch ( + Exception e) { + if (log.isDebugEnabled()) { + log.warn("Email could not be sent to user '{}'", user.getEmail(), e); + } else { + log.warn("Email could not be sent to user '{}': {}", user.getEmail(), e.getMessage()); + } + } + } + + @Async + public void sendEmailFromTemplate(Map variables, String templateName, String subject, String email) + throws MessagingException { + Context context = new Context(); + variables.entrySet().forEach(entry -> context.setVariable(entry.getKey(), entry.getValue())); + context.setVariable(BASE_URL, applicationProperties.getBaseUrl()); + String content = templateEngine.process(templateName, context); + sendEmail(email, subject, content); } @Async @@ -83,8 +113,16 @@ public class MailService { sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE); } - @Async - public void sendPasswordResetMail(User user) { + public void sendPasswordResetMail(User user) throws MessagingException, MailException { sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET); } + + public void sendInviteMail(Map variables, String email) throws MessagingException, MailException { + sendEmailFromTemplate(variables, "userInviteEmail", Constants.MAIL_INVITE, email); + } + + @Async + public void sendChangePasswordMail(User user) { + sendEmailFromTemplate(user, "passwordChangeEmail", Constants.MAIL_CHANGE_PASSWORD); + } } diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java index c98e4b7..7534110 100644 --- a/src/main/java/ru/ulstu/user/service/UserService.java +++ b/src/main/java/ru/ulstu/user/service/UserService.java @@ -1,331 +1,355 @@ -package ru.ulstu.user.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Sort; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; -import ru.ulstu.configuration.ApplicationProperties; -import ru.ulstu.core.error.EntityIdIsNullException; -import ru.ulstu.core.jpa.OffsetablePageRequest; -import ru.ulstu.core.model.BaseEntity; -import ru.ulstu.core.model.response.PageableItems; -import ru.ulstu.user.error.UserActivationError; -import ru.ulstu.user.error.UserEmailExistsException; -import ru.ulstu.user.error.UserIdExistsException; -import ru.ulstu.user.error.UserIsUndeadException; -import ru.ulstu.user.error.UserLoginExistsException; -import ru.ulstu.user.error.UserNotActivatedException; -import ru.ulstu.user.error.UserNotFoundException; -import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; -import ru.ulstu.user.error.UserResetKeyError; -import ru.ulstu.user.model.User; -import ru.ulstu.user.model.UserDto; -import ru.ulstu.user.model.UserListDto; -import ru.ulstu.user.model.UserResetPasswordDto; -import ru.ulstu.user.model.UserRole; -import ru.ulstu.user.model.UserRoleConstants; -import ru.ulstu.user.model.UserRoleDto; -import ru.ulstu.user.repository.UserRepository; -import ru.ulstu.user.repository.UserRoleRepository; -import ru.ulstu.user.util.UserUtils; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -@Service -@Transactional -public class UserService implements UserDetailsService { - private final Logger log = LoggerFactory.getLogger(UserService.class); - private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; - private final UserRoleRepository userRoleRepository; - private final UserMapper userMapper; - private final MailService mailService; - private final ApplicationProperties applicationProperties; - - public UserService(UserRepository userRepository, - PasswordEncoder passwordEncoder, - UserRoleRepository userRoleRepository, - UserMapper userMapper, - MailService mailService, - ApplicationProperties applicationProperties) { - this.userRepository = userRepository; - this.passwordEncoder = passwordEncoder; - this.userRoleRepository = userRoleRepository; - this.userMapper = userMapper; - this.mailService = mailService; - this.applicationProperties = applicationProperties; - } - - private User getUserByEmail(String email) { - return userRepository.findOneByEmailIgnoreCase(email); - } - - private User getUserByActivationKey(String activationKey) { - return userRepository.findOneByActivationKey(activationKey); - } - - public User getUserByLogin(String login) { - return userRepository.findOneByLoginIgnoreCase(login); - } - - @Transactional(readOnly = true) - public UserDto getUserWithRolesById(Integer userId) { - final User userEntity = userRepository.findOneWithRolesById(userId); - if (userEntity == null) { - throw new UserNotFoundException(userId.toString()); - } - return userMapper.userEntityToUserDto(userEntity); - } - - @Transactional(readOnly = true) - public PageableItems getAllUsers(int offset, int count) { - final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); - return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); - } - - // TODO: read only active users - public List findAll() { - return userRepository.findAll(); - } - - @Transactional(readOnly = true) - public PageableItems getUserRoles() { - final List roles = userRoleRepository.findAll().stream() - .map(UserRoleDto::new) - .sorted(Comparator.comparing(UserRoleDto::getViewValue)) - .collect(Collectors.toList()); - return new PageableItems<>(roles.size(), roles); - } - - public UserDto createUser(UserDto userDto) { - if (userDto.getId() != null) { - throw new UserIdExistsException(); - } - if (getUserByLogin(userDto.getLogin()) != null) { - throw new UserLoginExistsException(userDto.getLogin()); - } - if (getUserByEmail(userDto.getEmail()) != null) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!userDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - User user = userMapper.userDtoToUserEntity(userDto); - user.setActivated(false); - user.setActivationKey(UserUtils.generateActivationKey()); - user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - user = userRepository.save(user); - mailService.sendActivationEmail(user); - log.debug("Created Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto activateUser(String activationKey) { - final User user = getUserByActivationKey(activationKey); - if (user == null) { - throw new UserActivationError(activationKey); - } - user.setActivated(true); - user.setActivationKey(null); - user.setActivationDate(null); - log.debug("Activated user: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); - } - - public UserDto updateUser(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - if (!Objects.equals( - Optional.ofNullable(getUserByLogin(userDto.getLogin())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserLoginExistsException(userDto.getLogin()); - } - User user = userRepository.findOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - userDto.setLogin(applicationProperties.getUndeadUserLogin()); - userDto.setActivated(true); - userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); - } - user.setLogin(userDto.getLogin()); - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); - if (userDto.isActivated() != user.getActivated()) { - if (userDto.isActivated()) { - user.setActivationKey(null); - user.setActivationDate(null); - } else { - user.setActivationKey(UserUtils.generateActivationKey()); - user.setActivationDate(new Date()); - } - } - user.setActivated(userDto.isActivated()); - final Set roles = userMapper.rolesFromDto(userDto.getRoles()); - user.setRoles(roles.isEmpty() - ? Collections.singleton(new UserRole(UserRoleConstants.USER)) - : roles); - if (!StringUtils.isEmpty(userDto.getOldPassword())) { - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - log.debug("Changed password for User: {}", user.getLogin()); - } - user = userRepository.save(user); - log.debug("Changed Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto updateUserInformation(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!Objects.equals( - Optional.ofNullable(getUserByEmail(userDto.getEmail())) - .map(BaseEntity::getId).orElse(userDto.getId()), - userDto.getId())) { - throw new UserEmailExistsException(userDto.getEmail()); - } - User user = userRepository.findOne(userDto.getId()); - if (user == null) { - throw new UserNotFoundException(userDto.getId().toString()); - } - user.setFirstName(userDto.getFirstName()); - user.setLastName(userDto.getLastName()); - user.setEmail(userDto.getEmail()); - user = userRepository.save(user); - log.debug("Updated Information for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - public UserDto changeUserPassword(UserDto userDto) { - if (userDto.getId() == null) { - throw new EntityIdIsNullException(); - } - if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - final String login = UserUtils.getCurrentUserLogin(); - final User user = userRepository.findOneByLoginIgnoreCase(login); - if (user == null) { - throw new UserNotFoundException(login); - } - if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - user.setPassword(passwordEncoder.encode(userDto.getPassword())); - log.debug("Changed password for User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(userRepository.save(user)); - } - - public boolean requestUserPasswordReset(String email) { - User user = userRepository.findOneByEmailIgnoreCase(email); - if (user == null) { - throw new UserNotFoundException(email); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - user.setResetKey(UserUtils.generateResetKey()); - user.setResetDate(new Date()); - user = userRepository.save(user); - mailService.sendPasswordResetMail(user); - log.debug("Created Reset Password Request for User: {}", user.getLogin()); - return true; - } - - public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) { - if (!userResetPasswordDto.isPasswordsValid()) { - throw new UserPasswordsNotValidOrNotMatchException(); - } - User user = userRepository.findOneByResetKey(key); - if (user == null) { - throw new UserResetKeyError(key); - } - user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); - user.setResetKey(null); - user.setResetDate(null); - user = userRepository.save(user); - log.debug("Reset Password for User: {}", user.getLogin()); - return true; - } - - public UserDto deleteUser(Integer userId) { - final User user = userRepository.findOne(userId); - if (user == null) { - throw new UserNotFoundException(userId.toString()); - } - if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { - throw new UserIsUndeadException(user.getLogin()); - } - userRepository.delete(user); - log.debug("Deleted User: {}", user.getLogin()); - return userMapper.userEntityToUserDto(user); - } - - @Override - public UserDetails loadUserByUsername(String username) { - final User user = userRepository.findOneByLoginIgnoreCase(username); - if (user == null) { - throw new UserNotFoundException(username); - } - if (!user.getActivated()) { - throw new UserNotActivatedException(); - } - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() - .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList())); - } - - public List findByIds(List ids) { - return userRepository.findAll(ids); - } - - public User findById(Integer id) { - return userRepository.findOne(id); - } - - public User getCurrentUser() { - String login = UserUtils.getCurrentUserLogin(); - User user = userRepository.findOneByLoginIgnoreCase(login); - if (user == null) { - throw new UserNotFoundException(login); - } - return user; - } - - public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { - return userRepository.filterByAgeAndDegree(hasDegree, hasAge); - } -} +package ru.ulstu.user.service; + +import com.google.common.collect.ImmutableMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.mail.MailException; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; +import ru.ulstu.configuration.ApplicationProperties; +import ru.ulstu.core.error.EntityIdIsNullException; +import ru.ulstu.core.jpa.OffsetablePageRequest; +import ru.ulstu.core.model.BaseEntity; +import ru.ulstu.core.model.response.PageableItems; +import ru.ulstu.user.error.UserActivationError; +import ru.ulstu.user.error.UserEmailExistsException; +import ru.ulstu.user.error.UserIdExistsException; +import ru.ulstu.user.error.UserIsUndeadException; +import ru.ulstu.user.error.UserLoginExistsException; +import ru.ulstu.user.error.UserNotActivatedException; +import ru.ulstu.user.error.UserNotFoundException; +import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException; +import ru.ulstu.user.error.UserResetKeyError; +import ru.ulstu.user.error.UserSendingMailException; +import ru.ulstu.user.model.User; +import ru.ulstu.user.model.UserDto; +import ru.ulstu.user.model.UserListDto; +import ru.ulstu.user.model.UserResetPasswordDto; +import ru.ulstu.user.model.UserRole; +import ru.ulstu.user.model.UserRoleConstants; +import ru.ulstu.user.model.UserRoleDto; +import ru.ulstu.user.repository.UserRepository; +import ru.ulstu.user.repository.UserRoleRepository; +import ru.ulstu.user.util.UserUtils; + +import javax.mail.MessagingException; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Service +@Transactional +public class UserService implements UserDetailsService { + private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка"; + + private final Logger log = LoggerFactory.getLogger(UserService.class); + private final UserRepository userRepository; + private final PasswordEncoder passwordEncoder; + private final UserRoleRepository userRoleRepository; + private final UserMapper userMapper; + private final MailService mailService; + private final ApplicationProperties applicationProperties; + + public UserService(UserRepository userRepository, + PasswordEncoder passwordEncoder, + UserRoleRepository userRoleRepository, + UserMapper userMapper, + MailService mailService, + ApplicationProperties applicationProperties) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.userRoleRepository = userRoleRepository; + this.userMapper = userMapper; + this.mailService = mailService; + this.applicationProperties = applicationProperties; + } + + private User getUserByEmail(String email) { + return userRepository.findOneByEmailIgnoreCase(email); + } + + private User getUserByActivationKey(String activationKey) { + return userRepository.findOneByActivationKey(activationKey); + } + + public User getUserByLogin(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } + + @Transactional(readOnly = true) + public UserDto getUserWithRolesById(Integer userId) { + final User userEntity = userRepository.findOneWithRolesById(userId); + if (userEntity == null) { + throw new UserNotFoundException(userId.toString()); + } + return userMapper.userEntityToUserDto(userEntity); + } + + @Transactional(readOnly = true) + public PageableItems getAllUsers(int offset, int count) { + final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id"))); + return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent())); + } + + // TODO: read only active users + public List findAll() { + return userRepository.findAll(); + } + + @Transactional(readOnly = true) + public PageableItems getUserRoles() { + final List roles = userRoleRepository.findAll().stream() + .map(UserRoleDto::new) + .sorted(Comparator.comparing(UserRoleDto::getViewValue)) + .collect(Collectors.toList()); + return new PageableItems<>(roles.size(), roles); + } + + public UserDto createUser(UserDto userDto) { + if (userDto.getId() != null) { + throw new UserIdExistsException(); + } + if (getUserByLogin(userDto.getLogin()) != null) { + throw new UserLoginExistsException(userDto.getLogin()); + } + if (getUserByEmail(userDto.getEmail()) != null) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!userDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + User user = userMapper.userDtoToUserEntity(userDto); + user.setActivated(false); + user.setActivationKey(UserUtils.generateActivationKey()); + user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER))); + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + user = userRepository.save(user); + mailService.sendActivationEmail(user); + log.debug("Created Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto activateUser(String activationKey) { + final User user = getUserByActivationKey(activationKey); + if (user == null) { + throw new UserActivationError(activationKey); + } + user.setActivated(true); + user.setActivationKey(null); + user.setActivationDate(null); + log.debug("Activated user: {}", user.getLogin()); + return userMapper.userEntityToUserDto(userRepository.save(user)); + } + + public UserDto updateUser(UserDto userDto) { + if (userDto.getId() == null) { + throw new EntityIdIsNullException(); + } + if (!Objects.equals( + Optional.ofNullable(getUserByEmail(userDto.getEmail())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserEmailExistsException(userDto.getEmail()); + } + if (!Objects.equals( + Optional.ofNullable(getUserByLogin(userDto.getLogin())) + .map(BaseEntity::getId).orElse(userDto.getId()), + userDto.getId())) { + throw new UserLoginExistsException(userDto.getLogin()); + } + User user = userRepository.findOne(userDto.getId()); + if (user == null) { + throw new UserNotFoundException(userDto.getId().toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + userDto.setLogin(applicationProperties.getUndeadUserLogin()); + userDto.setActivated(true); + userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN))); + } + user.setLogin(userDto.getLogin()); + user.setFirstName(userDto.getFirstName()); + user.setLastName(userDto.getLastName()); + user.setEmail(userDto.getEmail()); + if (userDto.isActivated() != user.getActivated()) { + if (userDto.isActivated()) { + user.setActivationKey(null); + user.setActivationDate(null); + } else { + user.setActivationKey(UserUtils.generateActivationKey()); + user.setActivationDate(new Date()); + } + } + user.setActivated(userDto.isActivated()); + final Set roles = userMapper.rolesFromDto(userDto.getRoles()); + user.setRoles(roles.isEmpty() + ? Collections.singleton(new UserRole(UserRoleConstants.USER)) + : roles); + if (!StringUtils.isEmpty(userDto.getOldPassword())) { + if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + user.setPassword(passwordEncoder.encode(userDto.getPassword())); + log.debug("Changed password for User: {}", user.getLogin()); + } + user = userRepository.save(user); + log.debug("Changed Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public UserDto updateUserInformation(User user, UserDto updateUser) { + user.setFirstName(updateUser.getFirstName()); + user.setLastName(updateUser.getLastName()); + user.setEmail(updateUser.getEmail()); + user.setLogin(updateUser.getLogin()); + user = userRepository.save(user); + log.debug("Updated Information for User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + public void changeUserPassword(User user, Map payload) { + if (!payload.get("password").equals(payload.get("confirmPassword"))) { + throw new UserPasswordsNotValidOrNotMatchException(""); + } + if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) { + throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно"); + } + user.setPassword(passwordEncoder.encode(payload.get("password"))); + log.debug("Changed password for User: {}", user.getLogin()); + userRepository.save(user); + + mailService.sendChangePasswordMail(user); + } + + public boolean requestUserPasswordReset(String email) { + User user = userRepository.findOneByEmailIgnoreCase(email); + if (user == null) { + throw new UserNotFoundException(email); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + user.setResetKey(UserUtils.generateResetKey()); + user.setResetDate(new Date()); + user = userRepository.save(user); + try { + mailService.sendPasswordResetMail(user); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + log.debug("Created Reset Password Request for User: {}", user.getLogin()); + return true; + } + + public boolean completeUserPasswordReset(UserResetPasswordDto userResetPasswordDto) { + if (!userResetPasswordDto.isPasswordsValid()) { + throw new UserPasswordsNotValidOrNotMatchException("Пароли не совпадают"); + } + User user = userRepository.findOneByResetKey(userResetPasswordDto.getResetKey()); + if (user == null) { + throw new UserResetKeyError(userResetPasswordDto.getResetKey()); + } + user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword())); + user.setResetKey(null); + user.setResetDate(null); + user = userRepository.save(user); + + mailService.sendChangePasswordMail(user); + + log.debug("Reset Password for User: {}", user.getLogin()); + return true; + } + + public UserDto deleteUser(Integer userId) { + final User user = userRepository.findOne(userId); + if (user == null) { + throw new UserNotFoundException(userId.toString()); + } + if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) { + throw new UserIsUndeadException(user.getLogin()); + } + userRepository.delete(user); + log.debug("Deleted User: {}", user.getLogin()); + return userMapper.userEntityToUserDto(user); + } + + @Override + public UserDetails loadUserByUsername(String username) { + final User user = userRepository.findOneByLoginIgnoreCase(username); + if (user == null) { + throw new UserNotFoundException(username); + } + if (!user.getActivated()) { + throw new UserNotActivatedException(); + } + return new org.springframework.security.core.userdetails.User(user.getLogin(), + user.getPassword(), + Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream() + .map(role -> new SimpleGrantedAuthority(role.getName())) + .collect(Collectors.toList())); + } + + public List findByIds(List ids) { + return userRepository.findAll(ids); + } + + public User findById(Integer id) { + return userRepository.findOne(id); + } + + public User getCurrentUser() { + String login = UserUtils.getCurrentUserLogin(); + User user = userRepository.findOneByLoginIgnoreCase(login); + if (user == null) { + throw new UserNotFoundException(login); + } + return user; + } + + public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) { + return userRepository.filterByAgeAndDegree(hasDegree, hasAge); + } + + public void inviteUser(String email) throws UserSendingMailException { + if (userRepository.findOneByEmailIgnoreCase(email) != null) { + throw new UserEmailExistsException(email); + } + + String password = UserUtils.generatePassword(); + + User user = new User(); + user.setPassword(passwordEncoder.encode(password)); + user.setLogin(email); + user.setEmail(email); + user.setFirstName("user"); + user.setLastName("user"); + user.setActivated(true); + userRepository.save(user); + + Map variables = ImmutableMap.of("password", password, "email", email); + try { + mailService.sendInviteMail(variables, email); + } catch (MessagingException | MailException e) { + throw new UserSendingMailException(email); + } + } + + public User findOneByLoginIgnoreCase(String login) { + return userRepository.findOneByLoginIgnoreCase(login); + } +} diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java index 0d985cd..ae289d0 100644 --- a/src/main/java/ru/ulstu/user/service/UserSessionService.java +++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java @@ -54,4 +54,8 @@ public class UserSessionService { userSessionRepository.save(userSession); log.debug("User session {} closed", sessionId); } + + public User getUserBySessionId(String sessionId) { + return userSessionRepository.findOneBySessionId(sessionId).getUser(); + } } diff --git a/src/main/java/ru/ulstu/user/util/UserUtils.java b/src/main/java/ru/ulstu/user/util/UserUtils.java index de585a5..ec58dd9 100644 --- a/src/main/java/ru/ulstu/user/util/UserUtils.java +++ b/src/main/java/ru/ulstu/user/util/UserUtils.java @@ -5,6 +5,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; +import ru.ulstu.configuration.Constants; public class UserUtils { private static final int DEF_COUNT = 20; @@ -32,4 +33,8 @@ public class UserUtils { } return null; } + + public static String generatePassword() { + return RandomStringUtils.randomAscii(Constants.MIN_PASSWORD_LENGTH, Constants.MAX_PASSWORD_LENGTH); + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 038ddcf..f4be778 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -35,5 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml ng-tracker.base-url=http://127.0.0.1:8080 ng-tracker.undead-user-login=admin ng-tracker.dev-mode=true +ng-tracker.debug_email= ng-tracker.use-https=false ng-tracker.check-run=false \ No newline at end of file diff --git a/src/main/resources/db/changelog-20190520_000000-schema.xml b/src/main/resources/db/changelog-20190520_000000-schema.xml new file mode 100644 index 0000000..69cdad0 --- /dev/null +++ b/src/main/resources/db/changelog-20190520_000000-schema.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/main/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml new file mode 100644 index 0000000..aca880f --- /dev/null +++ b/src/main/resources/db/changelog-20190523_000000-schema.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml index d81f1cb..b4ce865 100644 --- a/src/main/resources/db/changelog-master.xml +++ b/src/main/resources/db/changelog-master.xml @@ -45,4 +45,6 @@ + + \ No newline at end of file diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver old mode 100644 new mode 100755 diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver old mode 100644 new mode 100755 diff --git a/src/main/resources/mail_templates/passwordChangeEmail.html b/src/main/resources/mail_templates/passwordChangeEmail.html new file mode 100644 index 0000000..ec15a36 --- /dev/null +++ b/src/main/resources/mail_templates/passwordChangeEmail.html @@ -0,0 +1,21 @@ + + + + Password reset + + + + +

+ Dear Ivan Ivanov +

+

+ Your password has been changed. +

+

+ Regards, +
+ Balance Team. +

+ + diff --git a/src/main/resources/mail_templates/passwordResetEmail.html b/src/main/resources/mail_templates/passwordResetEmail.html index a1034d4..99e4f77 100644 --- a/src/main/resources/mail_templates/passwordResetEmail.html +++ b/src/main/resources/mail_templates/passwordResetEmail.html @@ -1,23 +1,19 @@ - Password reset + Восстановление пароля

- Dear Ivan Ivanov + Дорогой Ivan Ivanov

- For your account a password reset was requested, please click on the URL below to + Ваш ключ для восстановления пароля

- Reset Link -

-

- Regards, + С уважением,
Balance Team.

diff --git a/src/main/resources/mail_templates/userInviteEmail.html b/src/main/resources/mail_templates/userInviteEmail.html new file mode 100644 index 0000000..98fe85f --- /dev/null +++ b/src/main/resources/mail_templates/userInviteEmail.html @@ -0,0 +1,21 @@ + + + + Account activation + + + + +

+ Аккаунт в системе NG-Tracker был создан.
+ Данные для входа:
+ Логин -
+ Пароль - +

+

+ Regards, +
+ Balance Team. +

+ + diff --git a/src/main/resources/public/css/base.css b/src/main/resources/public/css/base.css new file mode 100644 index 0000000..0c69e7c --- /dev/null +++ b/src/main/resources/public/css/base.css @@ -0,0 +1,3 @@ +.loader { + padding-left:50% +} \ No newline at end of file diff --git a/src/main/resources/public/css/conference.css b/src/main/resources/public/css/conference.css index dc83057..60a866d 100644 --- a/src/main/resources/public/css/conference.css +++ b/src/main/resources/public/css/conference.css @@ -23,11 +23,17 @@ body { text-decoration: none; margin: 0; } - .conference-row .d-flex .text-decoration:nth-child(1) { margin-left: 5px; } +.conference-row .d-flex .text-decoration span.h6.float-left.m-2 { + max-width: 470px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + .conference-row .d-flex .icon-delete { width: 29px; height: 29px; diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css index 824209f..b4b3f85 100644 --- a/src/main/resources/public/css/paper.css +++ b/src/main/resources/public/css/paper.css @@ -6,4 +6,35 @@ .nav-tabs { margin-bottom: 20px; +} + +#nav-references label, #nav-references select, #nav-references input { + display: inline-block; + vertical-align: middle; +} + +#nav-references .collapse-heading { + border: 1px solid #ddd; + border-radius: 4px; + padding: 5px 15px; + background-color: #efefef; +} + +#nav-references .collapse-heading a { + text-decoration: none; +} + +#nav-references a:hover { + text-decoration: none; +} + +#nav-references #formattedReferencesArea { + height: 150px; +} + +.ui-autocomplete { + max-height: 200px; + max-width: 400px; + overflow-y: scroll; + overflow-x: hidden; } \ No newline at end of file diff --git a/src/main/resources/public/img/main/ajax-loader.gif b/src/main/resources/public/img/main/ajax-loader.gif new file mode 100644 index 0000000..f2a1bc0 Binary files /dev/null and b/src/main/resources/public/img/main/ajax-loader.gif differ diff --git a/src/main/resources/public/js/core.js b/src/main/resources/public/js/core.js index 58e68f4..cc42258 100644 --- a/src/main/resources/public/js/core.js +++ b/src/main/resources/public/js/core.js @@ -4,6 +4,7 @@ var urlFileUpload = "/api/1.0/files/uploadTmpFile"; var urlFileDownload = "/api/1.0/files/download/"; var urlPdfGenerating = "/papers/generatePdf"; +var urlReferencesFormatting = "/papers/getFormattedReferences"; var urlFileDownloadTmp = "/api/1.0/files/download-tmp/"; /* exported MessageTypesEnum */ diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js new file mode 100644 index 0000000..e31d3ad --- /dev/null +++ b/src/main/resources/public/js/users.js @@ -0,0 +1,127 @@ +function changePassword() { + oldPassword = $("#oldPassword").val() + password = $("#password").val() + confirmPassword = $("#confirmPassword").val() + + if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) { + showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); + return; + } + + if (password != confirmPassword) { + showFeedbackMessage("Повторный пароль введен неверно", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/changePassword", + contentType: "application/json; charset=utf-8", + data: JSON.stringify({ + "oldPassword": oldPassword, + "password": password, + "confirmPassword": confirmPassword, + }), + method: "POST", + success: function() { + $("#closeModalPassword").click(); + showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS) + + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + +function inviteUser() { + email = $("#email").val(); + if (!isEmailValid(email)) { + showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/invite?email=" + email, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function() { + $("#closeModalInvite").click(); + showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + +function requestResetPassword() { + email = $("#emailReset").val() + + if (!isEmailValid(email)) { + showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING); + return; + } + $("#dvloader").show(); + + $.ajax({ + url:"/api/1.0/users/password-reset-request?email=" + email, + contentType: "application/json; charset=utf-8", + method: "POST", + success: function() { + showFeedbackMessage("Проверочный код был отправлен на указанный почтовый ящик", MessageTypesEnum.SUCCESS) + $("#passwordNew").show() + $("#passwordConfirm").show() + $("#btnReset").show() + $("#resetKey").show() + $("#emailReset").hide() + $("#btnSend").hide() + $("#dvloader").hide() + + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + $("#dvloader").hide() + } + }) + +} + +function resetPassword() { + passwordNew = $("#passwordNew").val(); + passwordConfirm = $("#passwordConfirm").val(); + resetKey = $("#resetKey").val(); + + if ([passwordNew, passwordConfirm, resetKey].includes("")) { + showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING); + return; + } + + if (passwordNew != passwordConfirm) { + showFeedbackMessage("Пароли не совпадают", MessageTypesEnum.WARNING); + return; + } + + $.ajax({ + url:"/api/1.0/users/password-reset", + contentType: "application/json; charset=utf-8", + method: "POST", + data: JSON.stringify({ + "password": passwordNew, + "passwordConfirm": passwordConfirm, + "resetKey": resetKey, + }), + success: function() { + showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS) + window.location.href = "/login" + }, + error: function(errorData) { + showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING) + } + }) +} + + +function isEmailValid(email) { + re = /\S+@\S+\.\S+/; + return re.test(email) +} \ No newline at end of file diff --git a/src/main/resources/templates/conferences/conference.html b/src/main/resources/templates/conferences/conference.html index d629d4e..201aa01 100644 --- a/src/main/resources/templates/conferences/conference.html +++ b/src/main/resources/templates/conferences/conference.html @@ -42,12 +42,20 @@ placeholder="http://"/> +

Incorrect description

+

+
+

Incorrect description

+

+
@@ -65,6 +73,7 @@
+

Incorrect title

@@ -94,6 +103,10 @@ +

Incorrect date

+

@@ -123,7 +136,6 @@
- diff --git a/src/main/resources/templates/conferences/dashboard.html b/src/main/resources/templates/conferences/dashboard.html index 86be4f2..e8cfa49 100644 --- a/src/main/resources/templates/conferences/dashboard.html +++ b/src/main/resources/templates/conferences/dashboard.html @@ -24,24 +24,24 @@

- - + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html index 65e0be6..32939e7 100644 --- a/src/main/resources/templates/default.html +++ b/src/main/resources/templates/default.html @@ -61,13 +61,24 @@ - +
+
@@ -379,6 +507,63 @@ } } + function getFormattedReferences() { + + var formData = new FormData(document.forms.paperform); + var xhr = new XMLHttpRequest(); + xhr.open("POST", urlReferencesFormatting); + console.log(formData); + xhr.send(formData); + + xhr.onload = function () { + if (this.status == 200) { + console.debug(this.response); + $('#formattedReferencesArea').val(this.response); + + } else { + showFeedbackMessage("Ошибка при форматировании списка литературы", MessageTypesEnum.DANGER); + } + } + } + + +
diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html index 2adab37..4a2aeab 100644 --- a/src/main/resources/templates/resetRequest.html +++ b/src/main/resources/templates/resetRequest.html @@ -1,57 +1,59 @@ + layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml"> + +
-
-
-
-
- -
- - -
-
-
- - - +
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+ + + + +
+
+
+ +
\ No newline at end of file diff --git a/src/main/resources/templates/users/changePassword.html b/src/main/resources/templates/users/changePassword.html new file mode 100644 index 0000000..bc96b5c --- /dev/null +++ b/src/main/resources/templates/users/changePassword.html @@ -0,0 +1,36 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/users/inviteModal.html b/src/main/resources/templates/users/inviteModal.html new file mode 100644 index 0000000..c91b397 --- /dev/null +++ b/src/main/resources/templates/users/inviteModal.html @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html new file mode 100644 index 0000000..93adfc7 --- /dev/null +++ b/src/main/resources/templates/users/profile.html @@ -0,0 +1,75 @@ + + + + + + + + +
+
+
+
+
+

Личный кабинет

+
+
+
+
+
+
+ +
+ + +

Incorrect firstName

+

+
+
+ + +

Incorrect lastName

+

+
+
+ + +

Incorrect email

+

+
+
+ + +

Incorrect email

+

+
+
+ +
+
+
+
+
+
+
+ + diff --git a/src/test/java/IndexConferenceTest.java b/src/test/java/ConferenceTest.java similarity index 99% rename from src/test/java/IndexConferenceTest.java rename to src/test/java/ConferenceTest.java index 269561f..3fae34b 100644 --- a/src/test/java/IndexConferenceTest.java +++ b/src/test/java/ConferenceTest.java @@ -26,7 +26,7 @@ import java.util.Map; @RunWith(SpringRunner.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class IndexConferenceTest extends TestTemplate { +public class ConferenceTest extends TestTemplate { private final Map> navigationHolder = ImmutableMap.of( new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"), new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"), diff --git a/src/test/java/StudentTaskTest.java b/src/test/java/StudentTaskTest.java new file mode 100644 index 0000000..f55a679 --- /dev/null +++ b/src/test/java/StudentTaskTest.java @@ -0,0 +1,214 @@ +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import core.PageObject; +import core.TestTemplate; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import ru.ulstu.NgTrackerApplication; +import ru.ulstu.configuration.ApplicationProperties; +import students.TaskPage; +import students.TasksDashboardPage; +import students.TasksPage; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +@RunWith(SpringRunner.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +public class StudentTaskTest extends TestTemplate { + private final Map> navigationHolder = ImmutableMap.of( + new TasksPage(), Arrays.asList("Список задач", "/students/tasks"), + new TasksDashboardPage(), Arrays.asList("Панель управления", "/students/dashboard"), + new TaskPage(), Arrays.asList("Создать задачу", "/students/task?id=0") + ); + + private final String tag = "ATag"; + + @Autowired + private ApplicationProperties applicationProperties; + + + @Test + public void testACreateTask() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskName)); + } + + @Test + public void testBEditTaskName() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + String taskNewName = "Task " + (new Date()).getTime(); + + tasksPage.goToFirstTask(); + taskPage.removeName(); + taskPage.setName(taskNewName); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTask(taskNewName)); + } + + @Test + public void testCDeleteTask() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + Integer size = tasksPage.getTasks().size(); + tasksPage.deleteFirstTask(); + Thread.sleep(3000); + tasksPage.submit(); + + Assert.assertEquals(size - 1, tasksPage.getTasks().size()); + } + + @Test + public void testDAddDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadnum = taskPage.getDeadNum(); + + String descr = "Description"; + String date = "06.06.2019"; + String dateValue = "2019-06-06"; + + taskPage.clickAddDeadline(); + taskPage.addDeadlineDescription(descr, deadnum); + taskPage.addDeadlineDate(date, deadnum); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testEEditDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + + String descr = "DescriptionTwo"; + String date = "12.12.2019"; + String dateValue = "2019-12-12"; + + taskPage.clearDeadlineDate(0); + taskPage.clearDeadlineDescription(0); + taskPage.addDeadlineDescription(descr, 0); + taskPage.addDeadlineDate(date, 0); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertTrue(taskPage.hasDeadline(descr, dateValue)); + } + + @Test + public void testFDeleteDeadline() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + TaskPage taskPage = (TaskPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 2).getKey()); + + tasksPage.goToFirstTask(); + String taskId = taskPage.getId(); + Integer deadNum = taskPage.getDeadNum(); + + taskPage.deleteDeadline(); + taskPage.save(); + + getContext().goTo(applicationProperties.getBaseUrl() + String.format("/students/task?id=%s", taskId)); + + Assert.assertEquals(deadNum - 1, (int) taskPage.getDeadNum()); + } + + @Test + public void testGCreateTaskWithTag() throws InterruptedException { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 2); + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + + TaskPage taskPage = (TaskPage) getContext().initPage(page.getKey()); + TasksPage tasksPage = (TasksPage) getContext().initPage(Iterables.get(navigationHolder.entrySet(), 0).getKey()); + String taskName = "Task " + (new Date()).getTime(); + + taskPage.setName(taskName); + taskPage.setTag(tag); + Thread.sleep(1000); + taskPage.addDeadlineDate("01.01.2020", 0); + taskPage.addDeadlineDescription("Description", 0); + taskPage.save(); + + Assert.assertTrue(tasksPage.findTaskByTag(taskName, tag)); + } + + @Test + public void testHFindTagInFilter() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + + Assert.assertTrue(tasksPage.findTag(tag)); + } + + @Test + public void testIFilterByTag() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + tasksPage.selectTag(tag); + + Assert.assertTrue(tasksPage.findTasksByTag(tag)); + } + + @Test + public void testJFilterByStatus() { + Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0); + + getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1)); + TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey()); + + tasksPage.selectStatus(); + Assert.assertTrue(tasksPage.findAllStatus()); + } + + +} diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java new file mode 100644 index 0000000..5864511 --- /dev/null +++ b/src/test/java/grant/KiasPage.java @@ -0,0 +1,11 @@ +package grant; + +import core.PageObject; +import org.openqa.selenium.By; + +public class KiasPage extends PageObject { + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h1")).getText(); + } +} diff --git a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java new file mode 100644 index 0000000..95f4820 --- /dev/null +++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java @@ -0,0 +1,289 @@ +package ru.ulstu.conference.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.domain.Sort; +import ru.ulstu.conference.model.Conference; +import ru.ulstu.conference.model.ConferenceDto; +import ru.ulstu.conference.model.ConferenceFilterDto; +import ru.ulstu.conference.model.ConferenceUser; +import ru.ulstu.conference.repository.ConferenceRepository; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.paper.model.Paper; +import ru.ulstu.paper.service.PaperService; +import ru.ulstu.ping.model.Ping; +import ru.ulstu.ping.service.PingService; +import ru.ulstu.timeline.service.EventService; +import ru.ulstu.user.model.User; +import ru.ulstu.user.service.UserService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class ConferenceServiceTest { + + @Mock + ConferenceRepository conferenceRepository; + + @Mock + DeadlineService deadlineService; + + @Mock + ConferenceUserService conferenceUserService; + + @Mock + PaperService paperService; + + @Mock + UserService userService; + + @Mock + EventService eventService; + + @Mock + ConferenceNotificationService conferenceNotificationService; + + @Mock + PingService pingService; + + @InjectMocks + ConferenceService conferenceService; + + private final static Integer ID = 1; + private final static Integer INDEX = 0; + private final static String NAME = "Name"; + private final static String DESCRIPTION = "Desc"; + private final static boolean TRUE = true; + private final static Integer YEAR = 2019; + private final static Sort SORT = new Sort(Sort.Direction.DESC, "beginDate"); + + private List conferences; + private List deadlines; + private List papers; + private List conferenceUsers; + + private Conference conferenceWithId; + + private Paper paperWithId; + private Paper paperWithoutId; + + private ConferenceDto conferenceDto; + private User user; + private Deadline deadline; + + @Before + public void setUp() throws Exception { + conferences = new ArrayList<>(); + conferenceWithId = new Conference(); + + conferenceWithId.setId(ID); + conferenceWithId.setTitle(NAME); + conferenceWithId.setDescription(DESCRIPTION); + + paperWithId = new Paper(); + paperWithId.setId(1); + paperWithId.setTitle(NAME); + + paperWithoutId = new Paper(); + paperWithoutId.setTitle(NAME); + + papers = new ArrayList<>(); + papers.add(paperWithId); + papers.add(paperWithoutId); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCRIPTION); + deadline.setId(ID); + deadlines.add(deadline); + + ConferenceUser conferenceUser = new ConferenceUser(); + conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE); + conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL); + user = new User(); + user.setFirstName(NAME); + conferenceUser.setUser(user); + + conferenceUsers = new ArrayList<>(); + conferenceUsers.add(conferenceUser); + + conferences.add(conferenceWithId); + conferenceDto = new ConferenceDto(conferenceWithId); + } + + @Test + public void getExistConferenceById() { + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(conferenceWithId); + newConferenceDto.setNotSelectedPapers(papers); + newConferenceDto.setDisabledTakePart(!TRUE); + ConferenceDto result = conferenceService.getExistConferenceById(ID); + + assertEquals(newConferenceDto.getId(), result.getId()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void getNewConference() { + when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.setNotSelectedPapers(papers); + ConferenceDto result = conferenceService.getNewConference(); + + assertEquals(newConferenceDto.getId(), result.getId()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void findAll() { + when(conferenceRepository.findAll(SORT)).thenReturn(conferences); + + assertEquals(Collections.singletonList(conferenceWithId), conferenceService.findAll()); + } + + @Test + public void create() throws IOException { + when(paperService.findPaperById(ID)).thenReturn(paperWithId); + when(paperService.create(new Paper())).thenReturn(paperWithoutId); + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(conferenceUserService.saveOrCreate(new ArrayList<>())).thenReturn(conferenceUsers); + when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId); + + conferenceDto.setPapers(papers); + conferenceDto.setDeadlines(deadlines); + conferenceDto.setUsers(conferenceUsers); + conferenceDto.getPaperIds().add(ID); + + Conference newConference = new Conference(); + newConference.setId(ID); + newConference.setTitle(NAME); + newConference.setDescription(DESCRIPTION); + newConference.setPapers(papers); + newConference.getPapers().add(paperWithId); + newConference.setDeadlines(deadlines); + newConference.setUsers(conferenceUsers); + + assertEquals(newConference, conferenceService.create(conferenceDto)); + } + + @Test + public void delete() { + when(conferenceRepository.exists(ID)).thenReturn(true); + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + assertTrue(conferenceService.delete(ID)); + } + + @Test + public void addDeadline() { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getDeadlines().add(new Deadline()); + conferenceDto.getDeadlines().clear(); + + assertEquals(newConferenceDto.getDeadlines().get(0), conferenceService.addDeadline(conferenceDto).getDeadlines().get(0)); + } + + @Test + public void removeDeadline() throws IOException { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getRemovedDeadlineIds().add(ID); + conferenceDto.getDeadlines().add(deadline); + ConferenceDto result = conferenceService.removeDeadline(conferenceDto, INDEX); + + assertEquals(newConferenceDto.getDeadlines(), result.getDeadlines()); + assertEquals(newConferenceDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds()); + } + + @Test + public void addPaper() { + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getPapers().add(paperWithoutId); + conferenceDto.getPapers().clear(); + ConferenceDto result = conferenceService.addPaper(conferenceDto); + result.getPapers().get(INDEX).setTitle(NAME); // приходится вручную назначать название, т.е. название зависит от даты + + assertEquals(newConferenceDto.getPapers(), result.getPapers()); + } + + @Test + public void removePaper() throws IOException { + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.getNotSelectedPapers().add(paperWithId); + newConferenceDto.getPapers().add(paperWithoutId); + conferenceDto.getPapers().add(paperWithId); + conferenceDto.getPapers().add(paperWithoutId); + ConferenceDto result = conferenceService.removePaper(conferenceDto, INDEX); + + assertEquals(newConferenceDto.getPapers(), result.getPapers()); + assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers()); + } + + @Test + public void takePart() throws IOException { + when(userService.getCurrentUser()).thenReturn(user); + + ConferenceDto newConferenceDto = new ConferenceDto(); + newConferenceDto.setUsers(conferenceUsers); + newConferenceDto.setDisabledTakePart(TRUE); + conferenceDto.getPapers().clear(); + ConferenceDto result = conferenceService.takePart(conferenceDto); + + assertEquals(newConferenceDto.getUsers(), result.getUsers()); + assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart()); + } + + @Test + public void getAllUsers() { + List users = Collections.singletonList(user); + when(userService.findAll()).thenReturn(users); + assertEquals(users, conferenceService.getAllUsers()); + } + + @Test + public void filter() { + when(userService.findById(ID)).thenReturn(user); + when(conferenceRepository.findByUserAndYear(user, YEAR)).thenReturn(conferences); + + ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto(); + conferenceFilterDto.setFilterUserId(ID); + conferenceFilterDto.setYear(YEAR); + + assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto)); + } + + @Test + public void isAttachedToConference() { + when(conferenceRepository.isPaperAttached(ID)).thenReturn(TRUE); + + assertTrue(conferenceService.isAttachedToConference(ID)); + } + + @Test + public void ping() throws IOException { + Ping ping = new Ping(); + when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId); + when(pingService.addPing(conferenceWithId)).thenReturn(ping); + when(conferenceRepository.updatePingConference(ID)).thenReturn(INDEX); + + assertEquals(ping, conferenceService.ping(conferenceDto)); + } +} \ No newline at end of file diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java new file mode 100644 index 0000000..8edfc77 --- /dev/null +++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java @@ -0,0 +1,216 @@ +package ru.ulstu.students.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.data.domain.Sort; +import ru.ulstu.core.util.DateUtils; +import ru.ulstu.deadline.model.Deadline; +import ru.ulstu.deadline.service.DeadlineService; +import ru.ulstu.students.model.Scheduler; +import ru.ulstu.students.model.Task; +import ru.ulstu.students.model.TaskDto; +import ru.ulstu.students.model.TaskFilterDto; +import ru.ulstu.students.repository.SchedulerRepository; +import ru.ulstu.students.repository.TaskRepository; +import ru.ulstu.tags.model.Tag; +import ru.ulstu.tags.service.TagService; +import ru.ulstu.timeline.service.EventService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class TaskServiceTest { + + @Mock + TaskRepository taskRepository; + + @Mock + SchedulerRepository schedulerRepository; + + @Mock + private TagService tagService; + + @Mock + DeadlineService deadlineService; + + @Mock + EventService eventService; + + @InjectMocks + TaskService taskService; + + private final static Sort SORT = new Sort(Sort.Direction.DESC, "createDate"); + private final static Integer ID = 1; + private final static Task.TaskStatus STATUS = Task.TaskStatus.IN_WORK; + private final static String TITLE = "title"; + private final static String DESCR = "descr"; + private final static String TAG = "tag"; + private final static Date YEAR = DateUtils.clearTime(DateUtils.addYears(new Date(), 0)); + + private List tasks; + private List tags; + private Task task; + private Task taskForSchedule; + private TaskDto taskDto; + private Tag tag; + private Deadline deadline; + private List deadlines; + private Scheduler scheduler; + + + @Before + public void setUp() throws Exception { + + tasks = new ArrayList<>(); + task = new Task(); + + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + + + tag = new Tag(); + tag.setId(ID); + tag.setTagName(TAG); + + deadlines = new ArrayList<>(); + deadline = new Deadline(new Date(), DESCR); + deadline.setId(ID); + deadlines.add(deadline); + + task.setDeadlines(deadlines); + + tags = new ArrayList<>(); + tags.add(tag); + + tasks.add(task); + taskDto = new TaskDto(task); + + taskForSchedule = new Task(); + taskForSchedule.setTitle(TITLE); + taskForSchedule.setDescription(DESCR); + + scheduler = new Scheduler(); + scheduler.setDate(new Date()); + scheduler.setTask(taskForSchedule); + + + } + + @Test + public void findAll() { + + when(taskRepository.findAll(SORT)).thenReturn(tasks); + assertEquals(Collections.singletonList(task), taskService.findAll()); + } + + @Test + public void filter() { + when(tagService.findById(ID)).thenReturn(tag); + when(taskRepository.filterNew(STATUS, tag)).thenReturn(tasks); + + TaskFilterDto taskFilterDto = new TaskFilterDto(); + taskFilterDto.setTag(ID); + taskFilterDto.setOrder("new"); + taskFilterDto.setStatus(STATUS); + + assertEquals(Collections.singletonList(taskDto), taskService.filter(taskFilterDto)); + } + + @Test + public void create() throws IOException { + when(tagService.saveOrCreate(new ArrayList<>())).thenReturn(tags); + when(deadlineService.saveOrCreate(new ArrayList<>())).thenReturn(deadlines); + when(taskRepository.save(new Task())).thenReturn(task); + eventService.createFromTask(new Task()); + + taskDto.setTags(tags); + taskDto.setDeadlines(deadlines); + + Task newTask = new Task(); + task.setId(ID); + task.setTitle(TITLE); + task.setDescription(DESCR); + task.setTags(tags); + task.setDeadlines(deadlines); + + assertEquals(task.getId(), taskService.create(taskDto)); + } + + @Test + public void delete() throws IOException { + when(taskRepository.exists(ID)).thenReturn(true); + when(taskRepository.findOne(ID)).thenReturn(task); + when(schedulerRepository.findOneByTask(task)).thenReturn(null); + + assertTrue(taskService.delete(ID)); + } + + @Test + public void generateYearTasks() { + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + tasks.get(0).setCreateDate(DateUtils.clearTime(DateUtils.addYears(new Date(), -1))); + when(taskRepository.findByTag(tag)).thenReturn(tasks); + + Task newTask = new Task(); + newTask.setTitle(tasks.get(0).getTitle()); + newTask.setTags(tasks.get(0).getTags()); + newTask.setCreateDate(new Date()); + newTask.setStatus(Task.TaskStatus.LOADED_FROM_KIAS); + + Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(task); + + assertEquals(Arrays.asList(task), taskService.generateYearTasks()); + } + + @Test + public void checkRepeatingTags() { + when(tagService.getTags()).thenReturn(tags); + tasks.get(0).setTags(tags); + when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks); + + assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false)); + } + + @Test + public void createPeriodTask() { + Task newTask = new Task(); + newTask.setTitle(scheduler.getTask().getTitle()); + newTask.setTags(scheduler.getTask().getTags()); + newTask.setCreateDate(new Date()); + + Deadline newDeadline = new Deadline(); + newDeadline.setId(ID); + newDeadline.setDescription(deadline.getDescription()); + newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1)); + when(deadlineService.create(newDeadline)).thenReturn(newDeadline); + newTask.setDeadlines(Arrays.asList(newDeadline)); + + when(taskRepository.save(newTask)).thenReturn(taskForSchedule); + + assertEquals(taskForSchedule, taskService.createPeriodTask(scheduler)); + } +} \ No newline at end of file diff --git a/src/test/java/students/TaskPage.java b/src/test/java/students/TaskPage.java new file mode 100644 index 0000000..c0105b2 --- /dev/null +++ b/src/test/java/students/TaskPage.java @@ -0,0 +1,81 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TaskPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public void setName(String name) { + driver.findElement(By.id("title")).sendKeys(name); + } + + public void save() { + driver.findElement(By.id("sendMessageButton")).click(); + } + + public void addDeadlineDate(String deadDate, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(deadDate); + } + + public void addDeadlineDescription(String deadDescr, Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).sendKeys(deadDescr); + } + + public void removeName() { + driver.findElement(By.id("title")).clear(); + } + + public String getId() { + return driver.findElement(By.id("id")).getAttribute("value"); + } + + public Integer getDeadNum() { + return driver.findElements(By.cssSelector("#task-form .form-group:nth-of-type(5) .row")).size(); + } + + public void clickAddDeadline() { + driver.findElement(By.cssSelector("#addDeadline")).click(); + } + + public List getDeadlines() { + return driver.findElements(By.cssSelector(".form-group:nth-of-type(5) .row")); + } + + public void deleteDeadline() { + driver.findElement(By.xpath("//*[@id=\"task-form\"]/div/div[1]/div[5]/div[1]/div[3]/a")).click(); + + } + + public void clearDeadlineDate(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.date", deadNum))).sendKeys(Keys.DELETE); + } + + public void clearDeadlineDescription(Integer deadNum) { + driver.findElement(By.id(String.format("deadlines%d.description", deadNum))).clear(); + } + + public boolean hasDeadline(String deadDescr, String deadValue) { + return getDeadlines() + .stream() + .anyMatch(webElement -> { + return webElement.findElement(By.cssSelector("input[type=\"text\"]")).getAttribute("value").equals(deadDescr) + && webElement.findElement(By.cssSelector("input[type=\"date\"]")).getAttribute("value").equals(deadValue); + }); + } + + public void setTag(String tag) { + driver.findElement(By.className("input-tag-name")).sendKeys(tag); + driver.findElement(By.className("input-tag-name")).sendKeys(Keys.ENTER); + } + + +} diff --git a/src/test/java/students/TasksDashboardPage.java b/src/test/java/students/TasksDashboardPage.java new file mode 100644 index 0000000..8cc6eda --- /dev/null +++ b/src/test/java/students/TasksDashboardPage.java @@ -0,0 +1,10 @@ +package students; + +import core.PageObject; + +public class TasksDashboardPage extends PageObject { + @Override + public String getSubTitle() { + return null; + } +} diff --git a/src/test/java/students/TasksPage.java b/src/test/java/students/TasksPage.java new file mode 100644 index 0000000..5c5d42c --- /dev/null +++ b/src/test/java/students/TasksPage.java @@ -0,0 +1,75 @@ +package students; + +import core.PageObject; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class TasksPage extends PageObject { + + @Override + public String getSubTitle() { + return driver.findElement(By.tagName("h3")).getText(); + } + + public List getTasks() { + return driver.findElements(By.cssSelector("span.h6")); + } + + public List getTaskRows() { + return driver.findElements(By.className("task-row")); + } + + public void goToFirstTask() { + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]")).click(); + } + + public boolean findTask(String taskName) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(taskName)); + + } + + public void deleteFirstTask() { + js.executeScript("$('a[data-confirm]').click();"); + } + + public void submit() { + driver.findElement(By.xpath("//*[@id=\"dataConfirmOK\"]")).click(); + } + + public boolean findTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + return driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul")).findElement(By.className("text")).getText().equals(tag); + } + + public boolean findTaskByTag(String name, String tag) { + return getTasks().stream() + .anyMatch(webElement -> webElement.getText().equals(name) + && webElement.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[1]/div/div/a[1]/span[3]")).getText().equals(tag)); + } + + public boolean findTasksByTag(String tag) { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("span.text-muted")).getText().equals(tag)); + } + + public void selectTag(String tag) { + driver.findElements(By.className("bootstrap-select")).get(2).findElement(By.className("btn")).click(); + driver.findElement(By.cssSelector(".bs-searchbox input")).sendKeys(tag); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[2]/div/div[2]/ul/li/a")).click(); + } + + + public void selectStatus() { + driver.findElements(By.className("bootstrap-select")).get(1).findElement(By.className("btn")).click(); + driver.findElement(By.xpath("//*[@id=\"tasks\"]/div/div[2]/div[2]/div[2]/div[1]/div/div/ul/li[2]/a")).click(); + } + + public boolean findAllStatus() { + return getTaskRows().stream() + .allMatch(webElement -> webElement.findElement(By.cssSelector("div i.text-primary")).isDisplayed()); + } +}