From 9da5fd8a7a8ae3d4f8fff8aea2d5349f1fc3ca2a Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 00:02:30 +0400
Subject: [PATCH 01/68] #104 shock, the first unit test works
---
.../conference/service/ConferenceService.java | 2 +
.../module_test/ConferenceServiceTest.java | 37 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 src/test/java/conference/module_test/ConferenceServiceTest.java
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index 38de435..8ffbf70 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -1,6 +1,7 @@
package ru.ulstu.conference.service;
import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -43,6 +44,7 @@ public class ConferenceService {
private final ConferenceNotificationService conferenceNotificationService;
private final EventService eventService;
+ @Autowired
public ConferenceService(ConferenceRepository conferenceRepository,
ConferenceUserService conferenceUserService,
DeadlineService deadlineService,
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
new file mode 100644
index 0000000..44c92ea
--- /dev/null
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -0,0 +1,37 @@
+package conference.module_test;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.springframework.data.domain.Sort;
+import ru.ulstu.conference.model.Conference;
+import ru.ulstu.conference.repository.ConferenceRepository;
+import ru.ulstu.conference.service.ConferenceService;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ConferenceServiceTest {
+
+ @Mock
+ ConferenceRepository conferenceRepository;
+
+ @InjectMocks
+ ConferenceService conferenceService;
+
+ @Test
+ public void testFindAllConferences() {
+ List conferences = new ArrayList<>();
+ Conference conference = new Conference();
+ conference.setId(1);
+ conferences.add(conference);
+ Mockito.when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
+ assertEquals(conferences, conferenceService.findAll());
+ }
+}
From 3a9fde3404bd3422dabde9a2a5459508bd043765 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 16:20:19 +0400
Subject: [PATCH 02/68] #104 setUp fields
---
.../module_test/ConferenceServiceTest.java | 60 +++++++++++++++++--
1 file changed, 56 insertions(+), 4 deletions(-)
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index 44c92ea..de83ae7 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -1,5 +1,6 @@
package conference.module_test;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
@@ -8,10 +9,17 @@ import org.mockito.Mockito;
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.repository.ConferenceRepository;
import ru.ulstu.conference.service.ConferenceService;
+import ru.ulstu.conference.service.ConferenceUserService;
+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 java.util.ArrayList;
+import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
@@ -22,16 +30,60 @@ public class ConferenceServiceTest {
@Mock
ConferenceRepository conferenceRepository;
+ @Mock
+ DeadlineService deadlineService;
+
+ @Mock
+ ConferenceUserService conferenceUserService;
+
+ @Mock
+ PaperService paperService;
+
@InjectMocks
ConferenceService conferenceService;
+ private List conferences;
+ private List deadlines;
+ private Conference conference;
+
+ private Paper paperWithId;
+ private Paper paperWithoutId;
+ private Deadline deadline;
+
+ private ConferenceDto conferenceDto;
+
+ @Before
+ public void setUp() throws Exception {
+ conferences = new ArrayList<>();
+ conference = new Conference();
+ conference.setId(1);
+ conference.setTitle("Название");
+ conference.setDescription("Описание");
+ conferences.add(conference);
+ conferenceDto = new ConferenceDto(conference);
+
+ paperWithId = new Paper();
+ paperWithId.setId(1);
+ paperWithId.setTitle("paperTitle");
+
+ paperWithoutId = new Paper();
+ paperWithoutId.setTitle("paperTitleNoId");
+
+ deadlines = new ArrayList<>();
+ deadline = new Deadline(new Date(),"desc");
+ deadline.setId(1);
+ deadlines.add(deadline);
+ }
+
@Test
public void testFindAllConferences() {
- List conferences = new ArrayList<>();
- Conference conference = new Conference();
- conference.setId(1);
- conferences.add(conference);
Mockito.when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
assertEquals(conferences, conferenceService.findAll());
}
+
+ @Test
+ public void testCopyFromDto() {
+
+
+ }
}
From a8d987b01f5e62f3a48652c248c7f55904518e00 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 17:49:22 +0400
Subject: [PATCH 03/68] #104 test copy from dto method
---
.../conference/service/ConferenceService.java | 2 +-
.../module_test/ConferenceServiceTest.java | 47 +++++++++++++++----
2 files changed, 39 insertions(+), 10 deletions(-)
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index 8ffbf70..0e4dd54 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -181,7 +181,7 @@ public class ConferenceService {
return Arrays.asList(ConferenceUser.Deposit.values());
}
- private Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
+ public Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
conference.setTitle(conferenceDto.getTitle());
conference.setDescription(conferenceDto.getDescription());
conference.setUrl(conferenceDto.getUrl());
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index de83ae7..87a77a8 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -5,11 +5,11 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
-import org.mockito.Mockito;
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.ConferenceUser;
import ru.ulstu.conference.repository.ConferenceRepository;
import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.conference.service.ConferenceUserService;
@@ -17,12 +17,15 @@ 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.user.model.User;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConferenceServiceTest {
@@ -44,7 +47,10 @@ public class ConferenceServiceTest {
private List conferences;
private List deadlines;
+ private List papers;
+ private List conferenceUsers;
private Conference conference;
+ private ConferenceUser conferenceUser;
private Paper paperWithId;
private Paper paperWithoutId;
@@ -56,11 +62,9 @@ public class ConferenceServiceTest {
public void setUp() throws Exception {
conferences = new ArrayList<>();
conference = new Conference();
- conference.setId(1);
+
conference.setTitle("Название");
conference.setDescription("Описание");
- conferences.add(conference);
- conferenceDto = new ConferenceDto(conference);
paperWithId = new Paper();
paperWithId.setId(1);
@@ -69,21 +73,46 @@ public class ConferenceServiceTest {
paperWithoutId = new Paper();
paperWithoutId.setTitle("paperTitleNoId");
+ papers = new ArrayList<>();
+ papers.add(paperWithId);
+ papers.add(paperWithoutId);
+
deadlines = new ArrayList<>();
- deadline = new Deadline(new Date(),"desc");
+ deadline = new Deadline(new Date(), "desc");
deadline.setId(1);
deadlines.add(deadline);
+
+ conferenceUser = new ConferenceUser();
+ conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE);
+ conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL);
+ User user = new User();
+ user.setFirstName("Name");
+ conferenceUser.setUser(user);
+
+ conferenceUsers = new ArrayList<>();
+ conferenceUsers.add(conferenceUser);
+
+ conference.setPapers(papers);
+ conference.setDeadlines(deadlines);
+ conference.setUsers(conferenceUsers);
+
+ conferences.add(conference);
+ conferenceDto = new ConferenceDto(conference);
}
@Test
public void testFindAllConferences() {
- Mockito.when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
+ when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
assertEquals(conferences, conferenceService.findAll());
}
@Test
- public void testCopyFromDto() {
-
-
+ public void testCopyFromDto() throws IOException {
+ when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
+ when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
+ when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
+ when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
+ assertEquals(conference, conferenceService.copyFromDto(new Conference(), conferenceDto));
}
+
}
From e6cb991463b4a6d0eb549d6dc9418b63b5fc97e0 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 17:54:18 +0400
Subject: [PATCH 04/68] #104 test is member
---
.../module_test/ConferenceServiceTest.java | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index 87a77a8..1e8f306 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -18,6 +18,7 @@ import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User;
+import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.util.ArrayList;
@@ -42,6 +43,9 @@ public class ConferenceServiceTest {
@Mock
PaperService paperService;
+ @Mock
+ UserService userService;
+
@InjectMocks
ConferenceService conferenceService;
@@ -57,6 +61,7 @@ public class ConferenceServiceTest {
private Deadline deadline;
private ConferenceDto conferenceDto;
+ private User user;
@Before
public void setUp() throws Exception {
@@ -85,7 +90,7 @@ public class ConferenceServiceTest {
conferenceUser = new ConferenceUser();
conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE);
conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL);
- User user = new User();
+ user = new User();
user.setFirstName("Name");
conferenceUser.setUser(user);
@@ -115,4 +120,9 @@ public class ConferenceServiceTest {
assertEquals(conference, conferenceService.copyFromDto(new Conference(), conferenceDto));
}
+ @Test
+ public void testIsCurrentUserParticipant() throws IOException {
+ when(userService.getCurrentUser()).thenReturn(user);
+ assertEquals(true, conferenceService.isCurrentUserParticipant(conferenceUsers));
+ }
}
From 1c5c05b5e466ff364d9e335615018b03151e39a1 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 18:01:50 +0400
Subject: [PATCH 05/68] #104 test take part
---
.../conference/module_test/ConferenceServiceTest.java | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index 1e8f306..1ccbc85 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -125,4 +125,12 @@ public class ConferenceServiceTest {
when(userService.getCurrentUser()).thenReturn(user);
assertEquals(true, conferenceService.isCurrentUserParticipant(conferenceUsers));
}
+
+ @Test
+ public void testTakePart() throws IOException {
+ when(userService.getCurrentUser()).thenReturn(user);
+ ConferenceDto newConferenceDto = new ConferenceDto();
+ conferenceService.takePart(newConferenceDto);
+ assertEquals(newConferenceDto.getUsers(), conferenceDto.getUsers());
+ }
}
From c88c77cd7db6800f8d0df39351a0f54916ad02f2 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 18:20:01 +0400
Subject: [PATCH 06/68] #104 test find one dto
---
.../ulstu/conference/model/ConferenceDto.java | 27 +++++++++++++++++++
.../conference/service/ConferenceService.java | 1 -
.../module_test/ConferenceServiceTest.java | 6 +++++
3 files changed, 33 insertions(+), 1 deletion(-)
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
index 2e2f13b..944cd9d 100644
--- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
@@ -13,6 +13,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;
@@ -218,4 +219,30 @@ public class ConferenceDto {
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(beginDate, that.beginDate) &&
+ Objects.equals(endDate, that.endDate) &&
+ 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 0e4dd54..cdb33ef 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -149,7 +149,6 @@ public class ConferenceService {
Paper paper = new Paper();
paper.setTitle(userService.getCurrentUser().getLastName() + "_" + conferenceDto.getTitle() + "_" + (new Date()).getTime());
paper.setStatus(Paper.PaperStatus.DRAFT);
-
conferenceDto.getPapers().add(paper);
}
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index 1ccbc85..6f2146b 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -133,4 +133,10 @@ public class ConferenceServiceTest {
conferenceService.takePart(newConferenceDto);
assertEquals(newConferenceDto.getUsers(), conferenceDto.getUsers());
}
+
+ @Test
+ public void testFindOneDto() throws IOException {
+ when(conferenceRepository.findOne(1)).thenReturn(conference);
+ assertEquals(conferenceDto, conferenceService.findOneDto(1));
+ }
}
From 11cab955b4d51bbc3b11413a0e0d844b05edfb5a Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 14 May 2019 18:51:03 +0400
Subject: [PATCH 07/68] #104 test create
---
.../ulstu/conference/model/ConferenceDto.java | 11 ++--
.../module_test/ConferenceServiceTest.java | 52 +++++++++++++++----
2 files changed, 49 insertions(+), 14 deletions(-)
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
index 944cd9d..76dbb90 100644
--- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
@@ -221,8 +221,12 @@ public class ConferenceDto {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
ConferenceDto that = (ConferenceDto) o;
return ping == that.ping &&
disabledTakePart == that.disabledTakePart &&
@@ -243,6 +247,7 @@ public class ConferenceDto {
@Override
public int hashCode() {
- return Objects.hash(id, title, description, url, ping, beginDate, endDate, deadlines, removedDeadlineIds, userIds, paperIds, papers, notSelectedPapers, users, disabledTakePart);
+ return Objects.hash(id, title, description, url, ping, beginDate, endDate, deadlines, removedDeadlineIds,
+ userIds, paperIds, papers, notSelectedPapers, users, disabledTakePart);
}
}
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/conference/module_test/ConferenceServiceTest.java
index 6f2146b..200b6f1 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/conference/module_test/ConferenceServiceTest.java
@@ -11,12 +11,14 @@ import ru.ulstu.conference.model.Conference;
import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.conference.model.ConferenceUser;
import ru.ulstu.conference.repository.ConferenceRepository;
+import ru.ulstu.conference.service.ConferenceNotificationService;
import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.conference.service.ConferenceUserService;
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.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
@@ -26,6 +28,7 @@ import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@@ -46,6 +49,12 @@ public class ConferenceServiceTest {
@Mock
UserService userService;
+ @Mock
+ ConferenceNotificationService conferenceNotificationService;
+
+ @Mock
+ EventService eventService;
+
@InjectMocks
ConferenceService conferenceService;
@@ -53,7 +62,9 @@ public class ConferenceServiceTest {
private List deadlines;
private List papers;
private List conferenceUsers;
- private Conference conference;
+
+ private Conference conferenceWithId;
+ private Conference conferenceWithoutId;
private ConferenceUser conferenceUser;
private Paper paperWithId;
@@ -66,10 +77,15 @@ public class ConferenceServiceTest {
@Before
public void setUp() throws Exception {
conferences = new ArrayList<>();
- conference = new Conference();
+ conferenceWithId = new Conference();
+ conferenceWithoutId = new Conference();
- conference.setTitle("Название");
- conference.setDescription("Описание");
+ conferenceWithId.setId(1);
+ conferenceWithId.setTitle("Название");
+ conferenceWithId.setDescription("Описание");
+
+ conferenceWithoutId.setTitle("Название");
+ conferenceWithoutId.setDescription("Описание");
paperWithId = new Paper();
paperWithId.setId(1);
@@ -97,12 +113,16 @@ public class ConferenceServiceTest {
conferenceUsers = new ArrayList<>();
conferenceUsers.add(conferenceUser);
- conference.setPapers(papers);
- conference.setDeadlines(deadlines);
- conference.setUsers(conferenceUsers);
+ conferenceWithId.setPapers(papers);
+ conferenceWithId.setDeadlines(deadlines);
+ conferenceWithId.setUsers(conferenceUsers);
- conferences.add(conference);
- conferenceDto = new ConferenceDto(conference);
+ conferenceWithoutId.setPapers(papers);
+ conferenceWithoutId.setDeadlines(deadlines);
+ conferenceWithoutId.setUsers(conferenceUsers);
+
+ conferences.add(conferenceWithId);
+ conferenceDto = new ConferenceDto(conferenceWithId);
}
@Test
@@ -117,7 +137,7 @@ public class ConferenceServiceTest {
when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
- assertEquals(conference, conferenceService.copyFromDto(new Conference(), conferenceDto));
+ assertEquals(conferenceWithoutId, conferenceService.copyFromDto(new Conference(), conferenceDto));
}
@Test
@@ -136,7 +156,17 @@ public class ConferenceServiceTest {
@Test
public void testFindOneDto() throws IOException {
- when(conferenceRepository.findOne(1)).thenReturn(conference);
+ when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
assertEquals(conferenceDto, conferenceService.findOneDto(1));
}
+
+ @Test
+ public void testCreate() throws IOException {
+ when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
+ when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
+ when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
+ when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
+ when(conferenceRepository.save(conferenceWithoutId)).thenReturn(conferenceWithoutId);
+ assertNull(conferenceService.create(conferenceDto));
+ }
}
From 95fc9da47decf785efc8aed710c02936b0994a38 Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Wed, 15 May 2019 00:49:54 +0400
Subject: [PATCH 08/68] lk base, created from dev
---
.../ulstu/user/controller/UserController.java | 7 -
.../user/controller/UserControllerV2.java | 178 ++++++++++++++++++
.../ru/ulstu/user/service/UserService.java | 21 +--
.../user/service/UserSessionService.java | 4 +
src/main/resources/templates/default.html | 10 +-
.../resources/templates/users/profile.html | 75 ++++++++
6 files changed, 269 insertions(+), 26 deletions(-)
create mode 100644 src/main/java/ru/ulstu/user/controller/UserControllerV2.java
create mode 100644 src/main/resources/templates/users/profile.html
diff --git a/src/main/java/ru/ulstu/user/controller/UserController.java b/src/main/java/ru/ulstu/user/controller/UserController.java
index d7db909..6806d19 100644
--- a/src/main/java/ru/ulstu/user/controller/UserController.java
+++ b/src/main/java/ru/ulstu/user/controller/UserController.java
@@ -141,13 +141,6 @@ 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) {
diff --git a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
new file mode 100644
index 0000000..f15872e
--- /dev/null
+++ b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
@@ -0,0 +1,178 @@
+package ru.ulstu.user.controller;
+
+import com.sun.org.apache.xpath.internal.operations.Mod;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.access.annotation.Secured;
+import org.springframework.stereotype.Controller;
+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;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import ru.ulstu.configuration.Constants;
+import ru.ulstu.core.model.response.PageableItems;
+import ru.ulstu.core.model.response.Response;
+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.*;
+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 static ru.ulstu.user.controller.UserController.URL;
+
+@Controller
+@RequestMapping(value = "/users")
+public class UserControllerV2 extends OdinController {
+ public static final String URL = Constants.API_1_0 + "users";
+ public static final String ROLES_URL = "/roles";
+ public static final String ROLES_META_URL = ROLES_URL + OdinController.META_LIST_URL;
+ public static final String SESSIONS_URL = "/sessions";
+ public static final String SESSIONS_META_URL = SESSIONS_URL + OdinController.META_LIST_URL;
+ public static final String REGISTER_URL = "/register";
+ public static final String ACTIVATE_URL = "/activate";
+ public static final String PASSWORD_RESET_REQUEST_URL = "/password-reset-request";
+ public static final String PASSWORD_RESET_URL = "/password-reset";
+
+ private final Logger log = LoggerFactory.getLogger(UserController.class);
+
+ private final UserService userService;
+ private final UserSessionService userSessionService;
+ private final OdinService odinRolesService;
+ private final OdinService odinSessionsService;
+
+ public UserControllerV2(UserService userService,
+ UserSessionService userSessionService,
+ OdinService odinRolesService,
+ OdinService odinSessionsService) {
+ super(UserListDto.class, UserDto.class);
+ this.userService = userService;
+ this.userSessionService = userSessionService;
+ this.odinRolesService = odinRolesService;
+ this.odinSessionsService = odinSessionsService;
+ }
+
+ @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.getUserDtoBySessionId(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.getUserDtoBySessionId(sessionId);
+ modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
+ }
+
+ @GetMapping(ROLES_URL)
+ @Secured(UserRoleConstants.ADMIN)
+ public Response> getUserRoles() {
+ log.debug("REST: UserController.getUserRoles()");
+ return new Response<>(userService.getUserRoles());
+ }
+
+ @GetMapping(ROLES_META_URL)
+ @Secured(UserRoleConstants.ADMIN)
+ public Response getUserRolesMetaData() {
+ log.debug("REST: UserController.getUserRolesMetaData()");
+ return new Response<>(odinRolesService.getListModel(UserRoleDto.class));
+ }
+
+ @GetMapping(SESSIONS_URL)
+ @Secured(UserRoleConstants.ADMIN)
+ public Response> getUserSessions(@RequestParam(value = "offset", defaultValue = "0") int offset,
+ @RequestParam(value = "count", defaultValue = "10") int count) {
+ log.debug("REST: UserController.getUserSessions()");
+ return new Response<>(userSessionService.getSessions(offset, count));
+ }
+
+ @GetMapping(SESSIONS_META_URL)
+ @Secured(UserRoleConstants.ADMIN)
+ public Response getUserSessionsMetaData() {
+ log.debug("REST: UserController.getUserSessionsMetaData()");
+ return new Response<>(odinSessionsService.getListModel(UserSessionListDto.class));
+ }
+
+ @GetMapping("")
+ @Secured(UserRoleConstants.ADMIN)
+ public Response> getAllUsers(@RequestParam(value = "offset", defaultValue = "0") int offset,
+ @RequestParam(value = "count", defaultValue = "10") int count) {
+ log.debug("REST: UserController.getAllUsers( {}, {} )", offset, count);
+ return new Response<>(userService.getAllUsers(offset, count));
+ }
+
+ @GetMapping("/{userId}")
+ @Secured(UserRoleConstants.ADMIN)
+ public Response getUser(@PathVariable Integer userId) {
+ log.debug("REST: UserController.getUser( {} )", userId);
+ return new Response<>(userService.getUserWithRolesById(userId));
+ }
+
+
+ @PostMapping("")
+ @Secured(UserRoleConstants.ADMIN)
+ public Response createUser(@Valid @RequestBody UserDto userDto) {
+ log.debug("REST: UserController.createUser( {} )", userDto.getLogin());
+ return new Response<>(userService.createUser(userDto));
+ }
+
+ @PutMapping("")
+ @Secured(UserRoleConstants.ADMIN)
+ public Response updateUser(@Valid @RequestBody UserDto userDto) {
+ log.debug("REST: UserController.updateUser( {} )", userDto.getLogin());
+ return new Response<>(userService.updateUser(userDto));
+ }
+
+ @DeleteMapping("/{userId}")
+ @Secured(UserRoleConstants.ADMIN)
+ public Response deleteUser(@PathVariable Integer userId) {
+ log.debug("REST: UserController.deleteUser( {} )", userId);
+ return new Response<>(userService.deleteUser(userId));
+ }
+
+ @PostMapping(REGISTER_URL)
+ public Response registerUser(@Valid @RequestBody UserDto userDto) {
+ log.debug("REST: UserController.registerUser( {} )", userDto.getLogin());
+ return new Response<>(userService.createUser(userDto));
+ }
+
+ @PostMapping(ACTIVATE_URL)
+ public Response activateUser(@RequestParam("key") String activationKey) {
+ log.debug("REST: UserController.activateUser( {} )", activationKey);
+ return new Response<>(userService.activateUser(activationKey));
+ }
+
+ // 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) {
+ log.debug("REST: UserController.requestPasswordReset( {} )", email);
+ return new Response<>(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));
+ }
+}
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index c98e4b7..202cf10 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -205,23 +205,10 @@ public class UserService implements UserDetailsService {
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());
+ public UserDto updateUserInformation(User user, UserDto updateUser) {
+ user.setFirstName(updateUser.getFirstName());
+ user.setLastName(updateUser.getLastName());
+ user.setEmail(updateUser.getEmail());
user = userRepository.save(user);
log.debug("Updated Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java
index 0d985cd..03415de 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 getUserDtoBySessionId(String sessionId) {
+ return userSessionRepository.findOneBySessionId(sessionId).getUser();
+ }
}
diff --git a/src/main/resources/templates/default.html b/src/main/resources/templates/default.html
index 65e0be6..4f9ec12 100644
--- a/src/main/resources/templates/default.html
+++ b/src/main/resources/templates/default.html
@@ -61,8 +61,14 @@
КИАС РФФИ
-
- Выход
+
+
+ Профиль
+
+
diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html
new file mode 100644
index 0000000..5468d1b
--- /dev/null
+++ b/src/main/resources/templates/users/profile.html
@@ -0,0 +1,75 @@
+
+
+
+
+
+
+
+
+
+
+
From 00c5d5f755732ec8b22922df44ec8aa7b5e4bbd7 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Wed, 15 May 2019 00:54:30 +0400
Subject: [PATCH 09/68] #104 test refactoring
---
.../ulstu/conference/model/ConferenceDto.java | 2 -
.../conference/service/ConferenceService.java | 41 ++++---
.../service}/ConferenceServiceTest.java | 109 ++++++++++++++----
3 files changed, 109 insertions(+), 43 deletions(-)
rename src/test/java/{conference/module_test => ru/ulstu/conference/service}/ConferenceServiceTest.java (64%)
diff --git a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
index 76dbb90..606ddae 100644
--- a/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
+++ b/src/main/java/ru/ulstu/conference/model/ConferenceDto.java
@@ -234,8 +234,6 @@ public class ConferenceDto {
Objects.equals(title, that.title) &&
Objects.equals(description, that.description) &&
Objects.equals(url, that.url) &&
- Objects.equals(beginDate, that.beginDate) &&
- Objects.equals(endDate, that.endDate) &&
Objects.equals(deadlines, that.deadlines) &&
Objects.equals(removedDeadlineIds, that.removedDeadlineIds) &&
Objects.equals(userIds, that.userIds) &&
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index cdb33ef..c69d273 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -64,7 +64,7 @@ public class ConferenceService {
}
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 +72,7 @@ public class ConferenceService {
public ConferenceDto getNewConference() {
ConferenceDto conferenceDto = new ConferenceDto();
- conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList()));
+ conferenceDto.setNotSelectedPapers(getNotSelectPapers(new ArrayList<>()));
return conferenceDto;
}
@@ -87,10 +87,6 @@ public class ConferenceService {
return conferences;
}
- public ConferenceDto findOneDto(Integer id) {
- return new ConferenceDto(conferenceRepository.findOne(id));
- }
-
public void save(ConferenceDto conferenceDto) throws IOException {
if (isEmpty(conferenceDto.getId())) {
create(conferenceDto);
@@ -127,44 +123,51 @@ public class ConferenceService {
}
@Transactional
- public void delete(Integer conferenceId) {
+ public boolean delete(Integer conferenceId) {
if (conferenceRepository.exists(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);
}
@@ -180,7 +183,7 @@ public class ConferenceService {
return Arrays.asList(ConferenceUser.Deposit.values());
}
- public Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
+ private Conference copyFromDto(Conference conference, ConferenceDto conferenceDto) throws IOException {
conference.setTitle(conferenceDto.getTitle());
conference.setDescription(conferenceDto.getDescription());
conference.setUrl(conferenceDto.getUrl());
@@ -198,7 +201,7 @@ public class ConferenceService {
}
- public boolean isCurrentUserParticipant(List conferenceUsers) {
+ private boolean isCurrentUserParticipant(List conferenceUsers) {
return conferenceUsers.stream().anyMatch(participant -> participant.getUser().equals(userService.getCurrentUser()));
}
@@ -213,7 +216,7 @@ public class ConferenceService {
return convert(findAllActive(), ConferenceDto::new);
}
- public List findAllActive() {
+ private List findAllActive() {
return conferenceRepository.findAllActive(new Date());
}
@@ -227,7 +230,7 @@ public class ConferenceService {
conferenceRepository.updatePingConference(conferenceDto.getId());
}
- public Conference findOne(Integer conferenceId) {
+ private Conference findOne(Integer conferenceId) {
return conferenceRepository.findOne(conferenceId);
}
@@ -253,7 +256,7 @@ public class ConferenceService {
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;
@@ -267,7 +270,7 @@ public class ConferenceService {
}
}
- public Deadline copyDeadline(Deadline oldDeadline) {
+ private Deadline copyDeadline(Deadline oldDeadline) {
Deadline newDeadline = new Deadline(oldDeadline.getDate(), oldDeadline.getDescription());
newDeadline.setId(oldDeadline.getId());
return newDeadline;
diff --git a/src/test/java/conference/module_test/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
similarity index 64%
rename from src/test/java/conference/module_test/ConferenceServiceTest.java
rename to src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index 200b6f1..9fe8301 100644
--- a/src/test/java/conference/module_test/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -1,4 +1,4 @@
-package conference.module_test;
+package ru.ulstu.conference.service;
import org.junit.Before;
import org.junit.Test;
@@ -11,9 +11,6 @@ import ru.ulstu.conference.model.Conference;
import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.conference.model.ConferenceUser;
import ru.ulstu.conference.repository.ConferenceRepository;
-import ru.ulstu.conference.service.ConferenceNotificationService;
-import ru.ulstu.conference.service.ConferenceService;
-import ru.ulstu.conference.service.ConferenceUserService;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.paper.model.Paper;
@@ -24,11 +21,12 @@ 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.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@@ -126,28 +124,82 @@ public class ConferenceServiceTest {
}
@Test
- public void testFindAllConferences() {
+ public void getExistConferenceById() {
+ when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
+ when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers);
+ when(userService.getCurrentUser()).thenReturn(user);
+ conferenceDto.setDisabledTakePart(true);
+ assertEquals(conferenceDto, conferenceService.getExistConferenceById(1));
+ }
+
+ @Test
+ public void getNewConference() {
+ ConferenceDto newConferenceDto = new ConferenceDto();
+ newConferenceDto.setNotSelectedPapers(papers);
+ when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers);
+ assertEquals(newConferenceDto, conferenceService.getNewConference());
+ }
+
+ @Test
+ public void findAll() {
when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
assertEquals(conferences, conferenceService.findAll());
}
@Test
- public void testCopyFromDto() throws IOException {
+ public void create() throws IOException {
when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
- assertEquals(conferenceWithoutId, conferenceService.copyFromDto(new Conference(), conferenceDto));
+ when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId);
+ assertEquals(conferenceWithId.getId(), conferenceService.create(conferenceDto));
}
@Test
- public void testIsCurrentUserParticipant() throws IOException {
+ public void update() throws IOException {
+ when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
+ when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
+ when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
+ when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
+ when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
+ when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId);
+ assertEquals(conferenceWithId.getId(), conferenceService.create(conferenceDto));
+ }
+
+ @Test
+ public void delete() {
+ when(conferenceRepository.exists(1)).thenReturn(true);
+ assertTrue(conferenceService.delete(1));
+ }
+
+ @Test
+ public void addDeadline() {
+ ConferenceDto newConferenceDto = conferenceService.addDeadline(conferenceDto);
+ assertEquals(conferenceDto, newConferenceDto);
+ }
+
+ @Test
+ public void removeDeadline() throws IOException {
+ ConferenceDto newConferenceDto = conferenceService.removeDeadline(conferenceDto, 0);
+ assertEquals(conferenceDto, newConferenceDto);
+ }
+
+ @Test
+ public void addPaper() {
when(userService.getCurrentUser()).thenReturn(user);
- assertEquals(true, conferenceService.isCurrentUserParticipant(conferenceUsers));
+ ConferenceDto newConferenceDto = conferenceService.addPaper(conferenceDto);
+ assertEquals(conferenceDto, newConferenceDto);
}
@Test
- public void testTakePart() throws IOException {
+ public void removePaper() throws IOException {
+ ConferenceDto newConferenceDto = conferenceService.removePaper(conferenceDto, 0);
+ assertEquals(conferenceDto, newConferenceDto);
+ }
+
+ @Test
+ public void takePart() throws IOException {
when(userService.getCurrentUser()).thenReturn(user);
ConferenceDto newConferenceDto = new ConferenceDto();
conferenceService.takePart(newConferenceDto);
@@ -155,18 +207,31 @@ public class ConferenceServiceTest {
}
@Test
- public void testFindOneDto() throws IOException {
- when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
- assertEquals(conferenceDto, conferenceService.findOneDto(1));
+ public void getAllUsers() {
+ List users = Collections.singletonList(user);
+ when(userService.findAll()).thenReturn(users);
+ assertEquals(users, conferenceService.getAllUsers());
+ }
+
+
+ @Test
+ public void filter() {
}
@Test
- public void testCreate() throws IOException {
- when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
- when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
- when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
- when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
- when(conferenceRepository.save(conferenceWithoutId)).thenReturn(conferenceWithoutId);
- assertNull(conferenceService.create(conferenceDto));
+ public void isAttachedToConference() {
}
-}
+
+ @Test
+ public void ping() {
+ }
+
+
+ @Test
+ public void checkEmptyFieldsOfDeadline() {
+ }
+
+ @Test
+ public void filterEmptyDeadlines() {
+ }
+}
\ No newline at end of file
From 7952787229fa31ec706ce6491ab5db8e5f72307f Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Wed, 15 May 2019 01:14:02 +0400
Subject: [PATCH 10/68] #104 add new tests, fixes
---
.../ru/ulstu/conference/model/Conference.java | 4 +-
.../conference/service/ConferenceService.java | 4 +-
.../service/ConferenceServiceTest.java | 40 ++++++++++---------
3 files changed, 26 insertions(+), 22 deletions(-)
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/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index c69d273..550c884 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -225,9 +225,9 @@ public class ConferenceService {
}
@Transactional
- public void ping(ConferenceDto conferenceDto) throws IOException {
+ public int ping(ConferenceDto conferenceDto) throws IOException {
pingService.addPing(findOne(conferenceDto.getId()));
- conferenceRepository.updatePingConference(conferenceDto.getId());
+ return conferenceRepository.updatePingConference(conferenceDto.getId());
}
private Conference findOne(Integer conferenceId) {
diff --git a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index 9fe8301..af583f9 100644
--- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -9,12 +9,14 @@ 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.service.PingService;
import ru.ulstu.timeline.service.EventService;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
@@ -47,11 +49,14 @@ public class ConferenceServiceTest {
@Mock
UserService userService;
+ @Mock
+ EventService eventService;
+
@Mock
ConferenceNotificationService conferenceNotificationService;
@Mock
- EventService eventService;
+ PingService pingService;
@InjectMocks
ConferenceService conferenceService;
@@ -62,12 +67,9 @@ public class ConferenceServiceTest {
private List conferenceUsers;
private Conference conferenceWithId;
- private Conference conferenceWithoutId;
- private ConferenceUser conferenceUser;
private Paper paperWithId;
private Paper paperWithoutId;
- private Deadline deadline;
private ConferenceDto conferenceDto;
private User user;
@@ -76,7 +78,7 @@ public class ConferenceServiceTest {
public void setUp() throws Exception {
conferences = new ArrayList<>();
conferenceWithId = new Conference();
- conferenceWithoutId = new Conference();
+ Conference conferenceWithoutId = new Conference();
conferenceWithId.setId(1);
conferenceWithId.setTitle("Название");
@@ -97,11 +99,11 @@ public class ConferenceServiceTest {
papers.add(paperWithoutId);
deadlines = new ArrayList<>();
- deadline = new Deadline(new Date(), "desc");
+ Deadline deadline = new Deadline(new Date(), "desc");
deadline.setId(1);
deadlines.add(deadline);
- conferenceUser = new ConferenceUser();
+ ConferenceUser conferenceUser = new ConferenceUser();
conferenceUser.setDeposit(ConferenceUser.Deposit.ARTICLE);
conferenceUser.setParticipation(ConferenceUser.Participation.INTRAMURAL);
user = new User();
@@ -164,7 +166,7 @@ public class ConferenceServiceTest {
when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId);
- assertEquals(conferenceWithId.getId(), conferenceService.create(conferenceDto));
+ assertEquals(conferenceWithId.getId(), conferenceService.update(conferenceDto));
}
@Test
@@ -216,22 +218,24 @@ public class ConferenceServiceTest {
@Test
public void filter() {
+ ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto();
+ conferenceFilterDto.setFilterUserId(1);
+ conferenceFilterDto.setYear(2019);
+ when(userService.findById(1)).thenReturn(user);
+ when(conferenceRepository.findByUserAndYear(user, 2019)).thenReturn(conferences);
+ assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto));
}
@Test
public void isAttachedToConference() {
+ when(conferenceRepository.isPaperAttached(1)).thenReturn(true);
+ assertTrue(conferenceService.isAttachedToConference(1));
}
@Test
- public void ping() {
- }
-
-
- @Test
- public void checkEmptyFieldsOfDeadline() {
- }
-
- @Test
- public void filterEmptyDeadlines() {
+ public void ping() throws IOException {
+ when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
+ when(conferenceRepository.updatePingConference(1)).thenReturn(1);
+ assertEquals(1, conferenceService.ping(conferenceDto));
}
}
\ No newline at end of file
From 11ef644e5e8e5c2b157ee937341f4a4aa8c4ef04 Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Wed, 15 May 2019 02:48:44 +0400
Subject: [PATCH 11/68] 88 inviting user base
---
.../ru/ulstu/configuration/Constants.java | 3 +
.../user/controller/UserControllerV2.java | 127 +-----------------
.../ru/ulstu/user/service/MailService.java | 14 ++
.../ru/ulstu/user/service/UserService.java | 32 ++++-
.../user/service/UserSessionService.java | 2 +-
.../java/ru/ulstu/user/util/UserUtils.java | 5 +
.../mail_templates/userInviteEmail.html | 21 +++
src/main/resources/templates/default.html | 7 +-
.../templates/users/inviteModal.html | 32 +++++
.../resources/templates/users/profile.html | 9 --
10 files changed, 114 insertions(+), 138 deletions(-)
create mode 100644 src/main/resources/mail_templates/userInviteEmail.html
create mode 100644 src/main/resources/templates/users/inviteModal.html
diff --git a/src/main/java/ru/ulstu/configuration/Constants.java b/src/main/java/ru/ulstu/configuration/Constants.java
index 0a2268a..51806b6 100644
--- a/src/main/java/ru/ulstu/configuration/Constants.java
+++ b/src/main/java/ru/ulstu/configuration/Constants.java
@@ -5,7 +5,10 @@ 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 int MIN_PASSWORD_LENGTH = 6;
+ public static final int MAX_PASSWORD_LENGTH = 32;
public static final String LOGIN_REGEX = "^[_'.@A-Za-z0-9-]*$";
diff --git a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
index f15872e..3447a49 100644
--- a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
+++ b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
@@ -1,36 +1,21 @@
package ru.ulstu.user.controller;
-import com.sun.org.apache.xpath.internal.operations.Mod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
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;
import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
-import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.configuration.Constants;
-import ru.ulstu.core.model.response.PageableItems;
-import ru.ulstu.core.model.response.Response;
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.*;
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 static ru.ulstu.user.controller.UserController.URL;
@Controller
@RequestMapping(value = "/users")
@@ -49,130 +34,32 @@ public class UserControllerV2 extends OdinController {
private final UserService userService;
private final UserSessionService userSessionService;
- private final OdinService odinRolesService;
- private final OdinService odinSessionsService;
public UserControllerV2(UserService userService,
- UserSessionService userSessionService,
- OdinService odinRolesService,
- OdinService odinSessionsService) {
+ UserSessionService userSessionService) {
super(UserListDto.class, UserDto.class);
this.userService = userService;
this.userSessionService = userSessionService;
- this.odinRolesService = odinRolesService;
- this.odinSessionsService = odinSessionsService;
}
@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.getUserDtoBySessionId(sessionId)));
+ 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.getUserDtoBySessionId(sessionId);
+ User user = userSessionService.getUserBySessionId(sessionId);
modelMap.addAttribute("userDto", userService.updateUserInformation(user, userDto));
}
- @GetMapping(ROLES_URL)
- @Secured(UserRoleConstants.ADMIN)
- public Response> getUserRoles() {
- log.debug("REST: UserController.getUserRoles()");
- return new Response<>(userService.getUserRoles());
- }
-
- @GetMapping(ROLES_META_URL)
- @Secured(UserRoleConstants.ADMIN)
- public Response getUserRolesMetaData() {
- log.debug("REST: UserController.getUserRolesMetaData()");
- return new Response<>(odinRolesService.getListModel(UserRoleDto.class));
- }
-
- @GetMapping(SESSIONS_URL)
- @Secured(UserRoleConstants.ADMIN)
- public Response> getUserSessions(@RequestParam(value = "offset", defaultValue = "0") int offset,
- @RequestParam(value = "count", defaultValue = "10") int count) {
- log.debug("REST: UserController.getUserSessions()");
- return new Response<>(userSessionService.getSessions(offset, count));
- }
-
- @GetMapping(SESSIONS_META_URL)
- @Secured(UserRoleConstants.ADMIN)
- public Response getUserSessionsMetaData() {
- log.debug("REST: UserController.getUserSessionsMetaData()");
- return new Response<>(odinSessionsService.getListModel(UserSessionListDto.class));
- }
-
- @GetMapping("")
- @Secured(UserRoleConstants.ADMIN)
- public Response> getAllUsers(@RequestParam(value = "offset", defaultValue = "0") int offset,
- @RequestParam(value = "count", defaultValue = "10") int count) {
- log.debug("REST: UserController.getAllUsers( {}, {} )", offset, count);
- return new Response<>(userService.getAllUsers(offset, count));
- }
-
- @GetMapping("/{userId}")
- @Secured(UserRoleConstants.ADMIN)
- public Response getUser(@PathVariable Integer userId) {
- log.debug("REST: UserController.getUser( {} )", userId);
- return new Response<>(userService.getUserWithRolesById(userId));
- }
-
-
- @PostMapping("")
- @Secured(UserRoleConstants.ADMIN)
- public Response createUser(@Valid @RequestBody UserDto userDto) {
- log.debug("REST: UserController.createUser( {} )", userDto.getLogin());
- return new Response<>(userService.createUser(userDto));
- }
-
- @PutMapping("")
- @Secured(UserRoleConstants.ADMIN)
- public Response updateUser(@Valid @RequestBody UserDto userDto) {
- log.debug("REST: UserController.updateUser( {} )", userDto.getLogin());
- return new Response<>(userService.updateUser(userDto));
- }
-
- @DeleteMapping("/{userId}")
- @Secured(UserRoleConstants.ADMIN)
- public Response deleteUser(@PathVariable Integer userId) {
- log.debug("REST: UserController.deleteUser( {} )", userId);
- return new Response<>(userService.deleteUser(userId));
- }
-
- @PostMapping(REGISTER_URL)
- public Response registerUser(@Valid @RequestBody UserDto userDto) {
- log.debug("REST: UserController.registerUser( {} )", userDto.getLogin());
- return new Response<>(userService.createUser(userDto));
- }
-
- @PostMapping(ACTIVATE_URL)
- public Response activateUser(@RequestParam("key") String activationKey) {
- log.debug("REST: UserController.activateUser( {} )", activationKey);
- return new Response<>(userService.activateUser(activationKey));
- }
-
- // 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) {
- log.debug("REST: UserController.requestPasswordReset( {} )", email);
- return new Response<>(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));
+ @PostMapping("/invite" )
+ public String inviteUser(@RequestParam(value = "email") String email){
+ userService.inviteUser(email);
+ return "redirect:/";
}
}
diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java
index da1da6d..da8e098 100644
--- a/src/main/java/ru/ulstu/user/service/MailService.java
+++ b/src/main/java/ru/ulstu/user/service/MailService.java
@@ -78,6 +78,15 @@ public class MailService {
sendEmail(user.getEmail(), subject, content);
}
+ @Async
+ public void sendEmailFromTemplate(Map variables, String templateName, String subject, String email) {
+ 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
public void sendActivationEmail(User user) {
sendEmailFromTemplate(user, "activationEmail", Constants.MAIL_ACTIVATE);
@@ -87,4 +96,9 @@ public class MailService {
public void sendPasswordResetMail(User user) {
sendEmailFromTemplate(user, "passwordResetEmail", Constants.MAIL_RESET);
}
+
+ @Async
+ public void sendInviteMail(Map variables, String email) {
+ sendEmailFromTemplate(variables, "userInviteEmail", Constants.MAIL_INVITE, email);
+ }
}
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index 202cf10..ef11796 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -1,5 +1,6 @@
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;
@@ -12,6 +13,7 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.configuration.ApplicationProperties;
+import ru.ulstu.configuration.Constants;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.jpa.OffsetablePageRequest;
import ru.ulstu.core.model.BaseEntity;
@@ -36,13 +38,7 @@ 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.*;
import java.util.stream.Collectors;
@Service
@@ -55,6 +51,7 @@ public class UserService implements UserDetailsService {
private final UserMapper userMapper;
private final MailService mailService;
private final ApplicationProperties applicationProperties;
+ private final Random random;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
@@ -68,6 +65,7 @@ public class UserService implements UserDetailsService {
this.userMapper = userMapper;
this.mailService = mailService;
this.applicationProperties = applicationProperties;
+ this.random = new Random();
}
private User getUserByEmail(String email) {
@@ -315,4 +313,24 @@ public class UserService implements UserDetailsService {
public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
}
+
+ public void inviteUser(String email) {
+ 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.setLastName("");
+ user.setActivated(true);
+ userRepository.save(user);
+
+ Map variables = ImmutableMap.of("password", password, "email", email);
+ mailService.sendInviteMail(variables, email);
+ }
}
diff --git a/src/main/java/ru/ulstu/user/service/UserSessionService.java b/src/main/java/ru/ulstu/user/service/UserSessionService.java
index 03415de..ae289d0 100644
--- a/src/main/java/ru/ulstu/user/service/UserSessionService.java
+++ b/src/main/java/ru/ulstu/user/service/UserSessionService.java
@@ -55,7 +55,7 @@ public class UserSessionService {
log.debug("User session {} closed", sessionId);
}
- public User getUserDtoBySessionId(String 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/mail_templates/userInviteEmail.html b/src/main/resources/mail_templates/userInviteEmail.html
new file mode 100644
index 0000000..180f0c5
--- /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/templates/default.html b/src/main/resources/templates/default.html
index 4f9ec12..0c92865 100644
--- a/src/main/resources/templates/default.html
+++ b/src/main/resources/templates/default.html
@@ -62,18 +62,21 @@
КИАС РФФИ
-
+
Профиль
+
@@ -114,6 +117,7 @@
/*]]>*/
+
@@ -148,6 +152,7 @@
f();
}
})(document, window, "yandex_metrika_callbacks2");
+
diff --git a/src/main/resources/templates/users/inviteModal.html b/src/main/resources/templates/users/inviteModal.html
new file mode 100644
index 0000000..5909c61
--- /dev/null
+++ b/src/main/resources/templates/users/inviteModal.html
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html
index 5468d1b..c97e539 100644
--- a/src/main/resources/templates/users/profile.html
+++ b/src/main/resources/templates/users/profile.html
@@ -49,15 +49,6 @@
class="alert alert-danger">Incorrect email
-
@@ -77,6 +78,7 @@
+
diff --git a/src/main/resources/templates/users/changePassword.html b/src/main/resources/templates/users/changePassword.html
new file mode 100644
index 0000000..845bbcb
--- /dev/null
+++ b/src/main/resources/templates/users/changePassword.html
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
From d50673f5fa5eec40dea9e7dbb55c16c2d94b73a8 Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Thu, 16 May 2019 01:01:31 +0400
Subject: [PATCH 16/68] 87-inviting-user small fix in mail template, and
changed default user name
---
src/main/java/ru/ulstu/user/service/UserService.java | 4 ++--
src/main/resources/mail_templates/userInviteEmail.html | 6 +++---
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index db20868..083b0f5 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -331,8 +331,8 @@ public class UserService implements UserDetailsService {
user.setPassword(passwordEncoder.encode(password));
user.setLogin(email);
user.setEmail(email);
- user.setFirstName("");
- user.setLastName("");
+ user.setFirstName("user");
+ user.setLastName("user");
user.setActivated(true);
userRepository.save(user);
diff --git a/src/main/resources/mail_templates/userInviteEmail.html b/src/main/resources/mail_templates/userInviteEmail.html
index 180f0c5..98fe85f 100644
--- a/src/main/resources/mail_templates/userInviteEmail.html
+++ b/src/main/resources/mail_templates/userInviteEmail.html
@@ -7,9 +7,9 @@
- Аккаунт в системе NG-Tracker был создан.
- Данные для входа:
- Логин -
+ Аккаунт в системе NG-Tracker был создан.
+ Данные для входа:
+ Логин -
Пароль -
From c47d4f8a05d4a3f573d87f269a9be31fd1a80398 Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Thu, 16 May 2019 01:17:04 +0400
Subject: [PATCH 17/68] #88 removed unused imports
---
src/main/java/ru/ulstu/user/controller/UserControllerV2.java | 2 --
1 file changed, 2 deletions(-)
diff --git a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
index 84c0349..23bbba9 100644
--- a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
+++ b/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
@@ -2,12 +2,10 @@ package ru.ulstu.user.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.http.MediaType;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.configuration.Constants;
From ce7b4c9c7a81d0752efc61a94a9216828aa5afd9 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 13:33:26 +0400
Subject: [PATCH 18/68] #104 addDeadline, removeDeadline fixed
---
.../ru/ulstu/deadline/model/Deadline.java | 5 ++++
.../service/ConferenceServiceTest.java | 25 +++++++++++++------
2 files changed, 22 insertions(+), 8 deletions(-)
diff --git a/src/main/java/ru/ulstu/deadline/model/Deadline.java b/src/main/java/ru/ulstu/deadline/model/Deadline.java
index 148697c..6c564aa 100644
--- a/src/main/java/ru/ulstu/deadline/model/Deadline.java
+++ b/src/main/java/ru/ulstu/deadline/model/Deadline.java
@@ -65,6 +65,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/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index af583f9..25c6d1b 100644
--- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -61,6 +61,9 @@ public class ConferenceServiceTest {
@InjectMocks
ConferenceService conferenceService;
+ private final Integer ID = 1;
+ private final Integer ROMOVE_INDEX = 0;
+
private List conferences;
private List deadlines;
private List papers;
@@ -171,20 +174,26 @@ public class ConferenceServiceTest {
@Test
public void delete() {
- when(conferenceRepository.exists(1)).thenReturn(true);
- assertTrue(conferenceService.delete(1));
+ when(conferenceRepository.exists(ID)).thenReturn(true);
+ when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId);
+ assertTrue(conferenceService.delete(ID));
}
@Test
public void addDeadline() {
- ConferenceDto newConferenceDto = conferenceService.addDeadline(conferenceDto);
- assertEquals(conferenceDto, newConferenceDto);
+ ConferenceDto newConferenceDto = new ConferenceDto();
+ newConferenceDto.getDeadlines().add(new Deadline());
+ conferenceDto.getDeadlines().clear();
+ assertEquals(newConferenceDto.getDeadlines(), conferenceService.addDeadline(conferenceDto).getDeadlines());
}
@Test
public void removeDeadline() throws IOException {
- ConferenceDto newConferenceDto = conferenceService.removeDeadline(conferenceDto, 0);
- assertEquals(conferenceDto, newConferenceDto);
+ ConferenceDto newConferenceDto = new ConferenceDto();
+ newConferenceDto.getRemovedDeadlineIds().add(ID);
+ ConferenceDto result = conferenceService.removeDeadline(conferenceDto, ROMOVE_INDEX);
+ assertEquals(newConferenceDto.getDeadlines(), result.getDeadlines());
+ assertEquals(newConferenceDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds());
}
@Test
@@ -196,7 +205,7 @@ public class ConferenceServiceTest {
@Test
public void removePaper() throws IOException {
- ConferenceDto newConferenceDto = conferenceService.removePaper(conferenceDto, 0);
+ ConferenceDto newConferenceDto = conferenceService.removePaper(conferenceDto, ROMOVE_INDEX);
assertEquals(conferenceDto, newConferenceDto);
}
@@ -234,7 +243,7 @@ public class ConferenceServiceTest {
@Test
public void ping() throws IOException {
- when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
+ when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId);
when(conferenceRepository.updatePingConference(1)).thenReturn(1);
assertEquals(1, conferenceService.ping(conferenceDto));
}
From c0937d721a2801efeb0b9a179ffaf9d08338f89b Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 15:35:32 +0400
Subject: [PATCH 19/68] #104 removePaper, addPaper, takePart fixed
---
src/main/java/ru/ulstu/paper/model/Paper.java | 27 +++++++++
.../service/ConferenceServiceTest.java | 57 +++++++++++--------
2 files changed, 61 insertions(+), 23 deletions(-)
diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java
index 4536ce5..2624b66 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;
@@ -264,4 +265,30 @@ 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/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index 25c6d1b..3a58cbb 100644
--- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -62,7 +62,9 @@ public class ConferenceServiceTest {
ConferenceService conferenceService;
private final Integer ID = 1;
- private final Integer ROMOVE_INDEX = 0;
+ private final Integer INDEX = 0;
+ private final String NAME = "Name";
+ private final boolean DISABLED = true;
private List conferences;
private List deadlines;
@@ -76,6 +78,7 @@ public class ConferenceServiceTest {
private ConferenceDto conferenceDto;
private User user;
+ private Deadline deadline;
@Before
public void setUp() throws Exception {
@@ -83,8 +86,8 @@ public class ConferenceServiceTest {
conferenceWithId = new Conference();
Conference conferenceWithoutId = new Conference();
- conferenceWithId.setId(1);
- conferenceWithId.setTitle("Название");
+ conferenceWithId.setId(ID);
+ conferenceWithId.setTitle(NAME);
conferenceWithId.setDescription("Описание");
conferenceWithoutId.setTitle("Название");
@@ -92,37 +95,31 @@ public class ConferenceServiceTest {
paperWithId = new Paper();
paperWithId.setId(1);
- paperWithId.setTitle("paperTitle");
+ paperWithId.setTitle(NAME);
paperWithoutId = new Paper();
- paperWithoutId.setTitle("paperTitleNoId");
+ paperWithoutId.setTitle(NAME);
papers = new ArrayList<>();
papers.add(paperWithId);
papers.add(paperWithoutId);
deadlines = new ArrayList<>();
- Deadline deadline = new Deadline(new Date(), "desc");
- deadline.setId(1);
+ deadline = new Deadline(new Date(), "desc");
+ 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");
+ user.setFirstName(NAME);
conferenceUser.setUser(user);
conferenceUsers = new ArrayList<>();
conferenceUsers.add(conferenceUser);
- conferenceWithId.setPapers(papers);
- conferenceWithId.setDeadlines(deadlines);
- conferenceWithId.setUsers(conferenceUsers);
- conferenceWithoutId.setPapers(papers);
- conferenceWithoutId.setDeadlines(deadlines);
- conferenceWithoutId.setUsers(conferenceUsers);
conferences.add(conferenceWithId);
conferenceDto = new ConferenceDto(conferenceWithId);
@@ -184,37 +181,52 @@ public class ConferenceServiceTest {
ConferenceDto newConferenceDto = new ConferenceDto();
newConferenceDto.getDeadlines().add(new Deadline());
conferenceDto.getDeadlines().clear();
- assertEquals(newConferenceDto.getDeadlines(), conferenceService.addDeadline(conferenceDto).getDeadlines());
+ 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 result = conferenceService.removeDeadline(conferenceDto, ROMOVE_INDEX);
+ conferenceDto.getDeadlines().add(deadline);
+ ConferenceDto result = conferenceService.removeDeadline(conferenceDto, INDEX);
assertEquals(newConferenceDto.getDeadlines(), result.getDeadlines());
assertEquals(newConferenceDto.getRemovedDeadlineIds(), result.getRemovedDeadlineIds());
}
@Test
public void addPaper() {
+ ConferenceDto newConferenceDto = new ConferenceDto();
+ newConferenceDto.getPapers().add(paperWithoutId);
+ conferenceDto.getPapers().clear();
when(userService.getCurrentUser()).thenReturn(user);
- ConferenceDto newConferenceDto = conferenceService.addPaper(conferenceDto);
- assertEquals(conferenceDto, newConferenceDto);
+ ConferenceDto result = conferenceService.addPaper(conferenceDto);
+ result.getPapers().get(INDEX).setTitle(NAME); // приходится вручную назначать название, т.е. название зависит от даты
+ assertEquals(newConferenceDto.getPapers(), result.getPapers());
}
@Test
public void removePaper() throws IOException {
- ConferenceDto newConferenceDto = conferenceService.removePaper(conferenceDto, ROMOVE_INDEX);
- assertEquals(conferenceDto, newConferenceDto);
+ 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();
- conferenceService.takePart(newConferenceDto);
- assertEquals(newConferenceDto.getUsers(), conferenceDto.getUsers());
+ newConferenceDto.setUsers(conferenceUsers);
+ newConferenceDto.setDisabledTakePart(DISABLED);
+ conferenceDto.getPapers().clear();
+ ConferenceDto result = conferenceService.takePart(conferenceDto);
+ assertEquals(newConferenceDto.getUsers(), result.getUsers());
+ assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart());
}
@Test
@@ -224,7 +236,6 @@ public class ConferenceServiceTest {
assertEquals(users, conferenceService.getAllUsers());
}
-
@Test
public void filter() {
ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto();
From bde9cb51fb20944b340792e8bb54b8d6cbec329a Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 15:55:29 +0400
Subject: [PATCH 20/68] #104 some methods fixed
---
.../conference/service/ConferenceService.java | 8 ++--
src/main/java/ru/ulstu/paper/model/Paper.java | 12 ++++--
.../ru/ulstu/ping/service/PingService.java | 4 +-
.../service/ConferenceServiceTest.java | 38 ++++++++++++-------
4 files changed, 41 insertions(+), 21 deletions(-)
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index 7162d37..633fa2e 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;
@@ -240,9 +241,10 @@ public class ConferenceService extends BaseService {
}
@Transactional
- public int ping(ConferenceDto conferenceDto) throws IOException {
- pingService.addPing(findOne(conferenceDto.getId()));
- return conferenceRepository.updatePingConference(conferenceDto.getId());
+ public Ping ping(ConferenceDto conferenceDto) throws IOException {
+ Ping ping = pingService.addPing(findOne(conferenceDto.getId()));
+ conferenceRepository.updatePingConference(conferenceDto.getId());
+ return ping;
}
private Conference findOne(Integer conferenceId) {
diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java
index 2624b66..15ee4b4 100644
--- a/src/main/java/ru/ulstu/paper/model/Paper.java
+++ b/src/main/java/ru/ulstu/paper/model/Paper.java
@@ -268,9 +268,15 @@ public class Paper extends BaseEntity implements UserContainer {
@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;
+ 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 &&
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/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index 3a58cbb..5925aed 100644
--- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -16,6 +16,7 @@ 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;
@@ -65,6 +66,7 @@ public class ConferenceServiceTest {
private final Integer INDEX = 0;
private final String NAME = "Name";
private final boolean DISABLED = true;
+ private final Integer YEAR = 2019;
private List conferences;
private List deadlines;
@@ -127,19 +129,27 @@ public class ConferenceServiceTest {
@Test
public void getExistConferenceById() {
- when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
+ when(conferenceRepository.findOne(ID)).thenReturn(conferenceWithId);
when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers);
when(userService.getCurrentUser()).thenReturn(user);
- conferenceDto.setDisabledTakePart(true);
- assertEquals(conferenceDto, conferenceService.getExistConferenceById(1));
+ ConferenceDto newConferenceDto = new ConferenceDto(conferenceWithId);
+ newConferenceDto.setNotSelectedPapers(papers);
+ newConferenceDto.setDisabledTakePart(!DISABLED);
+ 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);
- when(paperService.findAllNotSelect(new ArrayList<>())).thenReturn(papers);
- assertEquals(newConferenceDto, conferenceService.getNewConference());
+ ConferenceDto result = conferenceService.getNewConference();
+ assertEquals(newConferenceDto.getId(), result.getId());
+ assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers());
+ assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart());
}
@Test
@@ -239,23 +249,25 @@ public class ConferenceServiceTest {
@Test
public void filter() {
ConferenceFilterDto conferenceFilterDto = new ConferenceFilterDto();
- conferenceFilterDto.setFilterUserId(1);
- conferenceFilterDto.setYear(2019);
- when(userService.findById(1)).thenReturn(user);
- when(conferenceRepository.findByUserAndYear(user, 2019)).thenReturn(conferences);
+ conferenceFilterDto.setFilterUserId(ID);
+ conferenceFilterDto.setYear(YEAR);
+ when(userService.findById(ID)).thenReturn(user);
+ when(conferenceRepository.findByUserAndYear(user, YEAR)).thenReturn(conferences);
assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto));
}
@Test
public void isAttachedToConference() {
- when(conferenceRepository.isPaperAttached(1)).thenReturn(true);
- assertTrue(conferenceService.isAttachedToConference(1));
+ 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(conferenceRepository.updatePingConference(1)).thenReturn(1);
- assertEquals(1, conferenceService.ping(conferenceDto));
+ when(pingService.addPing(conferenceWithId)).thenReturn(ping);
+ when(conferenceRepository.updatePingConference(ID)).thenReturn(INDEX);
+ assertEquals(ping, conferenceService.ping(conferenceDto));
}
}
\ No newline at end of file
From 80de18d3eeca5434490107b796b92fd7d7e10010 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 16:31:10 +0400
Subject: [PATCH 21/68] #104 create fixed, remove update
---
.../conference/service/ConferenceService.java | 8 +-
.../service/ConferenceServiceTest.java | 88 +++++++++++--------
2 files changed, 56 insertions(+), 40 deletions(-)
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index 633fa2e..38ce659 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -111,16 +111,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)
@@ -134,7 +134,7 @@ public class ConferenceService extends BaseService {
conferenceNotificationService.updateConferencesDatesNotification(conference, oldBeginDate, oldEndDate);
}
conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove);
- return conference.getId();
+ return conference;
}
@Transactional
diff --git a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
index 5925aed..95f4820 100644
--- a/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
+++ b/src/test/java/ru/ulstu/conference/service/ConferenceServiceTest.java
@@ -62,11 +62,13 @@ public class ConferenceServiceTest {
@InjectMocks
ConferenceService conferenceService;
- private final Integer ID = 1;
- private final Integer INDEX = 0;
- private final String NAME = "Name";
- private final boolean DISABLED = true;
- private final Integer YEAR = 2019;
+ 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;
@@ -86,14 +88,10 @@ public class ConferenceServiceTest {
public void setUp() throws Exception {
conferences = new ArrayList<>();
conferenceWithId = new Conference();
- Conference conferenceWithoutId = new Conference();
conferenceWithId.setId(ID);
conferenceWithId.setTitle(NAME);
- conferenceWithId.setDescription("Описание");
-
- conferenceWithoutId.setTitle("Название");
- conferenceWithoutId.setDescription("Описание");
+ conferenceWithId.setDescription(DESCRIPTION);
paperWithId = new Paper();
paperWithId.setId(1);
@@ -107,7 +105,7 @@ public class ConferenceServiceTest {
papers.add(paperWithoutId);
deadlines = new ArrayList<>();
- deadline = new Deadline(new Date(), "desc");
+ deadline = new Deadline(new Date(), DESCRIPTION);
deadline.setId(ID);
deadlines.add(deadline);
@@ -121,8 +119,6 @@ public class ConferenceServiceTest {
conferenceUsers = new ArrayList<>();
conferenceUsers.add(conferenceUser);
-
-
conferences.add(conferenceWithId);
conferenceDto = new ConferenceDto(conferenceWithId);
}
@@ -132,10 +128,12 @@ public class ConferenceServiceTest {
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(!DISABLED);
+ newConferenceDto.setDisabledTakePart(!TRUE);
ConferenceDto result = conferenceService.getExistConferenceById(ID);
+
assertEquals(newConferenceDto.getId(), result.getId());
assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers());
assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart());
@@ -144,9 +142,11 @@ public class ConferenceServiceTest {
@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());
@@ -154,29 +154,34 @@ public class ConferenceServiceTest {
@Test
public void findAll() {
- when(conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"))).thenReturn(conferences);
- assertEquals(conferences, conferenceService.findAll());
+ when(conferenceRepository.findAll(SORT)).thenReturn(conferences);
+
+ assertEquals(Collections.singletonList(conferenceWithId), conferenceService.findAll());
}
@Test
public void create() throws IOException {
- when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
- when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
- when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
- when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
+ 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);
- assertEquals(conferenceWithId.getId(), conferenceService.create(conferenceDto));
- }
- @Test
- public void update() throws IOException {
- when(conferenceRepository.findOne(1)).thenReturn(conferenceWithId);
- when(paperService.findPaperById(paperWithId.getId())).thenReturn(paperWithId);
- when(paperService.create(paperWithoutId)).thenReturn(paperWithoutId);
- when(deadlineService.saveOrCreate(conferenceDto.getDeadlines())).thenReturn(deadlines);
- when(conferenceUserService.saveOrCreate(conferenceDto.getUsers())).thenReturn(conferenceUsers);
- when(conferenceRepository.save(new Conference())).thenReturn(conferenceWithId);
- assertEquals(conferenceWithId.getId(), conferenceService.update(conferenceDto));
+ 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
@@ -191,6 +196,7 @@ public class ConferenceServiceTest {
ConferenceDto newConferenceDto = new ConferenceDto();
newConferenceDto.getDeadlines().add(new Deadline());
conferenceDto.getDeadlines().clear();
+
assertEquals(newConferenceDto.getDeadlines().get(0), conferenceService.addDeadline(conferenceDto).getDeadlines().get(0));
}
@@ -200,18 +206,21 @@ public class ConferenceServiceTest {
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();
- when(userService.getCurrentUser()).thenReturn(user);
ConferenceDto result = conferenceService.addPaper(conferenceDto);
result.getPapers().get(INDEX).setTitle(NAME); // приходится вручную назначать название, т.е. название зависит от даты
+
assertEquals(newConferenceDto.getPapers(), result.getPapers());
}
@@ -223,6 +232,7 @@ public class ConferenceServiceTest {
conferenceDto.getPapers().add(paperWithId);
conferenceDto.getPapers().add(paperWithoutId);
ConferenceDto result = conferenceService.removePaper(conferenceDto, INDEX);
+
assertEquals(newConferenceDto.getPapers(), result.getPapers());
assertEquals(newConferenceDto.getNotSelectedPapers(), result.getNotSelectedPapers());
}
@@ -230,11 +240,13 @@ public class ConferenceServiceTest {
@Test
public void takePart() throws IOException {
when(userService.getCurrentUser()).thenReturn(user);
+
ConferenceDto newConferenceDto = new ConferenceDto();
newConferenceDto.setUsers(conferenceUsers);
- newConferenceDto.setDisabledTakePart(DISABLED);
+ newConferenceDto.setDisabledTakePart(TRUE);
conferenceDto.getPapers().clear();
ConferenceDto result = conferenceService.takePart(conferenceDto);
+
assertEquals(newConferenceDto.getUsers(), result.getUsers());
assertEquals(newConferenceDto.isDisabledTakePart(), result.isDisabledTakePart());
}
@@ -248,17 +260,20 @@ public class ConferenceServiceTest {
@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);
- when(userService.findById(ID)).thenReturn(user);
- when(conferenceRepository.findByUserAndYear(user, YEAR)).thenReturn(conferences);
+
assertEquals(Collections.singletonList(conferenceDto), conferenceService.filter(conferenceFilterDto));
}
@Test
public void isAttachedToConference() {
- when(conferenceRepository.isPaperAttached(ID)).thenReturn(true);
+ when(conferenceRepository.isPaperAttached(ID)).thenReturn(TRUE);
+
assertTrue(conferenceService.isAttachedToConference(ID));
}
@@ -268,6 +283,7 @@ public class ConferenceServiceTest {
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
From 526339337935f7913070fcfb9549ee667c31d8a1 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 17:55:34 +0400
Subject: [PATCH 22/68] #104 remove chart example from dashboard
---
.../templates/conferences/dashboard.html | 36 +++++++++----------
1 file changed, 18 insertions(+), 18 deletions(-)
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 @@
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
From dc34c7bfb7944a04403cf0f3f2c67136471df979 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Thu, 16 May 2019 18:07:18 +0400
Subject: [PATCH 23/68] #104 fixed conference-row style
---
src/main/resources/public/css/conference.css | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
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;
From 728fa4297278be50a17d55e2036d828cc940b27a Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Fri, 17 May 2019 02:01:26 +0400
Subject: [PATCH 24/68] 87 error handling
---
...ntrollerV2.java => UserMvcController.java} | 19 +++++++++++------
.../ru/ulstu/user/service/UserService.java | 5 ++++-
src/main/resources/templates/error/error.html | 21 +++++++++++++++++++
.../resources/templates/users/profile.html | 9 ++++++++
4 files changed, 47 insertions(+), 7 deletions(-)
rename src/main/java/ru/ulstu/user/controller/{UserControllerV2.java => UserMvcController.java} (77%)
create mode 100644 src/main/resources/templates/error/error.html
diff --git a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java b/src/main/java/ru/ulstu/user/controller/UserMvcController.java
similarity index 77%
rename from src/main/java/ru/ulstu/user/controller/UserControllerV2.java
rename to src/main/java/ru/ulstu/user/controller/UserMvcController.java
index eee98a1..c35dd79 100644
--- a/src/main/java/ru/ulstu/user/controller/UserControllerV2.java
+++ b/src/main/java/ru/ulstu/user/controller/UserMvcController.java
@@ -3,14 +3,15 @@ package ru.ulstu.user.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
+import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.configuration.Constants;
import ru.ulstu.odin.controller.OdinController;
-import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserListDto;
@@ -22,20 +23,26 @@ import javax.servlet.http.HttpSession;
@Controller
@RequestMapping(value = "/users")
-public class UserControllerV2 extends OdinController {
+public class UserMvcController extends OdinController {
- private final Logger log = LoggerFactory.getLogger(UserControllerV2.class);
+ private final Logger log = LoggerFactory.getLogger(UserMvcController.class);
private final UserService userService;
private final UserSessionService userSessionService;
- public UserControllerV2(UserService userService,
- UserSessionService userSessionService) {
+ public UserMvcController(UserService userService,
+ UserSessionService userSessionService) {
super(UserListDto.class, UserDto.class);
this.userService = userService;
this.userSessionService = userSessionService;
}
+ @ExceptionHandler(Exception.class)
+ public String errorHandler(Model model, Exception exception) {
+ model.addAttribute("error", exception.getMessage());
+ return "/error/error";
+ }
+
@GetMapping("/profile")
public void getUserProfile(ModelMap modelMap, HttpServletRequest request) {
HttpSession session = request.getSession(false);
@@ -52,7 +59,7 @@ public class UserControllerV2 extends OdinController {
}
@PostMapping("/invite")
- public String inviteUser(@RequestParam(value = "email") String email) throws UserSendingMailException {
+ public String inviteUser(@RequestParam(value = "email") String email, ModelMap modelMap) {
userService.inviteUser(email);
return "redirect:/";
}
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index 083b0f5..78f9d66 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -52,6 +52,8 @@ 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;
@@ -213,6 +215,7 @@ public class UserService implements UserDetailsService {
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);
@@ -340,7 +343,7 @@ public class UserService implements UserDetailsService {
try {
mailService.sendInviteMail(variables, email);
} catch (MessagingException e) {
- throw new UserSendingMailException(email);
+ throw new UserSendingMailException(INVITE_USER_EXCEPTION);
}
}
}
diff --git a/src/main/resources/templates/error/error.html b/src/main/resources/templates/error/error.html
new file mode 100644
index 0000000..53c9054
--- /dev/null
+++ b/src/main/resources/templates/error/error.html
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/resources/templates/users/profile.html b/src/main/resources/templates/users/profile.html
index c97e539..93adfc7 100644
--- a/src/main/resources/templates/users/profile.html
+++ b/src/main/resources/templates/users/profile.html
@@ -49,6 +49,15 @@
class="alert alert-danger">Incorrect email
+
\ No newline at end of file
From e468646cd6c5b2b214b15ba25855de5c824dfb90 Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Sun, 19 May 2019 00:47:49 +0400
Subject: [PATCH 37/68] 89 removed getCurrentUser
---
src/main/java/ru/ulstu/core/controller/AdviceController.java | 5 -----
src/main/resources/public/js/users.js | 1 -
2 files changed, 6 deletions(-)
diff --git a/src/main/java/ru/ulstu/core/controller/AdviceController.java b/src/main/java/ru/ulstu/core/controller/AdviceController.java
index 37078b9..f89001a 100644
--- a/src/main/java/ru/ulstu/core/controller/AdviceController.java
+++ b/src/main/java/ru/ulstu/core/controller/AdviceController.java
@@ -34,11 +34,6 @@ public class AdviceController {
public AdviceController(UserService userService) {
this.userService = userService;
}
-//
-// @ModelAttribute("currentUser")
-// public String getCurrentUser() {
-// return userService.getCurrentUser().getUserAbbreviate();
-// }
@ModelAttribute("flashMessage")
public String getFlashMessage() {
diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js
index a49bdc6..1ea26e3 100644
--- a/src/main/resources/public/js/users.js
+++ b/src/main/resources/public/js/users.js
@@ -81,7 +81,6 @@ function requestResetPassword() {
error: function(errorData) {
showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING)
document.getElementById("dvloader").hidden = true;
-
}
})
From 1823c1ba50c959dde3197fbfa64a516e9ffa1b3c Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Mon, 20 May 2019 18:37:24 +0400
Subject: [PATCH 38/68] #120 create kias page
---
src/test/java/grant/KiasPage.java | 28 ++++++++++++++++++++++++++++
1 file changed, 28 insertions(+)
create mode 100644 src/test/java/grant/KiasPage.java
diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java
new file mode 100644
index 0000000..49b40d9
--- /dev/null
+++ b/src/test/java/grant/KiasPage.java
@@ -0,0 +1,28 @@
+package grant;
+
+import core.PageObject;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+
+import java.util.List;
+
+public class KiasPage extends PageObject {
+ @Override
+ public String getSubTitle() {
+ return driver.findElement(By.tagName("h1")).getText();
+ }
+
+ public List getGrants() {
+ WebElement listContest = driver.findElement(By.tagName("tBody"));
+ return listContest.findElements(By.cssSelector("tr.tr"));
+
+ }
+
+ public String getGrantTitle(WebElement grant) {
+ return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
+ }
+
+ public String getFirstDeadline(WebElement grant) {
+ return grant.findElement(By.xpath("./td[5]")).getText();
+ }
+}
From c0e66e81a2e50d85a0859d1f779572a7e1065f1a Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Mon, 20 May 2019 20:47:10 +0400
Subject: [PATCH 39/68] #120 drop unnecessary table column
---
.../resources/db/changelog-20190520_000000-schema.xml | 8 ++++++++
src/main/resources/db/changelog-master.xml | 1 +
2 files changed, 9 insertions(+)
create mode 100644 src/main/resources/db/changelog-20190520_000000-schema.xml
diff --git a/src/main/resources/db/changelog-20190520_000000-schema.xml b/src/main/resources/db/changelog-20190520_000000-schema.xml
new file mode 100644
index 0000000..69cdad0
--- /dev/null
+++ b/src/main/resources/db/changelog-20190520_000000-schema.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml
index 18bd645..d2ccbca 100644
--- a/src/main/resources/db/changelog-master.xml
+++ b/src/main/resources/db/changelog-master.xml
@@ -42,4 +42,5 @@
+
\ No newline at end of file
From bb9f412480fc9948e41680a5a4c009a0c26f60b6 Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Mon, 20 May 2019 20:49:03 +0400
Subject: [PATCH 40/68] #120 check unique grant name
---
.../grant/controller/GrantController.java | 20 +---------
.../java/ru/ulstu/grant/model/GrantDto.java | 3 +-
.../grant/repository/GrantRepository.java | 9 ++++-
.../ru/ulstu/grant/service/GrantService.java | 37 ++++++++++++++++++-
4 files changed, 47 insertions(+), 22 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java
index ad5e992..91b0f91 100644
--- a/src/main/java/ru/ulstu/grant/controller/GrantController.java
+++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java
@@ -20,9 +20,7 @@ import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
-import java.util.stream.Collectors;
-import static org.springframework.util.StringUtils.isEmpty;
import static ru.ulstu.core.controller.Navigation.GRANTS_PAGE;
import static ru.ulstu.core.controller.Navigation.GRANT_PAGE;
import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@@ -62,17 +60,9 @@ public class GrantController {
@PostMapping(value = "/grant", params = "save")
public String save(@Valid GrantDto grantDto, Errors errors)
throws IOException {
- filterEmptyDeadlines(grantDto);
- if (grantDto.getDeadlines().isEmpty()) {
- errors.rejectValue("deadlines", "errorCode", "Не может быть пусто");
- }
- if (grantDto.getLeaderId().equals(-1)) {
- errors.rejectValue("leaderId", "errorCode", "Укажите руководителя");
- }
- if (errors.hasErrors()) {
+ if (!grantService.save(grantDto, errors)) {
return GRANT_PAGE;
}
- grantService.save(grantDto);
return String.format(REDIRECT_TO, GRANTS_PAGE);
}
@@ -89,7 +79,7 @@ public class GrantController {
@PostMapping(value = "/grant", params = "addDeadline")
public String addDeadline(@Valid GrantDto grantDto, Errors errors) {
- filterEmptyDeadlines(grantDto);
+ grantService.filterEmptyDeadlines(grantDto);
if (errors.hasErrors()) {
return GRANT_PAGE;
}
@@ -133,10 +123,4 @@ public class GrantController {
public List getAllPapers() {
return grantService.getAllUncompletedPapers();
}
-
- private void filterEmptyDeadlines(GrantDto grantDto) {
- grantDto.setDeadlines(grantDto.getDeadlines().stream()
- .filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
- .collect(Collectors.toList()));
- }
}
diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java
index 203d306..5a561b1 100644
--- a/src/main/java/ru/ulstu/grant/model/GrantDto.java
+++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java
@@ -6,6 +6,7 @@ import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;
+import ru.ulstu.name.NameContainer;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.user.model.UserDto;
@@ -17,7 +18,7 @@ import java.util.stream.Collectors;
import static ru.ulstu.core.util.StreamApiUtils.convert;
-public class GrantDto {
+public class GrantDto extends NameContainer {
private final static int MAX_AUTHORS_LENGTH = 60;
private Integer id;
diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
index 44c2cc0..26face4 100644
--- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
+++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
@@ -1,11 +1,18 @@
package ru.ulstu.grant.repository;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
import ru.ulstu.grant.model.Grant;
+import ru.ulstu.name.BaseRepository;
import java.util.List;
-public interface GrantRepository extends JpaRepository {
+public interface GrantRepository extends JpaRepository, BaseRepository {
List findByStatus(Grant.GrantStatus status);
+
+ @Override
+ @Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
+ String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java
index 45f9b2f..4972b6c 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantService.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantService.java
@@ -3,6 +3,7 @@ package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
+import org.springframework.validation.Errors;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
@@ -10,6 +11,7 @@ import ru.ulstu.file.service.FileService;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.repository.GrantRepository;
+import ru.ulstu.name.BaseService;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.service.PaperService;
@@ -27,6 +29,7 @@ import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty;
@@ -34,7 +37,7 @@ import static ru.ulstu.core.util.StreamApiUtils.convert;
import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service
-public class GrantService {
+public class GrantService extends BaseService {
private final static int MAX_DISPLAY_SIZE = 50;
private final GrantRepository grantRepository;
@@ -55,6 +58,7 @@ public class GrantService {
EventService eventService,
GrantNotificationService grantNotificationService) {
this.grantRepository = grantRepository;
+ this.baseRepository = grantRepository;
this.fileService = fileService;
this.deadlineService = deadlineService;
this.projectService = projectService;
@@ -176,12 +180,35 @@ public class GrantService {
return grant;
}
- public void save(GrantDto grantDto) throws IOException {
+ public boolean save(GrantDto grantDto, Errors errors) throws IOException {
+ grantDto.setName(grantDto.getTitle());
+ filterEmptyDeadlines(grantDto);
+ checkEmptyDeadlines(grantDto, errors);
+ checkEmptyLeader(grantDto, errors);
+ checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует");
+ if (errors.hasErrors()) {
+ return false;
+ }
+
if (isEmpty(grantDto.getId())) {
create(grantDto);
} else {
update(grantDto);
}
+
+ return true;
+ }
+
+ private void checkEmptyLeader(GrantDto grantDto, Errors errors) {
+ if (grantDto.getLeaderId().equals(-1)) {
+ errors.rejectValue("leaderId", "errorCode", "Укажите руководителя");
+ }
+ }
+
+ private void checkEmptyDeadlines(GrantDto grantDto, Errors errors) {
+ if (grantDto.getDeadlines().isEmpty()) {
+ errors.rejectValue("deadlines", "errorCode", "Не может быть пусто");
+ }
}
public List getGrantAuthors(GrantDto grantDto) {
@@ -261,4 +288,10 @@ public class GrantService {
.filter(author -> Collections.frequency(authors, author) > 3)
.collect(toList());
}
+
+ public void filterEmptyDeadlines(GrantDto grantDto) {
+ grantDto.setDeadlines(grantDto.getDeadlines().stream()
+ .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
+ .collect(Collectors.toList()));
+ }
}
From 8b52518c4a0411c760d7cac83153da69e4f2c628 Mon Sep 17 00:00:00 2001
From: Nightblade73
Date: Tue, 21 May 2019 15:53:42 +0400
Subject: [PATCH 41/68] #125 check method
---
.../conference/service/ConferenceService.java | 7 +++++++
.../templates/conferences/conference.html | 14 +++++++++++++-
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/src/main/java/ru/ulstu/conference/service/ConferenceService.java b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
index 38ce659..4ee4198 100644
--- a/src/main/java/ru/ulstu/conference/service/ConferenceService.java
+++ b/src/main/java/ru/ulstu/conference/service/ConferenceService.java
@@ -92,6 +92,7 @@ public class ConferenceService extends BaseService {
conferenceDto.setName(conferenceDto.getTitle());
filterEmptyDeadlines(conferenceDto);
checkEmptyFieldsOfDeadline(conferenceDto, errors);
+ checkEmptyFieldsOfDates(conferenceDto, errors);
checkUniqueName(conferenceDto,
errors,
conferenceDto.getId(),
@@ -301,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/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
+
+
+
Incorrect title
@@ -94,6 +103,10 @@
+ Incorrect date
+
Участники:
@@ -123,7 +136,6 @@
-
From bab621677eb65e10da2a75ba66e8c016da6389c9 Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Wed, 22 May 2019 15:10:51 +0400
Subject: [PATCH 42/68] #120 add methods for checking unique title and date of
grant
---
.../ru/ulstu/deadline/repository/DeadlineRepository.java | 7 +++++++
.../java/ru/ulstu/deadline/service/DeadlineService.java | 5 +++++
.../java/ru/ulstu/grant/repository/GrantRepository.java | 2 ++
src/main/java/ru/ulstu/name/BaseService.java | 7 +++++++
4 files changed, 21 insertions(+)
diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
index f26c572..5b434b9 100644
--- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
+++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
@@ -2,8 +2,15 @@ package ru.ulstu.deadline.repository;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
import ru.ulstu.deadline.model.Deadline;
+import java.util.Date;
+
public interface DeadlineRepository extends JpaRepository {
+ @Query(
+ value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)",
+ nativeQuery = true)
+ Date findByGrantIdAndDate(Integer grant_id, Date date);
}
diff --git a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java
index 0ef8a4f..e82211d 100644
--- a/src/main/java/ru/ulstu/deadline/service/DeadlineService.java
+++ b/src/main/java/ru/ulstu/deadline/service/DeadlineService.java
@@ -5,6 +5,7 @@ import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.repository.DeadlineRepository;
+import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@@ -46,4 +47,8 @@ public class DeadlineService {
public void remove(Integer deadlineId) {
deadlineRepository.delete(deadlineId);
}
+
+ public Date findByGrantIdAndDate(Integer id, Date date) {
+ return deadlineRepository.findByGrantIdAndDate(id, date);
+ }
}
diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
index 26face4..ae9fcc8 100644
--- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
+++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
@@ -12,6 +12,8 @@ public interface GrantRepository extends JpaRepository, BaseRepo
List findByStatus(Grant.GrantStatus status);
+ Grant findByTitle(String title);
+
@Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
diff --git a/src/main/java/ru/ulstu/name/BaseService.java b/src/main/java/ru/ulstu/name/BaseService.java
index 6619385..fd63cbf 100644
--- a/src/main/java/ru/ulstu/name/BaseService.java
+++ b/src/main/java/ru/ulstu/name/BaseService.java
@@ -13,4 +13,11 @@ public abstract class BaseService {
errors.rejectValue(checkField, "errorCode", errorMessage);
}
}
+
+ public String checkUniqueName(NameContainer nameContainer, Integer id) {
+ if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) {
+ return baseRepository.findByNameAndNotId(nameContainer.getName(), id);
+ }
+ return null;
+ }
}
From c21739bfc627b1aad3de8edbec7e4ad7d5d8a0dc Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Wed, 22 May 2019 15:12:45 +0400
Subject: [PATCH 43/68] #120 parse kias page
---
src/test/java/IndexKiasTest.java | 67 +++++++++++++++++++++++++++++++
src/test/java/grant/KiasPage.java | 28 ++++++++++++-
2 files changed, 93 insertions(+), 2 deletions(-)
create mode 100644 src/test/java/IndexKiasTest.java
diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java
new file mode 100644
index 0000000..73dc646
--- /dev/null
+++ b/src/test/java/IndexKiasTest.java
@@ -0,0 +1,67 @@
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import core.PageObject;
+import core.TestTemplate;
+import grant.KiasPage;
+import org.junit.runner.RunWith;
+import org.openqa.selenium.WebElement;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+import ru.ulstu.NgTrackerApplication;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.grant.model.Grant;
+import ru.ulstu.grant.model.GrantDto;
+import ru.ulstu.user.repository.UserRepository;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
+public class IndexKiasTest extends TestTemplate {
+ private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
+ private final static String CONTEST_STATUS_ID = "1";
+ private final static String CONTEST_TYPE = "-1";
+ private final static String CONTEST_YEAR = "2019";
+
+ private final Map> navigationHolder = ImmutableMap.of(
+ new KiasPage(), Arrays.asList("Поиск по конкурсам",
+ String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR))
+ );
+
+ @Autowired
+ UserRepository userRepository;
+
+ public List getNewGrantsDto() throws ParseException {
+ Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0);
+ getContext().goTo(page.getValue().get(1));
+ KiasPage kiasPage = (KiasPage) getContext().initPage(page.getKey());
+ List kiasGrants = new ArrayList<>();
+ List newGrants = new ArrayList<>();
+ do {
+ kiasGrants.addAll(kiasPage.getPageOfGrants());
+ for (WebElement grant : kiasGrants) {
+ GrantDto grantDto = new GrantDto();
+ grantDto.setTitle(kiasPage.getGrantTitle(grant));
+ String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59
+ SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
+ Date date = formatter.parse(deadlineDate);
+ Deadline deadline = new Deadline(date, "Окончание приёма заявок");
+ grantDto.setDeadlines(Arrays.asList(deadline));
+ grantDto.setLeaderId(userRepository.findOneByLoginIgnoreCase("admin").getId());
+ grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS);
+ newGrants.add(grantDto);
+ }
+ kiasGrants.clear();
+ }
+ while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
+
+ return newGrants;
+ }
+}
diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java
index 49b40d9..7723b01 100644
--- a/src/test/java/grant/KiasPage.java
+++ b/src/test/java/grant/KiasPage.java
@@ -4,7 +4,9 @@ import core.PageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
+import java.util.ArrayList;
import java.util.List;
+import java.util.NoSuchElementException;
public class KiasPage extends PageObject {
@Override
@@ -13,9 +15,31 @@ public class KiasPage extends PageObject {
}
public List getGrants() {
- WebElement listContest = driver.findElement(By.tagName("tBody"));
- return listContest.findElements(By.cssSelector("tr.tr"));
+ List grants = new ArrayList<>();
+ do {
+ grants.addAll(getPageOfGrants());
+ }
+ while (checkPagination());
+ return grants;
+ }
+
+ public List getPageOfGrants() {
+ WebElement listContest = driver.findElement(By.tagName("tBody"));
+ List grants = listContest.findElements(By.cssSelector("tr.tr"));
+ return grants;
+ }
+
+ public boolean checkPagination() {
+ try {
+ if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
+ driver.findElement(By.id("js-ctrlNext")).click();
+ return true;
+ }
+ } catch (NoSuchElementException e) {
+ return false;
+ }
+ return false;
}
public String getGrantTitle(WebElement grant) {
From 5f214620bff80e208fc4b382be55d5070057cdd6 Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Wed, 22 May 2019 15:16:20 +0400
Subject: [PATCH 44/68] #120 use loading from kias
---
.../ulstu/grant/service/GrantScheduler.java | 22 +++++++++++++++
.../ru/ulstu/grant/service/GrantService.java | 27 +++++++++++++++++--
2 files changed, 47 insertions(+), 2 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
index 1c38c4a..efe1e41 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
@@ -27,4 +27,26 @@ public class GrantScheduler {
grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished");
}
+
+ @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara")
+ public void loadGrantsFromKias() {
+ log.debug("GrantScheduler.loadGrantsFromKias started");
+ //
+ // Метод для сохранения загруженных грантов
+ //
+
+// List grants = IndexKiasTest.getNewGrantsDto();
+// grants.forEach(grantDto -> {
+// try {
+// if (grantService.saveFromKias(grantDto)) {
+// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded");
+// } else {
+// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists");
+// }
+// } catch (IOException e) {
+// e.printStackTrace();
+// }
+// });
+ log.debug("GrantScheduler.loadGrantsFromKias finished");
+ }
}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java
index 4972b6c..38c16c3 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantService.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantService.java
@@ -189,16 +189,31 @@ public class GrantService extends BaseService {
if (errors.hasErrors()) {
return false;
}
-
if (isEmpty(grantDto.getId())) {
create(grantDto);
} else {
update(grantDto);
}
-
return true;
}
+ public boolean saveFromKias(GrantDto grantDto) throws IOException {
+ grantDto.setName(grantDto.getTitle());
+ String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени
+ if (title != null) {
+ Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд
+ if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают
+ return false;
+ } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать
+ create(grantDto);
+ return true;
+ }
+ } else { //иначе такого гранта ещё нет, поэтому надо создать
+ create(grantDto);
+ return true;
+ }
+ }
+
private void checkEmptyLeader(GrantDto grantDto, Errors errors) {
if (grantDto.getLeaderId().equals(-1)) {
errors.rejectValue("leaderId", "errorCode", "Укажите руководителя");
@@ -211,6 +226,14 @@ public class GrantService extends BaseService {
}
}
+ private boolean checkSameDeadline(GrantDto grantDto, Integer id) {
+ Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас
+ if (deadlineService.findByGrantIdAndDate(id, date).compareTo(date) == 0) { //если есть такая строка с датой
+ return true;
+ }
+ return false;
+ }
+
public List getGrantAuthors(GrantDto grantDto) {
List filteredUsers = userService.filterByAgeAndDegree(grantDto.isHasAge(), grantDto.isHasDegree());
if (grantDto.isWasLeader()) {
From 457f1da98525439184bddad051aafbce2a710325 Mon Sep 17 00:00:00 2001
From: T-Midnight
Date: Wed, 22 May 2019 15:45:23 +0400
Subject: [PATCH 45/68] #120 fix checkRun and checkStyle
---
.../java/ru/ulstu/deadline/repository/DeadlineRepository.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
index 5b434b9..3f237e4 100644
--- a/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
+++ b/src/main/java/ru/ulstu/deadline/repository/DeadlineRepository.java
@@ -12,5 +12,5 @@ public interface DeadlineRepository extends JpaRepository {
@Query(
value = "SELECT date FROM Deadline d WHERE (d.grant_id = ?1) AND (d.date = ?2)",
nativeQuery = true)
- Date findByGrantIdAndDate(Integer grant_id, Date date);
+ Date findByGrantIdAndDate(Integer grantId, Date date);
}
From bd24525315e5c9f21b1345fde5c92615f8668582 Mon Sep 17 00:00:00 2001
From: ASH
Date: Thu, 23 May 2019 00:15:03 +0400
Subject: [PATCH 46/68] #103 integration tests
---
src/test/java/IndexTaskTest.java | 214 ++++++++++++++++++
src/test/java/students/TaskPage.java | 81 +++++++
.../java/students/TasksDashboardPage.java | 10 +
src/test/java/students/TasksPage.java | 75 ++++++
4 files changed, 380 insertions(+)
create mode 100644 src/test/java/IndexTaskTest.java
create mode 100644 src/test/java/students/TaskPage.java
create mode 100644 src/test/java/students/TasksDashboardPage.java
create mode 100644 src/test/java/students/TasksPage.java
diff --git a/src/test/java/IndexTaskTest.java b/src/test/java/IndexTaskTest.java
new file mode 100644
index 0000000..51b5e07
--- /dev/null
+++ b/src/test/java/IndexTaskTest.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 IndexTaskTest 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/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());
+ }
+}
From 284a3f51e9539c27db16825145815006c1d510ab Mon Sep 17 00:00:00 2001
From: ASH
Date: Thu, 23 May 2019 12:07:34 +0400
Subject: [PATCH 47/68] #104 mod tests filter and create tasks
---
.../java/ru/ulstu/students/model/TaskDto.java | 20 ++
.../students/service/TaskServiceTest.java | 181 ++++++++++++++++++
2 files changed, 201 insertions(+)
create mode 100644 src/test/java/ru/ulstu/students/service/TaskServiceTest.java
diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java
index 8d52e01..1d0eac0 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,25 @@ 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/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
new file mode 100644
index 0000000..e00570c
--- /dev/null
+++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
@@ -0,0 +1,181 @@
+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.deadline.model.Deadline;
+import ru.ulstu.deadline.service.DeadlineService;
+import ru.ulstu.students.model.Task;
+import ru.ulstu.students.model.TaskDto;
+import ru.ulstu.students.model.TaskFilterDto;
+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.Collections;
+import java.util.Date;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.when;
+
+@RunWith(MockitoJUnitRunner.class)
+public class TaskServiceTest {
+
+ @Mock
+ TaskRepository taskRepository;
+
+ @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 List tasks;
+ private List tags;
+ private Task task;
+ private TaskFilterDto filterDto;
+ private TaskDto taskDto;
+ private List tasksDto;
+ private Tag tag;
+ private Tag tagNull;
+ private Deadline deadline;
+ private List deadlines;
+
+
+ @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);
+
+ tags = new ArrayList<>();
+ tags.add(tag);
+
+ tasks.add(task);
+ taskDto = new TaskDto(task);
+
+ }
+
+ @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 update() {
+ }
+
+ @Test
+ public void delete() {
+ }
+
+ @Test
+ public void save() {
+ }
+
+ @Test
+ public void copyMainPart() {
+ }
+
+ @Test
+ public void copyTaskWithNewDates() {
+ }
+
+ @Test
+ public void copyTaskWithNewYear() {
+ }
+
+ @Test
+ public void generateYearTasks() {
+ }
+
+ @Test
+ public void checkRepeatingTags() {
+ }
+
+ @Test
+ public void getTaskStatuses() {
+ }
+
+ @Test
+ public void getTags() {
+ }
+
+ @Test
+ public void findTasksByTag() {
+ }
+
+ @Test
+ public void createPeriodTask() {
+ }
+}
\ No newline at end of file
From 1c8359f900fef08760ad9dc30aaec1103fc867e3 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Thu, 23 May 2019 13:54:44 +0400
Subject: [PATCH 48/68] #103 modify files permissions
---
src/main/resources/drivers/chromedriver | Bin
src/main/resources/drivers/geckodriver | Bin
2 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 src/main/resources/drivers/chromedriver
mode change 100644 => 100755 src/main/resources/drivers/geckodriver
diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver
old mode 100644
new mode 100755
diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver
old mode 100644
new mode 100755
From ef521123dd157ea0381d2b6699be4ac9569e295e Mon Sep 17 00:00:00 2001
From: ASH
Date: Thu, 23 May 2019 14:31:34 +0400
Subject: [PATCH 49/68] #104 mod tests check repeatings
---
.../java/ru/ulstu/students/model/TaskDto.java | 8 +++-
.../ulstu/students/service/TaskService.java | 10 ++--
.../students/service/TaskServiceTest.java | 46 +++++++++++--------
3 files changed, 38 insertions(+), 26 deletions(-)
diff --git a/src/main/java/ru/ulstu/students/model/TaskDto.java b/src/main/java/ru/ulstu/students/model/TaskDto.java
index 1d0eac0..2df691f 100644
--- a/src/main/java/ru/ulstu/students/model/TaskDto.java
+++ b/src/main/java/ru/ulstu/students/model/TaskDto.java
@@ -138,8 +138,12 @@ public class TaskDto {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
TaskDto taskDto = (TaskDto) o;
return Objects.equals(id, taskDto.id) &&
Objects.equals(title, taskDto.title) &&
diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java
index 2be44cb..379314d 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()));
diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
index e00570c..19eff12 100644
--- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
+++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
@@ -7,11 +7,13 @@ 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.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;
@@ -21,9 +23,12 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
@@ -32,6 +37,9 @@ public class TaskServiceTest {
@Mock
TaskRepository taskRepository;
+ @Mock
+ SchedulerRepository schedulerRepository;
+
@Mock
private TagService tagService;
@@ -50,6 +58,7 @@ public class TaskServiceTest {
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;
@@ -61,6 +70,7 @@ public class TaskServiceTest {
private Tag tagNull;
private Deadline deadline;
private List deadlines;
+ private Set repeatingTags;
@Before
@@ -83,12 +93,17 @@ public class TaskServiceTest {
deadline.setId(ID);
deadlines.add(deadline);
+ task.setDeadlines(deadlines);
+
tags = new ArrayList<>();
tags.add(tag);
tasks.add(task);
taskDto = new TaskDto(task);
+ repeatingTags = new HashSet<>();
+ repeatingTags.add(tag);
+
}
@Test
@@ -132,35 +147,26 @@ public class TaskServiceTest {
}
@Test
- public void update() {
- }
+ public void delete() throws IOException {
+ when(taskRepository.exists(ID)).thenReturn(true);
+ when(taskRepository.findOne(ID)).thenReturn(task);
+ when(schedulerRepository.findOneByTask(task)).thenReturn(null);
- @Test
- public void delete() {
- }
-
- @Test
- public void save() {
- }
-
- @Test
- public void copyMainPart() {
- }
-
- @Test
- public void copyTaskWithNewDates() {
- }
-
- @Test
- public void copyTaskWithNewYear() {
+ assertTrue(taskService.delete(ID));
}
@Test
public void generateYearTasks() {
+ when(taskService.checkRepeatingTags(false)).thenReturn(repeatingTags);
+
}
@Test
public void checkRepeatingTags() {
+ when(tagService.findById(ID)).thenReturn(tag);
+ when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks);
+
+ assertEquals(tag, taskService.checkRepeatingTags(false));
}
@Test
From 29cfadef02940976788796151f41132d557a5884 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Thu, 23 May 2019 15:02:55 +0400
Subject: [PATCH 50/68] #127 reference model, schema
---
.../java/ru/ulstu/paper/model/Reference.java | 90 +++++++++++++++++++
.../db/changelog-20190523_000000-schema.xml | 34 +++++++
src/main/resources/db/changelog-master.xml | 1 +
3 files changed, 125 insertions(+)
create mode 100644 src/main/java/ru/ulstu/paper/model/Reference.java
create mode 100644 src/main/resources/db/changelog-20190523_000000-schema.xml
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..1901f41
--- /dev/null
+++ b/src/main/java/ru/ulstu/paper/model/Reference.java
@@ -0,0 +1,90 @@
+package ru.ulstu.paper.model;
+
+import org.hibernate.validator.constraints.NotBlank;
+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 {
+
+ @NotBlank
+ 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/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml
new file mode 100644
index 0000000..2bdc788
--- /dev/null
+++ b/src/main/resources/db/changelog-20190523_000000-schema.xml
@@ -0,0 +1,34 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/db/changelog-master.xml b/src/main/resources/db/changelog-master.xml
index 18bd645..5011cc5 100644
--- a/src/main/resources/db/changelog-master.xml
+++ b/src/main/resources/db/changelog-master.xml
@@ -42,4 +42,5 @@
+
\ No newline at end of file
From 7c1b124c9470821b47c82642a7c6b945724efd04 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Thu, 23 May 2019 15:48:46 +0400
Subject: [PATCH 51/68] #127 references tab, crud
---
.../paper/controller/PaperController.java | 20 ++++
src/main/java/ru/ulstu/paper/model/Paper.java | 13 +++
.../java/ru/ulstu/paper/model/PaperDto.java | 25 ++++-
.../java/ru/ulstu/paper/model/Reference.java | 2 -
.../ru/ulstu/paper/model/ReferenceDto.java | 39 +++++++-
.../paper/repository/ReferenceRepository.java | 8 ++
.../ru/ulstu/paper/service/PaperService.java | 57 +++++++++++
.../db/changelog-20190523_000000-schema.xml | 13 +--
src/main/resources/public/css/paper.css | 20 ++++
.../resources/templates/papers/paper.html | 97 ++++++++++++++++++-
10 files changed, 279 insertions(+), 15 deletions(-)
create mode 100644 src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java
index 41d5586..beae772 100644
--- a/src/main/java/ru/ulstu/paper/controller/PaperController.java
+++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java
@@ -16,6 +16,7 @@ import ru.ulstu.deadline.model.Deadline;
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 +106,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 +139,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();
diff --git a/src/main/java/ru/ulstu/paper/model/Paper.java b/src/main/java/ru/ulstu/paper/model/Paper.java
index 15ee4b4..413c5db 100644
--- a/src/main/java/ru/ulstu/paper/model/Paper.java
+++ b/src/main/java/ru/ulstu/paper/model/Paper.java
@@ -123,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;
}
@@ -248,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()
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
index 1901f41..289cdc1 100644
--- a/src/main/java/ru/ulstu/paper/model/Reference.java
+++ b/src/main/java/ru/ulstu/paper/model/Reference.java
@@ -1,6 +1,5 @@
package ru.ulstu.paper.model;
-import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Column;
@@ -11,7 +10,6 @@ import javax.persistence.Enumerated;
@Entity
public class Reference extends BaseEntity {
- @NotBlank
private String authors;
@Column(name = "publication_title")
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..68e97d4
--- /dev/null
+++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
@@ -0,0 +1,8 @@
+package ru.ulstu.paper.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import ru.ulstu.paper.model.Reference;
+
+public interface ReferenceRepository extends JpaRepository {
+ void deleteById(Integer id);
+}
diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java
index db810f5..8658015 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -10,8 +10,10 @@ import ru.ulstu.file.service.FileService;
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 +41,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 +52,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 +123,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 +134,43 @@ 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());
+ updateReference.setAuthors(referenceDto.getAuthors());
+ updateReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle());
+ updateReference.setPages(referenceDto.getPages());
+ updateReference.setPublicationTitle(referenceDto.getPublicationTitle());
+ updateReference.setPublicationYear(referenceDto.getPublicationYear());
+ updateReference.setPublisher(referenceDto.getPublisher());
+ updateReference.setReferenceType(referenceDto.getReferenceType());
+ referenceRepository.save(updateReference);
+ return updateReference;
+ }
+
+ @Transactional
+ public Reference createReference(ReferenceDto referenceDto) {
+ Reference newReference = new Reference();
+ newReference.setAuthors(referenceDto.getAuthors());
+ newReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle());
+ newReference.setPages(referenceDto.getPages());
+ newReference.setPublicationTitle(referenceDto.getPublicationTitle());
+ newReference.setPublicationYear(referenceDto.getPublicationYear());
+ newReference.setPublisher(referenceDto.getPublisher());
+ newReference.setReferenceType(referenceDto.getReferenceType());
+ newReference = referenceRepository.save(newReference);
+ return newReference;
+ }
+
+
@Transactional
public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.findOne(paperDto.getId());
@@ -139,6 +183,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 +217,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();
diff --git a/src/main/resources/db/changelog-20190523_000000-schema.xml b/src/main/resources/db/changelog-20190523_000000-schema.xml
index 2bdc788..aca880f 100644
--- a/src/main/resources/db/changelog-20190523_000000-schema.xml
+++ b/src/main/resources/db/changelog-20190523_000000-schema.xml
@@ -7,20 +7,13 @@
-
-
-
-
-
-
-
-
-
+
+
+
-
diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css
index 824209f..1be8c1f 100644
--- a/src/main/resources/public/css/paper.css
+++ b/src/main/resources/public/css/paper.css
@@ -6,4 +6,24 @@
.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;
}
\ No newline at end of file
diff --git a/src/main/resources/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html
index d408913..ef4217d 100644
--- a/src/main/resources/templates/papers/paper.html
+++ b/src/main/resources/templates/papers/paper.html
@@ -31,6 +31,9 @@
href="#nav-main" role="tab" aria-controls="nav-main" aria-selected="true">Статья
Latex
+ References
@@ -167,6 +170,99 @@
+
@@ -378,7 +474,6 @@
$('#pdfBtn').prop('disabled', false);
}
}
-
From c303d65c8d8c02fc0d86c4ec332067e334cfe7ec Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Thu, 23 May 2019 16:02:44 +0400
Subject: [PATCH 52/68] #120 move to services
---
build.gradle | 2 +-
.../java/ru/ulstu/grant/page/KiasPage.java | 52 ++
.../ulstu/grant/service/GrantScheduler.java | 24 +-
.../ru/ulstu/grant/service/GrantService.java | 20 +-
.../ru/ulstu/grant/service/KiasService.java | 83 +++
.../ru/ulstu/user/service/UserService.java | 693 +++++++++---------
src/main/resources/drivers/chromedriver | Bin
src/main/resources/drivers/geckodriver | Bin
8 files changed, 512 insertions(+), 362 deletions(-)
create mode 100644 src/main/java/ru/ulstu/grant/page/KiasPage.java
create mode 100644 src/main/java/ru/ulstu/grant/service/KiasService.java
mode change 100644 => 100755 src/main/resources/drivers/chromedriver
mode change 100644 => 100755 src/main/resources/drivers/geckodriver
diff --git a/build.gradle b/build.gradle
index 38de2c7..71c9977 100644
--- a/build.gradle
+++ b/build.gradle
@@ -126,6 +126,6 @@ dependencies {
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
- testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
+ compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
}
\ No newline at end of file
diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java
new file mode 100644
index 0000000..4353684
--- /dev/null
+++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java
@@ -0,0 +1,52 @@
+package ru.ulstu.grant.page;
+
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class KiasPage {
+ private WebDriver driver;
+ public KiasPage(WebDriver webDriver) {
+ this.driver = webDriver;
+ }
+
+ public List getGrants() {
+ List grants = new ArrayList<>();
+ do {
+ grants.addAll(getPageOfGrants());
+ }
+ while (checkPagination());
+
+ return grants;
+ }
+
+ public List getPageOfGrants() {
+ WebElement listContest = driver.findElement(By.tagName("tBody"));
+ List grants = listContest.findElements(By.cssSelector("tr.tr"));
+ return grants;
+ }
+
+ public boolean checkPagination() {
+ try {
+ if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
+ driver.findElement(By.id("js-ctrlNext")).click();
+ return true;
+ }
+ } catch (NoSuchElementException e) {
+ return false;
+ }
+ return false;
+ }
+
+ public String getGrantTitle(WebElement grant) {
+ return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
+ }
+
+ public String getFirstDeadline(WebElement grant) {
+ return grant.findElement(By.xpath("./td[5]")).getText();
+ }
+}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
index efe1e41..fb236af 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
@@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
+import java.io.IOException;
+import java.text.ParseException;
+
@Service
public class GrantScheduler {
private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true;
@@ -31,22 +34,11 @@ public class GrantScheduler {
@Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started");
- //
- // Метод для сохранения загруженных грантов
- //
-
-// List grants = IndexKiasTest.getNewGrantsDto();
-// grants.forEach(grantDto -> {
-// try {
-// if (grantService.saveFromKias(grantDto)) {
-// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded");
-// } else {
-// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists");
-// }
-// } catch (IOException e) {
-// e.printStackTrace();
-// }
-// });
+ try {
+ grantService.createFromKias();
+ } catch (ParseException | IOException e) {
+ e.printStackTrace();
+ }
log.debug("GrantScheduler.loadGrantsFromKias finished");
}
}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java
index 38c16c3..8d65da7 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantService.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantService.java
@@ -1,6 +1,8 @@
package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
@@ -23,6 +25,7 @@ import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.io.IOException;
+import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
@@ -39,6 +42,7 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service
public class GrantService extends BaseService {
private final static int MAX_DISPLAY_SIZE = 50;
+ private final Logger log = LoggerFactory.getLogger(GrantService.class);
private final GrantRepository grantRepository;
private final ProjectService projectService;
@@ -48,6 +52,7 @@ public class GrantService extends BaseService {
private final PaperService paperService;
private final EventService eventService;
private final GrantNotificationService grantNotificationService;
+ private final KiasService kiasService;
public GrantService(GrantRepository grantRepository,
FileService fileService,
@@ -56,8 +61,10 @@ public class GrantService extends BaseService {
UserService userService,
PaperService paperService,
EventService eventService,
- GrantNotificationService grantNotificationService) {
+ GrantNotificationService grantNotificationService,
+ KiasService kiasService) {
this.grantRepository = grantRepository;
+ this.kiasService = kiasService;
this.baseRepository = grantRepository;
this.fileService = fileService;
this.deadlineService = deadlineService;
@@ -317,4 +324,15 @@ public class GrantService extends BaseService {
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList()));
}
+
+ @Transactional
+ public void createFromKias() throws IOException, ParseException {
+ for (GrantDto grantDto : kiasService.getNewGrantsDto()) {
+ if (saveFromKias(grantDto)) {
+ log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded");
+ } else {
+ log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists");
+ }
+ }
+ }
}
diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java
new file mode 100644
index 0000000..6ff0bd9
--- /dev/null
+++ b/src/main/java/ru/ulstu/grant/service/KiasService.java
@@ -0,0 +1,83 @@
+package ru.ulstu.grant.service;
+
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.openqa.selenium.chrome.ChromeDriver;
+import org.openqa.selenium.chrome.ChromeOptions;
+import org.springframework.stereotype.Service;
+import ru.ulstu.deadline.model.Deadline;
+import ru.ulstu.grant.model.Grant;
+import ru.ulstu.grant.model.GrantDto;
+import ru.ulstu.grant.page.KiasPage;
+import ru.ulstu.user.service.UserService;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+@Service
+public class KiasService {
+ private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
+ private final static String CONTEST_STATUS_ID = "1";
+ private final static String CONTEST_TYPE = "-1";
+ private final static int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR);
+
+ private final static String DRIVER_LOCATION = "drivers/%s";
+ private final static String WINDOWS_DRIVER = "chromedriver.exe";
+ private final static String LINUX_DRIVER = "chromedriver";
+ private final static String DRIVER_TYPE = "webdriver.chrome.driver";
+
+ private final UserService userService;
+ private WebDriver webDriver;
+
+ public KiasService(UserService userService) {
+ System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
+ this.userService = userService;
+ final ChromeOptions chromeOptions = new ChromeOptions();
+ chromeOptions.addArguments("--headless");
+ webDriver = new ChromeDriver(chromeOptions);
+ }
+
+ public List getNewGrantsDto() throws ParseException {
+ webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR));
+ KiasPage kiasPage = new KiasPage(webDriver);
+ List kiasGrants = new ArrayList<>();
+ List newGrants = new ArrayList<>();
+ do {
+ kiasGrants.addAll(kiasPage.getPageOfGrants());
+ for (WebElement grant : kiasGrants) {
+ GrantDto grantDto = new GrantDto();
+ grantDto.setTitle(kiasPage.getGrantTitle(grant));
+ String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59
+ SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
+ Date date = formatter.parse(deadlineDate);
+ Deadline deadline = new Deadline(date, "Окончание приёма заявок");
+ grantDto.setDeadlines(Arrays.asList(deadline));
+ grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId());
+ grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS);
+ newGrants.add(grantDto);
+ }
+ kiasGrants.clear();
+ }
+ while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
+
+ return newGrants;
+ }
+
+ private String getDriverExecutablePath() {
+ return KiasService.class.getClassLoader().getResource(
+ String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile();
+ }
+
+ private String getDriverExecutable(boolean isWindows) {
+ return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER;
+ }
+
+ private boolean isWindows() {
+ return System.getProperty("os.name").toLowerCase().contains("windows");
+ }
+}
diff --git a/src/main/java/ru/ulstu/user/service/UserService.java b/src/main/java/ru/ulstu/user/service/UserService.java
index c889caa..30eeb19 100644
--- a/src/main/java/ru/ulstu/user/service/UserService.java
+++ b/src/main/java/ru/ulstu/user/service/UserService.java
@@ -1,344 +1,349 @@
-package ru.ulstu.user.service;
-
-import com.google.common.collect.ImmutableMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.data.domain.Page;
-import org.springframework.data.domain.Sort;
-import org.springframework.mail.MailException;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
-import org.springframework.util.StringUtils;
-import ru.ulstu.configuration.ApplicationProperties;
-import ru.ulstu.core.error.EntityIdIsNullException;
-import ru.ulstu.core.jpa.OffsetablePageRequest;
-import ru.ulstu.core.model.BaseEntity;
-import ru.ulstu.core.model.response.PageableItems;
-import ru.ulstu.user.error.UserActivationError;
-import ru.ulstu.user.error.UserEmailExistsException;
-import ru.ulstu.user.error.UserIdExistsException;
-import ru.ulstu.user.error.UserIsUndeadException;
-import ru.ulstu.user.error.UserLoginExistsException;
-import ru.ulstu.user.error.UserNotActivatedException;
-import ru.ulstu.user.error.UserNotFoundException;
-import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
-import ru.ulstu.user.error.UserResetKeyError;
-import ru.ulstu.user.error.UserSendingMailException;
-import ru.ulstu.user.model.User;
-import ru.ulstu.user.model.UserDto;
-import ru.ulstu.user.model.UserListDto;
-import ru.ulstu.user.model.UserResetPasswordDto;
-import ru.ulstu.user.model.UserRole;
-import ru.ulstu.user.model.UserRoleConstants;
-import ru.ulstu.user.model.UserRoleDto;
-import ru.ulstu.user.repository.UserRepository;
-import ru.ulstu.user.repository.UserRoleRepository;
-import ru.ulstu.user.util.UserUtils;
-
-import javax.mail.MessagingException;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-@Service
-@Transactional
-public class UserService implements UserDetailsService {
- private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
-
- private final Logger log = LoggerFactory.getLogger(UserService.class);
- private final UserRepository userRepository;
- private final PasswordEncoder passwordEncoder;
- private final UserRoleRepository userRoleRepository;
- private final UserMapper userMapper;
- private final MailService mailService;
- private final ApplicationProperties applicationProperties;
-
- public UserService(UserRepository userRepository,
- PasswordEncoder passwordEncoder,
- UserRoleRepository userRoleRepository,
- UserMapper userMapper,
- MailService mailService,
- ApplicationProperties applicationProperties) {
- this.userRepository = userRepository;
- this.passwordEncoder = passwordEncoder;
- this.userRoleRepository = userRoleRepository;
- this.userMapper = userMapper;
- this.mailService = mailService;
- this.applicationProperties = applicationProperties;
- }
-
- private User getUserByEmail(String email) {
- return userRepository.findOneByEmailIgnoreCase(email);
- }
-
- private User getUserByActivationKey(String activationKey) {
- return userRepository.findOneByActivationKey(activationKey);
- }
-
- public User getUserByLogin(String login) {
- return userRepository.findOneByLoginIgnoreCase(login);
- }
-
- @Transactional(readOnly = true)
- public UserDto getUserWithRolesById(Integer userId) {
- final User userEntity = userRepository.findOneWithRolesById(userId);
- if (userEntity == null) {
- throw new UserNotFoundException(userId.toString());
- }
- return userMapper.userEntityToUserDto(userEntity);
- }
-
- @Transactional(readOnly = true)
- public PageableItems getAllUsers(int offset, int count) {
- final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
- return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
- }
-
- // TODO: read only active users
- public List findAll() {
- return userRepository.findAll();
- }
-
- @Transactional(readOnly = true)
- public PageableItems getUserRoles() {
- final List roles = userRoleRepository.findAll().stream()
- .map(UserRoleDto::new)
- .sorted(Comparator.comparing(UserRoleDto::getViewValue))
- .collect(Collectors.toList());
- return new PageableItems<>(roles.size(), roles);
- }
-
- public UserDto createUser(UserDto userDto) {
- if (userDto.getId() != null) {
- throw new UserIdExistsException();
- }
- if (getUserByLogin(userDto.getLogin()) != null) {
- throw new UserLoginExistsException(userDto.getLogin());
- }
- if (getUserByEmail(userDto.getEmail()) != null) {
- throw new UserEmailExistsException(userDto.getEmail());
- }
- if (!userDto.isPasswordsValid()) {
- throw new UserPasswordsNotValidOrNotMatchException("");
- }
- User user = userMapper.userDtoToUserEntity(userDto);
- user.setActivated(false);
- user.setActivationKey(UserUtils.generateActivationKey());
- user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
- user.setPassword(passwordEncoder.encode(userDto.getPassword()));
- user = userRepository.save(user);
- mailService.sendActivationEmail(user);
- log.debug("Created Information for User: {}", user.getLogin());
- return userMapper.userEntityToUserDto(user);
- }
-
- public UserDto activateUser(String activationKey) {
- final User user = getUserByActivationKey(activationKey);
- if (user == null) {
- throw new UserActivationError(activationKey);
- }
- user.setActivated(true);
- user.setActivationKey(null);
- user.setActivationDate(null);
- log.debug("Activated user: {}", user.getLogin());
- return userMapper.userEntityToUserDto(userRepository.save(user));
- }
-
- public UserDto updateUser(UserDto userDto) {
- if (userDto.getId() == null) {
- throw new EntityIdIsNullException();
- }
- if (!Objects.equals(
- Optional.ofNullable(getUserByEmail(userDto.getEmail()))
- .map(BaseEntity::getId).orElse(userDto.getId()),
- userDto.getId())) {
- throw new UserEmailExistsException(userDto.getEmail());
- }
- if (!Objects.equals(
- Optional.ofNullable(getUserByLogin(userDto.getLogin()))
- .map(BaseEntity::getId).orElse(userDto.getId()),
- userDto.getId())) {
- throw new UserLoginExistsException(userDto.getLogin());
- }
- User user = userRepository.findOne(userDto.getId());
- if (user == null) {
- throw new UserNotFoundException(userDto.getId().toString());
- }
- if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
- userDto.setLogin(applicationProperties.getUndeadUserLogin());
- userDto.setActivated(true);
- userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
- }
- user.setLogin(userDto.getLogin());
- user.setFirstName(userDto.getFirstName());
- user.setLastName(userDto.getLastName());
- user.setEmail(userDto.getEmail());
- if (userDto.isActivated() != user.getActivated()) {
- if (userDto.isActivated()) {
- user.setActivationKey(null);
- user.setActivationDate(null);
- } else {
- user.setActivationKey(UserUtils.generateActivationKey());
- user.setActivationDate(new Date());
- }
- }
- user.setActivated(userDto.isActivated());
- final Set roles = userMapper.rolesFromDto(userDto.getRoles());
- user.setRoles(roles.isEmpty()
- ? Collections.singleton(new UserRole(UserRoleConstants.USER))
- : roles);
- if (!StringUtils.isEmpty(userDto.getOldPassword())) {
- if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
- throw new UserPasswordsNotValidOrNotMatchException("");
- }
- if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
- throw new UserPasswordsNotValidOrNotMatchException("");
- }
- user.setPassword(passwordEncoder.encode(userDto.getPassword()));
- log.debug("Changed password for User: {}", user.getLogin());
- }
- user = userRepository.save(user);
- log.debug("Changed Information for User: {}", user.getLogin());
- return userMapper.userEntityToUserDto(user);
- }
-
- public UserDto updateUserInformation(User user, UserDto updateUser) {
- user.setFirstName(updateUser.getFirstName());
- user.setLastName(updateUser.getLastName());
- user.setEmail(updateUser.getEmail());
- user.setLogin(updateUser.getLogin());
- user = userRepository.save(user);
- log.debug("Updated Information for User: {}", user.getLogin());
- return userMapper.userEntityToUserDto(user);
- }
-
- public void changeUserPassword(User user, Map payload) {
- if (!payload.get("password").equals(payload.get("confirmPassword"))) {
- throw new UserPasswordsNotValidOrNotMatchException("");
- }
- if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
- throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
- }
- user.setPassword(passwordEncoder.encode(payload.get("password")));
- log.debug("Changed password for User: {}", user.getLogin());
- userRepository.save(user);
-
- mailService.sendChangePasswordMail(user);
- }
-
- public boolean requestUserPasswordReset(String email) {
- User user = userRepository.findOneByEmailIgnoreCase(email);
- if (user == null) {
- throw new UserNotFoundException(email);
- }
- if (!user.getActivated()) {
- throw new UserNotActivatedException();
- }
- user.setResetKey(UserUtils.generateResetKey());
- user.setResetDate(new Date());
- user = userRepository.save(user);
- mailService.sendPasswordResetMail(user);
- log.debug("Created Reset Password Request for User: {}", user.getLogin());
- return true;
- }
-
- public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) {
- if (!userResetPasswordDto.isPasswordsValid()) {
- throw new UserPasswordsNotValidOrNotMatchException("");
- }
- User user = userRepository.findOneByResetKey(key);
- if (user == null) {
- throw new UserResetKeyError(key);
- }
- user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
- user.setResetKey(null);
- user.setResetDate(null);
- user = userRepository.save(user);
- log.debug("Reset Password for User: {}", user.getLogin());
- return true;
- }
-
- public UserDto deleteUser(Integer userId) {
- final User user = userRepository.findOne(userId);
- if (user == null) {
- throw new UserNotFoundException(userId.toString());
- }
- if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
- throw new UserIsUndeadException(user.getLogin());
- }
- userRepository.delete(user);
- log.debug("Deleted User: {}", user.getLogin());
- return userMapper.userEntityToUserDto(user);
- }
-
- @Override
- public UserDetails loadUserByUsername(String username) {
- final User user = userRepository.findOneByLoginIgnoreCase(username);
- if (user == null) {
- throw new UserNotFoundException(username);
- }
- if (!user.getActivated()) {
- throw new UserNotActivatedException();
- }
- return new org.springframework.security.core.userdetails.User(user.getLogin(),
- user.getPassword(),
- Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
- .map(role -> new SimpleGrantedAuthority(role.getName()))
- .collect(Collectors.toList()));
- }
-
- public List findByIds(List ids) {
- return userRepository.findAll(ids);
- }
-
- public User findById(Integer id) {
- return userRepository.findOne(id);
- }
-
- public User getCurrentUser() {
- String login = UserUtils.getCurrentUserLogin();
- User user = userRepository.findOneByLoginIgnoreCase(login);
- if (user == null) {
- throw new UserNotFoundException(login);
- }
- return user;
- }
-
- public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
- return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
- }
-
- public void inviteUser(String email) throws UserSendingMailException {
- if (userRepository.findOneByEmailIgnoreCase(email) != null) {
- throw new UserEmailExistsException(email);
- }
-
- String password = UserUtils.generatePassword();
-
- User user = new User();
- user.setPassword(passwordEncoder.encode(password));
- user.setLogin(email);
- user.setEmail(email);
- user.setFirstName("user");
- user.setLastName("user");
- user.setActivated(true);
- userRepository.save(user);
-
- Map variables = ImmutableMap.of("password", password, "email", email);
- try {
- mailService.sendInviteMail(variables, email);
- } catch (MessagingException | MailException e) {
- throw new UserSendingMailException(email);
- }
- }
-}
+package ru.ulstu.user.service;
+
+import com.google.common.collect.ImmutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Sort;
+import org.springframework.mail.MailException;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+import ru.ulstu.configuration.ApplicationProperties;
+import ru.ulstu.core.error.EntityIdIsNullException;
+import ru.ulstu.core.jpa.OffsetablePageRequest;
+import ru.ulstu.core.model.BaseEntity;
+import ru.ulstu.core.model.response.PageableItems;
+import ru.ulstu.grant.model.GrantDto;
+import ru.ulstu.user.error.UserActivationError;
+import ru.ulstu.user.error.UserEmailExistsException;
+import ru.ulstu.user.error.UserIdExistsException;
+import ru.ulstu.user.error.UserIsUndeadException;
+import ru.ulstu.user.error.UserLoginExistsException;
+import ru.ulstu.user.error.UserNotActivatedException;
+import ru.ulstu.user.error.UserNotFoundException;
+import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
+import ru.ulstu.user.error.UserResetKeyError;
+import ru.ulstu.user.error.UserSendingMailException;
+import ru.ulstu.user.model.User;
+import ru.ulstu.user.model.UserDto;
+import ru.ulstu.user.model.UserListDto;
+import ru.ulstu.user.model.UserResetPasswordDto;
+import ru.ulstu.user.model.UserRole;
+import ru.ulstu.user.model.UserRoleConstants;
+import ru.ulstu.user.model.UserRoleDto;
+import ru.ulstu.user.repository.UserRepository;
+import ru.ulstu.user.repository.UserRoleRepository;
+import ru.ulstu.user.util.UserUtils;
+
+import javax.mail.MessagingException;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+@Service
+@Transactional
+public class UserService implements UserDetailsService {
+ private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
+
+ private final Logger log = LoggerFactory.getLogger(UserService.class);
+ private final UserRepository userRepository;
+ private final PasswordEncoder passwordEncoder;
+ private final UserRoleRepository userRoleRepository;
+ private final UserMapper userMapper;
+ private final MailService mailService;
+ private final ApplicationProperties applicationProperties;
+
+ public UserService(UserRepository userRepository,
+ PasswordEncoder passwordEncoder,
+ UserRoleRepository userRoleRepository,
+ UserMapper userMapper,
+ MailService mailService,
+ ApplicationProperties applicationProperties) {
+ this.userRepository = userRepository;
+ this.passwordEncoder = passwordEncoder;
+ this.userRoleRepository = userRoleRepository;
+ this.userMapper = userMapper;
+ this.mailService = mailService;
+ this.applicationProperties = applicationProperties;
+ }
+
+ private User getUserByEmail(String email) {
+ return userRepository.findOneByEmailIgnoreCase(email);
+ }
+
+ private User getUserByActivationKey(String activationKey) {
+ return userRepository.findOneByActivationKey(activationKey);
+ }
+
+ public User getUserByLogin(String login) {
+ return userRepository.findOneByLoginIgnoreCase(login);
+ }
+
+ @Transactional(readOnly = true)
+ public UserDto getUserWithRolesById(Integer userId) {
+ final User userEntity = userRepository.findOneWithRolesById(userId);
+ if (userEntity == null) {
+ throw new UserNotFoundException(userId.toString());
+ }
+ return userMapper.userEntityToUserDto(userEntity);
+ }
+
+ @Transactional(readOnly = true)
+ public PageableItems getAllUsers(int offset, int count) {
+ final Page page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
+ return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
+ }
+
+ // TODO: read only active users
+ public List findAll() {
+ return userRepository.findAll();
+ }
+
+ @Transactional(readOnly = true)
+ public PageableItems getUserRoles() {
+ final List roles = userRoleRepository.findAll().stream()
+ .map(UserRoleDto::new)
+ .sorted(Comparator.comparing(UserRoleDto::getViewValue))
+ .collect(Collectors.toList());
+ return new PageableItems<>(roles.size(), roles);
+ }
+
+ public UserDto createUser(UserDto userDto) {
+ if (userDto.getId() != null) {
+ throw new UserIdExistsException();
+ }
+ if (getUserByLogin(userDto.getLogin()) != null) {
+ throw new UserLoginExistsException(userDto.getLogin());
+ }
+ if (getUserByEmail(userDto.getEmail()) != null) {
+ throw new UserEmailExistsException(userDto.getEmail());
+ }
+ if (!userDto.isPasswordsValid()) {
+ throw new UserPasswordsNotValidOrNotMatchException("");
+ }
+ User user = userMapper.userDtoToUserEntity(userDto);
+ user.setActivated(false);
+ user.setActivationKey(UserUtils.generateActivationKey());
+ user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
+ user.setPassword(passwordEncoder.encode(userDto.getPassword()));
+ user = userRepository.save(user);
+ mailService.sendActivationEmail(user);
+ log.debug("Created Information for User: {}", user.getLogin());
+ return userMapper.userEntityToUserDto(user);
+ }
+
+ public UserDto activateUser(String activationKey) {
+ final User user = getUserByActivationKey(activationKey);
+ if (user == null) {
+ throw new UserActivationError(activationKey);
+ }
+ user.setActivated(true);
+ user.setActivationKey(null);
+ user.setActivationDate(null);
+ log.debug("Activated user: {}", user.getLogin());
+ return userMapper.userEntityToUserDto(userRepository.save(user));
+ }
+
+ public UserDto updateUser(UserDto userDto) {
+ if (userDto.getId() == null) {
+ throw new EntityIdIsNullException();
+ }
+ if (!Objects.equals(
+ Optional.ofNullable(getUserByEmail(userDto.getEmail()))
+ .map(BaseEntity::getId).orElse(userDto.getId()),
+ userDto.getId())) {
+ throw new UserEmailExistsException(userDto.getEmail());
+ }
+ if (!Objects.equals(
+ Optional.ofNullable(getUserByLogin(userDto.getLogin()))
+ .map(BaseEntity::getId).orElse(userDto.getId()),
+ userDto.getId())) {
+ throw new UserLoginExistsException(userDto.getLogin());
+ }
+ User user = userRepository.findOne(userDto.getId());
+ if (user == null) {
+ throw new UserNotFoundException(userDto.getId().toString());
+ }
+ if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
+ userDto.setLogin(applicationProperties.getUndeadUserLogin());
+ userDto.setActivated(true);
+ userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
+ }
+ user.setLogin(userDto.getLogin());
+ user.setFirstName(userDto.getFirstName());
+ user.setLastName(userDto.getLastName());
+ user.setEmail(userDto.getEmail());
+ if (userDto.isActivated() != user.getActivated()) {
+ if (userDto.isActivated()) {
+ user.setActivationKey(null);
+ user.setActivationDate(null);
+ } else {
+ user.setActivationKey(UserUtils.generateActivationKey());
+ user.setActivationDate(new Date());
+ }
+ }
+ user.setActivated(userDto.isActivated());
+ final Set roles = userMapper.rolesFromDto(userDto.getRoles());
+ user.setRoles(roles.isEmpty()
+ ? Collections.singleton(new UserRole(UserRoleConstants.USER))
+ : roles);
+ if (!StringUtils.isEmpty(userDto.getOldPassword())) {
+ if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
+ throw new UserPasswordsNotValidOrNotMatchException("");
+ }
+ if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
+ throw new UserPasswordsNotValidOrNotMatchException("");
+ }
+ user.setPassword(passwordEncoder.encode(userDto.getPassword()));
+ log.debug("Changed password for User: {}", user.getLogin());
+ }
+ user = userRepository.save(user);
+ log.debug("Changed Information for User: {}", user.getLogin());
+ return userMapper.userEntityToUserDto(user);
+ }
+
+ public UserDto updateUserInformation(User user, UserDto updateUser) {
+ user.setFirstName(updateUser.getFirstName());
+ user.setLastName(updateUser.getLastName());
+ user.setEmail(updateUser.getEmail());
+ user.setLogin(updateUser.getLogin());
+ user = userRepository.save(user);
+ log.debug("Updated Information for User: {}", user.getLogin());
+ return userMapper.userEntityToUserDto(user);
+ }
+
+ public void changeUserPassword(User user, Map payload) {
+ if (!payload.get("password").equals(payload.get("confirmPassword"))) {
+ throw new UserPasswordsNotValidOrNotMatchException("");
+ }
+ if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
+ throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
+ }
+ user.setPassword(passwordEncoder.encode(payload.get("password")));
+ log.debug("Changed password for User: {}", user.getLogin());
+ userRepository.save(user);
+
+ mailService.sendChangePasswordMail(user);
+ }
+
+ public boolean requestUserPasswordReset(String email) {
+ User user = userRepository.findOneByEmailIgnoreCase(email);
+ if (user == null) {
+ throw new UserNotFoundException(email);
+ }
+ if (!user.getActivated()) {
+ throw new UserNotActivatedException();
+ }
+ user.setResetKey(UserUtils.generateResetKey());
+ user.setResetDate(new Date());
+ user = userRepository.save(user);
+ mailService.sendPasswordResetMail(user);
+ log.debug("Created Reset Password Request for User: {}", user.getLogin());
+ return true;
+ }
+
+ public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) {
+ if (!userResetPasswordDto.isPasswordsValid()) {
+ throw new UserPasswordsNotValidOrNotMatchException("");
+ }
+ User user = userRepository.findOneByResetKey(key);
+ if (user == null) {
+ throw new UserResetKeyError(key);
+ }
+ user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
+ user.setResetKey(null);
+ user.setResetDate(null);
+ user = userRepository.save(user);
+ log.debug("Reset Password for User: {}", user.getLogin());
+ return true;
+ }
+
+ public UserDto deleteUser(Integer userId) {
+ final User user = userRepository.findOne(userId);
+ if (user == null) {
+ throw new UserNotFoundException(userId.toString());
+ }
+ if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
+ throw new UserIsUndeadException(user.getLogin());
+ }
+ userRepository.delete(user);
+ log.debug("Deleted User: {}", user.getLogin());
+ return userMapper.userEntityToUserDto(user);
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String username) {
+ final User user = userRepository.findOneByLoginIgnoreCase(username);
+ if (user == null) {
+ throw new UserNotFoundException(username);
+ }
+ if (!user.getActivated()) {
+ throw new UserNotActivatedException();
+ }
+ return new org.springframework.security.core.userdetails.User(user.getLogin(),
+ user.getPassword(),
+ Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
+ .map(role -> new SimpleGrantedAuthority(role.getName()))
+ .collect(Collectors.toList()));
+ }
+
+ public List findByIds(List ids) {
+ return userRepository.findAll(ids);
+ }
+
+ public User findById(Integer id) {
+ return userRepository.findOne(id);
+ }
+
+ public User getCurrentUser() {
+ String login = UserUtils.getCurrentUserLogin();
+ User user = userRepository.findOneByLoginIgnoreCase(login);
+ if (user == null) {
+ throw new UserNotFoundException(login);
+ }
+ return user;
+ }
+
+ public List filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
+ return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
+ }
+
+ public void inviteUser(String email) throws UserSendingMailException {
+ if (userRepository.findOneByEmailIgnoreCase(email) != null) {
+ throw new UserEmailExistsException(email);
+ }
+
+ String password = UserUtils.generatePassword();
+
+ User user = new User();
+ user.setPassword(passwordEncoder.encode(password));
+ user.setLogin(email);
+ user.setEmail(email);
+ user.setFirstName("user");
+ user.setLastName("user");
+ user.setActivated(true);
+ userRepository.save(user);
+
+ Map variables = ImmutableMap.of("password", password, "email", email);
+ try {
+ mailService.sendInviteMail(variables, email);
+ } catch (MessagingException | MailException e) {
+ throw new UserSendingMailException(email);
+ }
+ }
+
+ public User findOneByLoginIgnoreCase(String login) {
+ return userRepository.findOneByLoginIgnoreCase(login);
+ }
+}
diff --git a/src/main/resources/drivers/chromedriver b/src/main/resources/drivers/chromedriver
old mode 100644
new mode 100755
diff --git a/src/main/resources/drivers/geckodriver b/src/main/resources/drivers/geckodriver
old mode 100644
new mode 100755
From 82e454a50b8b209d0e0eb771e62ea3a864c0dbcc Mon Sep 17 00:00:00 2001
From: ASH
Date: Thu, 23 May 2019 16:17:04 +0400
Subject: [PATCH 53/68] #104 mod tests generate task
---
.../ulstu/students/service/TaskService.java | 4 ++-
.../students/service/TaskServiceTest.java | 26 ++++++++++++++++---
2 files changed, 26 insertions(+), 4 deletions(-)
diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java
index 379314d..d080d37 100644
--- a/src/main/java/ru/ulstu/students/service/TaskService.java
+++ b/src/main/java/ru/ulstu/students/service/TaskService.java
@@ -186,7 +186,7 @@ public class TaskService {
}
@Transactional
- public void generateYearTasks() {
+ public List generateYearTasks() {
Set tags = checkRepeatingTags(false);
List tasks = new ArrayList<>();
tags.forEach(tag -> {
@@ -202,7 +202,9 @@ public class TaskService {
Task newTask = copyTaskWithNewYear(task);
taskRepository.save(newTask);
});
+ return tasks;
}
+ return null;
}
diff --git a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
index 19eff12..1ba04c4 100644
--- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
+++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
@@ -21,6 +21,7 @@ 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;
@@ -157,16 +158,35 @@ public class TaskServiceTest {
@Test
public void generateYearTasks() {
- when(taskService.checkRepeatingTags(false)).thenReturn(repeatingTags);
+ 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.setDescription(deadline.getDescription());
+ newDeadline.setDate(DateUtils.addYears(deadline.getDate(), 1));
+ newTask.setDeadlines(Arrays.asList(newDeadline));
+
+ when(taskRepository.save(newTask)).thenReturn(task);
+
+ assertEquals(Arrays.asList(task), taskService.generateYearTasks());
}
@Test
public void checkRepeatingTags() {
- when(tagService.findById(ID)).thenReturn(tag);
+ when(tagService.getTags()).thenReturn(tags);
+ tasks.get(0).setTags(tags);
when(taskRepository.findAllYear(DateUtils.clearTime(DateUtils.addYears(new Date(), -1)))).thenReturn(tasks);
- assertEquals(tag, taskService.checkRepeatingTags(false));
+ assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false));
}
@Test
From 181086c9db9e7eb5683c520d4a89110d6561b38f Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Thu, 23 May 2019 16:36:48 +0400
Subject: [PATCH 54/68] #120 disable start browser on run application
---
src/main/java/ru/ulstu/grant/service/KiasService.java | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java
index 6ff0bd9..449b948 100644
--- a/src/main/java/ru/ulstu/grant/service/KiasService.java
+++ b/src/main/java/ru/ulstu/grant/service/KiasService.java
@@ -32,17 +32,16 @@ public class KiasService {
private final static String DRIVER_TYPE = "webdriver.chrome.driver";
private final UserService userService;
- private WebDriver webDriver;
public KiasService(UserService userService) {
- System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
this.userService = userService;
- final ChromeOptions chromeOptions = new ChromeOptions();
- chromeOptions.addArguments("--headless");
- webDriver = new ChromeDriver(chromeOptions);
}
public List getNewGrantsDto() throws ParseException {
+ System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
+ final ChromeOptions chromeOptions = new ChromeOptions();
+ chromeOptions.addArguments("--headless");
+ WebDriver webDriver = new ChromeDriver(chromeOptions);
webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR));
KiasPage kiasPage = new KiasPage(webDriver);
List kiasGrants = new ArrayList<>();
@@ -64,7 +63,7 @@ public class KiasService {
kiasGrants.clear();
}
while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
-
+ webDriver.quit();
return newGrants;
}
From ab17b9f1521e498d7bea148935e48cfa675f1b5e Mon Sep 17 00:00:00 2001
From: ASH
Date: Thu, 23 May 2019 16:45:09 +0400
Subject: [PATCH 55/68] #104 mod tests period task
---
.../ulstu/students/service/TaskService.java | 3 +-
.../students/service/TaskServiceTest.java | 47 +++++++++++--------
2 files changed, 30 insertions(+), 20 deletions(-)
diff --git a/src/main/java/ru/ulstu/students/service/TaskService.java b/src/main/java/ru/ulstu/students/service/TaskService.java
index d080d37..e89aedf 100644
--- a/src/main/java/ru/ulstu/students/service/TaskService.java
+++ b/src/main/java/ru/ulstu/students/service/TaskService.java
@@ -249,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/test/java/ru/ulstu/students/service/TaskServiceTest.java b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
index 1ba04c4..8edfc77 100644
--- a/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
+++ b/src/test/java/ru/ulstu/students/service/TaskServiceTest.java
@@ -10,6 +10,7 @@ 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;
@@ -26,7 +27,6 @@ import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
-import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@@ -64,14 +64,12 @@ public class TaskServiceTest {
private List tasks;
private List tags;
private Task task;
- private TaskFilterDto filterDto;
+ private Task taskForSchedule;
private TaskDto taskDto;
- private List tasksDto;
private Tag tag;
- private Tag tagNull;
private Deadline deadline;
private List deadlines;
- private Set repeatingTags;
+ private Scheduler scheduler;
@Before
@@ -102,8 +100,14 @@ public class TaskServiceTest {
tasks.add(task);
taskDto = new TaskDto(task);
- repeatingTags = new HashSet<>();
- repeatingTags.add(tag);
+ taskForSchedule = new Task();
+ taskForSchedule.setTitle(TITLE);
+ taskForSchedule.setDescription(DESCR);
+
+ scheduler = new Scheduler();
+ scheduler.setDate(new Date());
+ scheduler.setTask(taskForSchedule);
+
}
@@ -171,8 +175,10 @@ public class TaskServiceTest {
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);
@@ -189,19 +195,22 @@ public class TaskServiceTest {
assertEquals(new HashSet(Arrays.asList(tag)), taskService.checkRepeatingTags(false));
}
- @Test
- public void getTaskStatuses() {
- }
-
- @Test
- public void getTags() {
- }
-
- @Test
- public void findTasksByTag() {
- }
-
@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
From 512a805e8c4c4fa26cb58027ff2efc173e179c4a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Thu, 23 May 2019 17:26:22 +0400
Subject: [PATCH 56/68] #127 references formatting
---
.../paper/controller/PaperController.java | 5 +++
.../ru/ulstu/paper/service/PaperService.java | 11 +++++
src/main/resources/public/css/paper.css | 4 ++
src/main/resources/public/js/core.js | 1 +
.../resources/templates/papers/paper.html | 45 +++++++++++++++++++
5 files changed, 66 insertions(+)
diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java
index beae772..e10135f 100644
--- a/src/main/java/ru/ulstu/paper/controller/PaperController.java
+++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java
@@ -157,6 +157,11 @@ 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);
+ }
+
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/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java
index 8658015..8a59486 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -344,6 +344,17 @@ 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(),
diff --git a/src/main/resources/public/css/paper.css b/src/main/resources/public/css/paper.css
index 1be8c1f..386c5af 100644
--- a/src/main/resources/public/css/paper.css
+++ b/src/main/resources/public/css/paper.css
@@ -26,4 +26,8 @@
#nav-references a:hover {
text-decoration: none;
+}
+
+#nav-references #formattedReferencesArea {
+ height: 150px;
}
\ No newline at end of file
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/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html
index ef4217d..e80fe85 100644
--- a/src/main/resources/templates/papers/paper.html
+++ b/src/main/resources/templates/papers/paper.html
@@ -260,7 +260,33 @@
class="btn btn-primary"
value="Добавить источник"/>
+
@@ -474,6 +500,25 @@
$('#pdfBtn').prop('disabled', false);
}
}
+
+ 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);
+ }
+ }
+ }
From 24a1276005ecaac2d95bd0ca20ad5eddd353c778 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Fri, 24 May 2019 00:14:46 +0400
Subject: [PATCH 57/68] #127 autocomplete
---
.../paper/controller/PaperController.java | 6 +
.../ulstu/paper/model/AutoCompleteData.java | 42 ++++++
.../paper/repository/ReferenceRepository.java | 15 ++
.../ru/ulstu/paper/service/PaperService.java | 10 ++
src/main/resources/public/css/paper.css | 7 +
.../resources/templates/papers/paper.html | 139 ++++++++++++------
6 files changed, 172 insertions(+), 47 deletions(-)
create mode 100644 src/main/java/ru/ulstu/paper/model/AutoCompleteData.java
diff --git a/src/main/java/ru/ulstu/paper/controller/PaperController.java b/src/main/java/ru/ulstu/paper/controller/PaperController.java
index e10135f..29da57d 100644
--- a/src/main/java/ru/ulstu/paper/controller/PaperController.java
+++ b/src/main/java/ru/ulstu/paper/controller/PaperController.java
@@ -13,6 +13,7 @@ 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;
@@ -162,6 +163,11 @@ public class PaperController {
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..b70a780
--- /dev/null
+++ b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java
@@ -0,0 +1,42 @@
+package ru.ulstu.paper.model;
+
+import java.util.ArrayList;
+
+public class AutoCompleteData {
+ ArrayList authors = new ArrayList<>();
+ ArrayList publicationTitles = new ArrayList<>();
+ ArrayList publishers = new ArrayList<>();
+ ArrayList journalOrCollectionTitles = new ArrayList<>();
+
+ public ArrayList getAuthors() {
+ return authors;
+ }
+
+ public void setAuthors(ArrayList authors) {
+ this.authors = authors;
+ }
+
+ public ArrayList getPublicationTitles() {
+ return publicationTitles;
+ }
+
+ public void setPublicationTitles(ArrayList publicationTitles) {
+ this.publicationTitles = publicationTitles;
+ }
+
+ public ArrayList getPublishers() {
+ return publishers;
+ }
+
+ public void setPublishers(ArrayList publishers) {
+ this.publishers = publishers;
+ }
+
+ public ArrayList getJournalOrCollectionTitles() {
+ return journalOrCollectionTitles;
+ }
+
+ public void setJournalOrCollectionTitles(ArrayList journalOrCollectionTitles) {
+ this.journalOrCollectionTitles = journalOrCollectionTitles;
+ }
+}
diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
index 68e97d4..1d4321b 100644
--- a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
+++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
@@ -1,8 +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.ArrayList;
+
public interface ReferenceRepository extends JpaRepository {
void deleteById(Integer id);
+
+ @Query("SELECT DISTINCT r.authors FROM Reference r")
+ ArrayList findDistinctAuthors();
+
+ @Query("SELECT DISTINCT r.publicationTitle FROM Reference r")
+ ArrayList findDistinctPublicationTitles();
+
+ @Query("SELECT DISTINCT r.publisher FROM Reference r")
+ ArrayList findDistinctPublishers();
+
+ @Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''")
+ ArrayList findDistinctJournalOrCollectionTitles();
}
diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java
index 8a59486..f452c2f 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -7,6 +7,7 @@ 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;
@@ -378,4 +379,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/resources/public/css/paper.css b/src/main/resources/public/css/paper.css
index 386c5af..b4b3f85 100644
--- a/src/main/resources/public/css/paper.css
+++ b/src/main/resources/public/css/paper.css
@@ -30,4 +30,11 @@
#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/templates/papers/paper.html b/src/main/resources/templates/papers/paper.html
index e80fe85..2755aba 100644
--- a/src/main/resources/templates/papers/paper.html
+++ b/src/main/resources/templates/papers/paper.html
@@ -4,6 +4,10 @@
layout:decorator="default" xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">
+
+
+
+
@@ -74,54 +78,56 @@
th:field="*{comment}">
-
- Ссылка на сайт конференции:
-
-
+
+ Ссылка на сайт конференции:
+
+
-
-
-
+
-
-
+
+
@@ -519,6 +525,45 @@
}
}
}
+
+
+
From 01bcac2680f4b0e64e5fd69b03d3679d7c0bd759 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Fri, 24 May 2019 00:26:38 +0400
Subject: [PATCH 58/68] #127 allow nullable year
---
src/main/java/ru/ulstu/paper/service/PaperService.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/ru/ulstu/paper/service/PaperService.java b/src/main/java/ru/ulstu/paper/service/PaperService.java
index f452c2f..cfb1a0a 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -361,7 +361,7 @@ public class PaperService {
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() + ".");
}
@@ -369,7 +369,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() + ", ",
From 8bb9e3a84469d2ff8529a463459f91497cf9600a Mon Sep 17 00:00:00 2001
From: "Artem.Arefev"
Date: Fri, 24 May 2019 01:52:50 +0400
Subject: [PATCH 59/68] #89 jquery
---
src/main/resources/public/js/users.js | 38 +++++++++----------
.../resources/templates/resetRequest.html | 12 +++---
2 files changed, 25 insertions(+), 25 deletions(-)
diff --git a/src/main/resources/public/js/users.js b/src/main/resources/public/js/users.js
index 1ea26e3..e31d3ad 100644
--- a/src/main/resources/public/js/users.js
+++ b/src/main/resources/public/js/users.js
@@ -1,7 +1,7 @@
function changePassword() {
- oldPassword = document.getElementById("oldPassword").value
- password = document.getElementById("password").value
- confirmPassword = document.getElementById("confirmPassword").value
+ oldPassword = $("#oldPassword").val()
+ password = $("#password").val()
+ confirmPassword = $("#confirmPassword").val()
if ([oldPassword.length, password.length, confirmPassword.length].includes(0)) {
showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING);
@@ -23,7 +23,7 @@ function changePassword() {
}),
method: "POST",
success: function() {
- document.getElementById("closeModalPassword").click();
+ $("#closeModalPassword").click();
showFeedbackMessage("Пароль был обновлен", MessageTypesEnum.SUCCESS)
},
@@ -34,7 +34,7 @@ function changePassword() {
}
function inviteUser() {
- email = document.getElementById("email").value;
+ email = $("#email").val();
if (!isEmailValid(email)) {
showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING);
return;
@@ -45,7 +45,7 @@ function inviteUser() {
contentType: "application/json; charset=utf-8",
method: "POST",
success: function() {
- document.getElementById("closeModalInvite").click();
+ $("#closeModalInvite").click();
showFeedbackMessage("Пользователь был успешно приглашен", MessageTypesEnum.SUCCESS)
},
error: function(errorData) {
@@ -55,13 +55,13 @@ function inviteUser() {
}
function requestResetPassword() {
- email = document.getElementById("emailReset").value
+ email = $("#emailReset").val()
if (!isEmailValid(email)) {
showFeedbackMessage("Некорректный почтовый ящик", MessageTypesEnum.WARNING);
return;
}
- document.getElementById("dvloader").hidden = false;
+ $("#dvloader").show();
$.ajax({
url:"/api/1.0/users/password-reset-request?email=" + email,
@@ -69,27 +69,27 @@ function requestResetPassword() {
method: "POST",
success: function() {
showFeedbackMessage("Проверочный код был отправлен на указанный почтовый ящик", MessageTypesEnum.SUCCESS)
- document.getElementById("passwordNew").hidden = false
- document.getElementById("passwordConfirm").hidden = false
- document.getElementById("btnReset").hidden = false
- document.getElementById("resetKey").hidden = false
- document.getElementById("emailReset").hidden = true
- document.getElementById("btnSend").hidden = true
- document.getElementById("dvloader").hidden = true;
+ $("#passwordNew").show()
+ $("#passwordConfirm").show()
+ $("#btnReset").show()
+ $("#resetKey").show()
+ $("#emailReset").hide()
+ $("#btnSend").hide()
+ $("#dvloader").hide()
},
error: function(errorData) {
showFeedbackMessage(errorData.responseJSON.error.message, MessageTypesEnum.WARNING)
- document.getElementById("dvloader").hidden = true;
+ $("#dvloader").hide()
}
})
}
function resetPassword() {
- passwordNew = document.getElementById("passwordNew").value;
- passwordConfirm = document.getElementById("passwordConfirm").value;
- resetKey = document.getElementById("resetKey").value;
+ passwordNew = $("#passwordNew").val();
+ passwordConfirm = $("#passwordConfirm").val();
+ resetKey = $("#resetKey").val();
if ([passwordNew, passwordConfirm, resetKey].includes("")) {
showFeedbackMessage("Заполните все поля", MessageTypesEnum.WARNING);
diff --git a/src/main/resources/templates/resetRequest.html b/src/main/resources/templates/resetRequest.html
index 73bff76..4a2aeab 100644
--- a/src/main/resources/templates/resetRequest.html
+++ b/src/main/resources/templates/resetRequest.html
@@ -10,7 +10,7 @@
@@ -25,22 +25,22 @@
+ placeholder="Новый пароль" style="display:none"/>
+ placeholder="Подтвердите пароль" style="display:none"/>
+ placeholder="Код подтверждения" style="display:none"/>
-
+
Отправить код подтверждения
-
Сбросить
пароль
From 22195813aed9d14e7e7114b723f07be04dbbbbbd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=A1=D0=B5=D0=BC=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=20=D0=9C?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D1=8F?=
Date: Fri, 24 May 2019 16:15:38 +0400
Subject: [PATCH 60/68] #127 fixes
---
.../ulstu/paper/model/AutoCompleteData.java | 25 +++++++++---------
.../paper/repository/ReferenceRepository.java | 10 +++----
.../ru/ulstu/paper/service/PaperService.java | 26 +++++++++----------
3 files changed, 30 insertions(+), 31 deletions(-)
diff --git a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java
index b70a780..91c3bf4 100644
--- a/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java
+++ b/src/main/java/ru/ulstu/paper/model/AutoCompleteData.java
@@ -1,42 +1,43 @@
package ru.ulstu.paper.model;
import java.util.ArrayList;
+import java.util.List;
public class AutoCompleteData {
- ArrayList authors = new ArrayList<>();
- ArrayList publicationTitles = new ArrayList<>();
- ArrayList publishers = new ArrayList<>();
- ArrayList journalOrCollectionTitles = new ArrayList<>();
+ private List authors = new ArrayList<>();
+ private List publicationTitles = new ArrayList<>();
+ private List publishers = new ArrayList<>();
+ private List journalOrCollectionTitles = new ArrayList<>();
- public ArrayList getAuthors() {
+ public List getAuthors() {
return authors;
}
- public void setAuthors(ArrayList authors) {
+ public void setAuthors(List authors) {
this.authors = authors;
}
- public ArrayList getPublicationTitles() {
+ public List getPublicationTitles() {
return publicationTitles;
}
- public void setPublicationTitles(ArrayList publicationTitles) {
+ public void setPublicationTitles(List publicationTitles) {
this.publicationTitles = publicationTitles;
}
- public ArrayList getPublishers() {
+ public List getPublishers() {
return publishers;
}
- public void setPublishers(ArrayList publishers) {
+ public void setPublishers(List publishers) {
this.publishers = publishers;
}
- public ArrayList getJournalOrCollectionTitles() {
+ public List getJournalOrCollectionTitles() {
return journalOrCollectionTitles;
}
- public void setJournalOrCollectionTitles(ArrayList journalOrCollectionTitles) {
+ public void setJournalOrCollectionTitles(List journalOrCollectionTitles) {
this.journalOrCollectionTitles = journalOrCollectionTitles;
}
}
diff --git a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
index 1d4321b..942a5b8 100644
--- a/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
+++ b/src/main/java/ru/ulstu/paper/repository/ReferenceRepository.java
@@ -4,20 +4,20 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.paper.model.Reference;
-import java.util.ArrayList;
+import java.util.List;
public interface ReferenceRepository extends JpaRepository {
void deleteById(Integer id);
@Query("SELECT DISTINCT r.authors FROM Reference r")
- ArrayList findDistinctAuthors();
+ List findDistinctAuthors();
@Query("SELECT DISTINCT r.publicationTitle FROM Reference r")
- ArrayList findDistinctPublicationTitles();
+ List findDistinctPublicationTitles();
@Query("SELECT DISTINCT r.publisher FROM Reference r")
- ArrayList findDistinctPublishers();
+ List findDistinctPublishers();
@Query("SELECT DISTINCT r.journalOrCollectionTitle FROM Reference r where r.journalOrCollectionTitle <> ''")
- ArrayList findDistinctJournalOrCollectionTitles();
+ 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 cfb1a0a..2393af4 100644
--- a/src/main/java/ru/ulstu/paper/service/PaperService.java
+++ b/src/main/java/ru/ulstu/paper/service/PaperService.java
@@ -146,13 +146,7 @@ public class PaperService {
@Transactional
public Reference updateReference(ReferenceDto referenceDto) {
Reference updateReference = referenceRepository.findOne(referenceDto.getId());
- updateReference.setAuthors(referenceDto.getAuthors());
- updateReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle());
- updateReference.setPages(referenceDto.getPages());
- updateReference.setPublicationTitle(referenceDto.getPublicationTitle());
- updateReference.setPublicationYear(referenceDto.getPublicationYear());
- updateReference.setPublisher(referenceDto.getPublisher());
- updateReference.setReferenceType(referenceDto.getReferenceType());
+ copyFromDto(updateReference, referenceDto);
referenceRepository.save(updateReference);
return updateReference;
}
@@ -160,17 +154,21 @@ public class PaperService {
@Transactional
public Reference createReference(ReferenceDto referenceDto) {
Reference newReference = new Reference();
- newReference.setAuthors(referenceDto.getAuthors());
- newReference.setJournalOrCollectionTitle(referenceDto.getJournalOrCollectionTitle());
- newReference.setPages(referenceDto.getPages());
- newReference.setPublicationTitle(referenceDto.getPublicationTitle());
- newReference.setPublicationYear(referenceDto.getPublicationYear());
- newReference.setPublisher(referenceDto.getPublisher());
- newReference.setReferenceType(referenceDto.getReferenceType());
+ 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 {
From 59d6edb818c766e4f70776a0cf19de60119b84f2 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 15:42:08 +0400
Subject: [PATCH 61/68] #120 refactor
---
.../java/ru/ulstu/grant/model/GrantDto.java | 7 +++
.../java/ru/ulstu/grant/page/KiasPage.java | 54 ++++++++++++------
.../ru/ulstu/grant/service/KiasService.java | 49 +++++++---------
src/test/java/IndexKiasTest.java | 56 -------------------
src/test/java/grant/KiasPage.java | 41 --------------
5 files changed, 63 insertions(+), 144 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/model/GrantDto.java b/src/main/java/ru/ulstu/grant/model/GrantDto.java
index 5a561b1..9e59d86 100644
--- a/src/main/java/ru/ulstu/grant/model/GrantDto.java
+++ b/src/main/java/ru/ulstu/grant/model/GrantDto.java
@@ -12,6 +12,7 @@ import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.user.model.UserDto;
import java.util.ArrayList;
+import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -96,6 +97,12 @@ public class GrantDto extends NameContainer {
this.papers = convert(grant.getPapers(), PaperDto::new);
}
+ public GrantDto(String grantTitle, Date deadLineDate) {
+ this.title = grantTitle;
+ deadlines.add(new Deadline(deadLineDate, "Окончание приёма заявок"));
+ status = Grant.GrantStatus.LOADED_FROM_KIAS;
+ }
+
public Integer getId() {
return id;
}
diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java
index 4353684..8a6e444 100644
--- a/src/main/java/ru/ulstu/grant/page/KiasPage.java
+++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java
@@ -3,34 +3,31 @@ package ru.ulstu.grant.page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
+import ru.ulstu.grant.model.GrantDto;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
import java.util.ArrayList;
+import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
public class KiasPage {
private WebDriver driver;
+
public KiasPage(WebDriver webDriver) {
this.driver = webDriver;
}
- public List getGrants() {
- List grants = new ArrayList<>();
+ public List getKiasGrants() throws ParseException {
+ List newGrants = new ArrayList<>();
do {
- grants.addAll(getPageOfGrants());
- }
- while (checkPagination());
-
- return grants;
+ newGrants.addAll(getGrantsFromPage());
+ } while (goToNextPage()); //проверка существования следующей страницы с грантами
+ return newGrants;
}
- public List getPageOfGrants() {
- WebElement listContest = driver.findElement(By.tagName("tBody"));
- List grants = listContest.findElements(By.cssSelector("tr.tr"));
- return grants;
- }
-
- public boolean checkPagination() {
+ private boolean goToNextPage() {
try {
if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
driver.findElement(By.id("js-ctrlNext")).click();
@@ -42,11 +39,34 @@ public class KiasPage {
return false;
}
- public String getGrantTitle(WebElement grant) {
+ private List getPageOfGrants() {
+ WebElement listContest = driver.findElement(By.tagName("tBody"));
+ List grants = listContest.findElements(By.cssSelector("tr.tr"));
+ return grants;
+ }
+
+ private String getGrantTitle(WebElement grant) {
return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
}
- public String getFirstDeadline(WebElement grant) {
- return grant.findElement(By.xpath("./td[5]")).getText();
+ private List getGrantsFromPage() throws ParseException {
+ List grants = new ArrayList<>();
+ for (WebElement grantElement : getPageOfGrants()) {
+ GrantDto grantDto = new GrantDto(
+ getGrantTitle(grantElement),
+ parseDeadLineDate(grantElement));
+ grants.add(grantDto);
+ }
+ return grants;
+ }
+
+ private Date parseDeadLineDate(WebElement grantElement) throws ParseException {
+ String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59
+ SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
+ return formatter.parse(deadlineDate);
+ }
+
+ private String getFirstDeadline(WebElement grantElement) {
+ return grantElement.findElement(By.xpath("./td[5]")).getText();
}
}
diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java
index 449b948..6881292 100644
--- a/src/main/java/ru/ulstu/grant/service/KiasService.java
+++ b/src/main/java/ru/ulstu/grant/service/KiasService.java
@@ -1,22 +1,17 @@
package ru.ulstu.grant.service;
import org.openqa.selenium.WebDriver;
-import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;
-import ru.ulstu.deadline.model.Deadline;
-import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.page.KiasPage;
import ru.ulstu.user.service.UserService;
import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
-import java.util.Date;
import java.util.List;
@Service
@@ -24,7 +19,6 @@ public class KiasService {
private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
private final static String CONTEST_STATUS_ID = "1";
private final static String CONTEST_TYPE = "-1";
- private final static int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR);
private final static String DRIVER_LOCATION = "drivers/%s";
private final static String WINDOWS_DRIVER = "chromedriver.exe";
@@ -38,33 +32,28 @@ public class KiasService {
}
public List getNewGrantsDto() throws ParseException {
+ WebDriver webDriver = getDriver();
+ Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId();
+ List grants = new ArrayList<>();
+ for (Integer year : generateGrantYears()) {
+ webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year));
+ grants.addAll(new KiasPage(webDriver).getKiasGrants());
+ }
+ grants.forEach(grantDto -> grantDto.setLeaderId(leaderId));
+ webDriver.quit();
+ return grants;
+ }
+
+ private List generateGrantYears() {
+ return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR),
+ Calendar.getInstance().get(Calendar.YEAR) + 1);
+ }
+
+ private WebDriver getDriver() {
System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
- WebDriver webDriver = new ChromeDriver(chromeOptions);
- webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR));
- KiasPage kiasPage = new KiasPage(webDriver);
- List kiasGrants = new ArrayList<>();
- List newGrants = new ArrayList<>();
- do {
- kiasGrants.addAll(kiasPage.getPageOfGrants());
- for (WebElement grant : kiasGrants) {
- GrantDto grantDto = new GrantDto();
- grantDto.setTitle(kiasPage.getGrantTitle(grant));
- String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59
- SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
- Date date = formatter.parse(deadlineDate);
- Deadline deadline = new Deadline(date, "Окончание приёма заявок");
- grantDto.setDeadlines(Arrays.asList(deadline));
- grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId());
- grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS);
- newGrants.add(grantDto);
- }
- kiasGrants.clear();
- }
- while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
- webDriver.quit();
- return newGrants;
+ return new ChromeDriver(chromeOptions);
}
private String getDriverExecutablePath() {
diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java
index 73dc646..8228e76 100644
--- a/src/test/java/IndexKiasTest.java
+++ b/src/test/java/IndexKiasTest.java
@@ -1,67 +1,11 @@
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import core.PageObject;
import core.TestTemplate;
-import grant.KiasPage;
import org.junit.runner.RunWith;
-import org.openqa.selenium.WebElement;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import ru.ulstu.NgTrackerApplication;
-import ru.ulstu.deadline.model.Deadline;
-import ru.ulstu.grant.model.Grant;
-import ru.ulstu.grant.model.GrantDto;
-import ru.ulstu.user.repository.UserRepository;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class IndexKiasTest extends TestTemplate {
- private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
- private final static String CONTEST_STATUS_ID = "1";
- private final static String CONTEST_TYPE = "-1";
- private final static String CONTEST_YEAR = "2019";
- private final Map> navigationHolder = ImmutableMap.of(
- new KiasPage(), Arrays.asList("Поиск по конкурсам",
- String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR))
- );
-
- @Autowired
- UserRepository userRepository;
-
- public List getNewGrantsDto() throws ParseException {
- Map.Entry> page = Iterables.get(navigationHolder.entrySet(), 0);
- getContext().goTo(page.getValue().get(1));
- KiasPage kiasPage = (KiasPage) getContext().initPage(page.getKey());
- List kiasGrants = new ArrayList<>();
- List newGrants = new ArrayList<>();
- do {
- kiasGrants.addAll(kiasPage.getPageOfGrants());
- for (WebElement grant : kiasGrants) {
- GrantDto grantDto = new GrantDto();
- grantDto.setTitle(kiasPage.getGrantTitle(grant));
- String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59
- SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
- Date date = formatter.parse(deadlineDate);
- Deadline deadline = new Deadline(date, "Окончание приёма заявок");
- grantDto.setDeadlines(Arrays.asList(deadline));
- grantDto.setLeaderId(userRepository.findOneByLoginIgnoreCase("admin").getId());
- grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS);
- newGrants.add(grantDto);
- }
- kiasGrants.clear();
- }
- while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
-
- return newGrants;
- }
}
diff --git a/src/test/java/grant/KiasPage.java b/src/test/java/grant/KiasPage.java
index 7723b01..5864511 100644
--- a/src/test/java/grant/KiasPage.java
+++ b/src/test/java/grant/KiasPage.java
@@ -2,51 +2,10 @@ package grant;
import core.PageObject;
import org.openqa.selenium.By;
-import org.openqa.selenium.WebElement;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.NoSuchElementException;
public class KiasPage extends PageObject {
@Override
public String getSubTitle() {
return driver.findElement(By.tagName("h1")).getText();
}
-
- public List getGrants() {
- List grants = new ArrayList<>();
- do {
- grants.addAll(getPageOfGrants());
- }
- while (checkPagination());
-
- return grants;
- }
-
- public List getPageOfGrants() {
- WebElement listContest = driver.findElement(By.tagName("tBody"));
- List grants = listContest.findElements(By.cssSelector("tr.tr"));
- return grants;
- }
-
- public boolean checkPagination() {
- try {
- if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
- driver.findElement(By.id("js-ctrlNext")).click();
- return true;
- }
- } catch (NoSuchElementException e) {
- return false;
- }
- return false;
- }
-
- public String getGrantTitle(WebElement grant) {
- return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
- }
-
- public String getFirstDeadline(WebElement grant) {
- return grant.findElement(By.xpath("./td[5]")).getText();
- }
}
From 477a9fd6ffbff5d4128d31f298cc1212a4f0cc0b Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 15:48:32 +0400
Subject: [PATCH 62/68] #120 move to service
---
.../java/ru/ulstu/grant/page/KiasPage.java | 29 +++----------------
.../ru/ulstu/grant/service/KiasService.java | 23 ++++++++++++++-
2 files changed, 26 insertions(+), 26 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java
index 8a6e444..ea9bdb4 100644
--- a/src/main/java/ru/ulstu/grant/page/KiasPage.java
+++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java
@@ -3,11 +3,9 @@ package ru.ulstu.grant.page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
-import ru.ulstu.grant.model.GrantDto;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
@@ -19,15 +17,7 @@ public class KiasPage {
this.driver = webDriver;
}
- public List getKiasGrants() throws ParseException {
- List newGrants = new ArrayList<>();
- do {
- newGrants.addAll(getGrantsFromPage());
- } while (goToNextPage()); //проверка существования следующей страницы с грантами
- return newGrants;
- }
-
- private boolean goToNextPage() {
+ public boolean goToNextPage() {
try {
if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
driver.findElement(By.id("js-ctrlNext")).click();
@@ -39,28 +29,17 @@ public class KiasPage {
return false;
}
- private List getPageOfGrants() {
+ public List getPageOfGrants() {
WebElement listContest = driver.findElement(By.tagName("tBody"));
List grants = listContest.findElements(By.cssSelector("tr.tr"));
return grants;
}
- private String getGrantTitle(WebElement grant) {
+ public String getGrantTitle(WebElement grant) {
return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
}
- private List getGrantsFromPage() throws ParseException {
- List grants = new ArrayList<>();
- for (WebElement grantElement : getPageOfGrants()) {
- GrantDto grantDto = new GrantDto(
- getGrantTitle(grantElement),
- parseDeadLineDate(grantElement));
- grants.add(grantDto);
- }
- return grants;
- }
-
- private Date parseDeadLineDate(WebElement grantElement) throws ParseException {
+ public Date parseDeadLineDate(WebElement grantElement) throws ParseException {
String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
return formatter.parse(deadlineDate);
diff --git a/src/main/java/ru/ulstu/grant/service/KiasService.java b/src/main/java/ru/ulstu/grant/service/KiasService.java
index 6881292..618e83c 100644
--- a/src/main/java/ru/ulstu/grant/service/KiasService.java
+++ b/src/main/java/ru/ulstu/grant/service/KiasService.java
@@ -1,6 +1,7 @@
package ru.ulstu.grant.service;
import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;
@@ -37,13 +38,33 @@ public class KiasService {
List grants = new ArrayList<>();
for (Integer year : generateGrantYears()) {
webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year));
- grants.addAll(new KiasPage(webDriver).getKiasGrants());
+ grants.addAll(getKiasGrants(webDriver));
}
grants.forEach(grantDto -> grantDto.setLeaderId(leaderId));
webDriver.quit();
return grants;
}
+ public List getKiasGrants(WebDriver webDriver) throws ParseException {
+ List newGrants = new ArrayList<>();
+ KiasPage kiasPage = new KiasPage(webDriver);
+ do {
+ newGrants.addAll(getGrantsFromPage(kiasPage));
+ } while (kiasPage.goToNextPage()); //проверка существования следующей страницы с грантами
+ return newGrants;
+ }
+
+ private List getGrantsFromPage(KiasPage kiasPage) throws ParseException {
+ List grants = new ArrayList<>();
+ for (WebElement grantElement : kiasPage.getPageOfGrants()) {
+ GrantDto grantDto = new GrantDto(
+ kiasPage.getGrantTitle(grantElement),
+ kiasPage.parseDeadLineDate(grantElement));
+ grants.add(grantDto);
+ }
+ return grants;
+ }
+
private List generateGrantYears() {
return Arrays.asList(Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.YEAR) + 1);
From 916bbae41494d0420a4aaede0c633d3730ca4806 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 21:15:21 +0400
Subject: [PATCH 63/68] #120 add debug email
---
.../ulstu/configuration/ApplicationProperties.java | 10 ++++++++++
.../java/ru/ulstu/user/service/MailService.java | 13 ++++++++++---
src/main/resources/application.properties | 1 +
3 files changed, 21 insertions(+), 3 deletions(-)
diff --git a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
index f75f53f..49efac4 100644
--- a/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
+++ b/src/main/java/ru/ulstu/configuration/ApplicationProperties.java
@@ -21,6 +21,8 @@ public class ApplicationProperties {
private boolean checkRun;
+ private String debugEmail;
+
public boolean isUseHttps() {
return useHttps;
}
@@ -60,4 +62,12 @@ public class ApplicationProperties {
public void setCheckRun(boolean checkRun) {
this.checkRun = checkRun;
}
+
+ public String getDebugEmail() {
+ return debugEmail;
+ }
+
+ public void setDebugEmail(String debugEmail) {
+ this.debugEmail = debugEmail;
+ }
}
diff --git a/src/main/java/ru/ulstu/user/service/MailService.java b/src/main/java/ru/ulstu/user/service/MailService.java
index 864b749..3724792 100644
--- a/src/main/java/ru/ulstu/user/service/MailService.java
+++ b/src/main/java/ru/ulstu/user/service/MailService.java
@@ -1,5 +1,6 @@
package ru.ulstu.user.service;
+import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
@@ -21,11 +22,9 @@ import java.util.Map;
@Service
public class MailService {
- private final Logger log = LoggerFactory.getLogger(MailService.class);
-
private static final String USER = "user";
private static final String BASE_URL = "baseUrl";
-
+ private final Logger log = LoggerFactory.getLogger(MailService.class);
private final JavaMailSender javaMailSender;
private final SpringTemplateEngine templateEngine;
private final MailProperties mailProperties;
@@ -48,10 +47,18 @@ public class MailService {
message.setFrom(mailProperties.getUsername());
message.setSubject(subject);
message.setText(content, true);
+ modifyForDebug(message, subject);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
}
+ private void modifyForDebug(MimeMessageHelper message, String originalSubject) throws MessagingException {
+ if (!StringUtils.isEmpty(applicationProperties.getDebugEmail())) {
+ message.setTo(applicationProperties.getDebugEmail());
+ message.setSubject("To " + applicationProperties.getDebugEmail() + "; " + originalSubject);
+ }
+ }
+
@Async
public void sendEmailFromTemplate(User user, String templateName, String subject) {
Context context = new Context();
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index 038ddcf..cdd7569 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -35,5 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml
ng-tracker.base-url=http://127.0.0.1:8080
ng-tracker.undead-user-login=admin
ng-tracker.dev-mode=true
+ng-tracker.debug_email=romanov73@gmail.com
ng-tracker.use-https=false
ng-tracker.check-run=false
\ No newline at end of file
From 678397e970099cb6c655cc3ece6f43c3a47abf30 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 21:15:54 +0400
Subject: [PATCH 64/68] #120 test classes refactor
---
.../{IndexConferenceTest.java => ConferenceTest.java} | 2 +-
src/test/java/IndexKiasTest.java | 11 -----------
.../java/{IndexTaskTest.java => StudentTaskTest.java} | 2 +-
3 files changed, 2 insertions(+), 13 deletions(-)
rename src/test/java/{IndexConferenceTest.java => ConferenceTest.java} (99%)
delete mode 100644 src/test/java/IndexKiasTest.java
rename src/test/java/{IndexTaskTest.java => StudentTaskTest.java} (99%)
diff --git a/src/test/java/IndexConferenceTest.java b/src/test/java/ConferenceTest.java
similarity index 99%
rename from src/test/java/IndexConferenceTest.java
rename to src/test/java/ConferenceTest.java
index 269561f..3fae34b 100644
--- a/src/test/java/IndexConferenceTest.java
+++ b/src/test/java/ConferenceTest.java
@@ -26,7 +26,7 @@ import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-public class IndexConferenceTest extends TestTemplate {
+public class ConferenceTest extends TestTemplate {
private final Map> navigationHolder = ImmutableMap.of(
new ConferencesPage(), Arrays.asList("КОНФЕРЕНЦИИ", "/conferences/conferences"),
new ConferencePage(), Arrays.asList("РЕДАКТИРОВАНИЕ КОНФЕРЕНЦИИ", "/conferences/conference?id=0"),
diff --git a/src/test/java/IndexKiasTest.java b/src/test/java/IndexKiasTest.java
deleted file mode 100644
index 8228e76..0000000
--- a/src/test/java/IndexKiasTest.java
+++ /dev/null
@@ -1,11 +0,0 @@
-import core.TestTemplate;
-import org.junit.runner.RunWith;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringRunner;
-import ru.ulstu.NgTrackerApplication;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-public class IndexKiasTest extends TestTemplate {
-
-}
diff --git a/src/test/java/IndexTaskTest.java b/src/test/java/StudentTaskTest.java
similarity index 99%
rename from src/test/java/IndexTaskTest.java
rename to src/test/java/StudentTaskTest.java
index 51b5e07..f15b55c 100644
--- a/src/test/java/IndexTaskTest.java
+++ b/src/test/java/StudentTaskTest.java
@@ -24,7 +24,7 @@ import java.util.Map;
@RunWith(SpringRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringBootTest(classes = NgTrackerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-public class IndexTaskTest extends TestTemplate {
+public class StudentTaskTest extends TestTemplate {
private final Map> navigationHolder = ImmutableMap.of(
new TasksPage(), Arrays.asList("Список задач", "/students/tasks"),
new TasksDashboardPage(), Arrays.asList("Панель управления", "/students/dashboard"),
From 828d320e0f9f9d38b6beca019c9cdf3b97245a49 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 21:16:26 +0400
Subject: [PATCH 65/68] #120 try to run test in docker
---
.gitlab-ci.yml | 2 +-
src/main/java/ru/ulstu/grant/page/KiasPage.java | 7 +++----
2 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index fb4c0ed..6709891 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -22,7 +22,7 @@ checkRun:
checkStyle:
stage: test
- script: ./gradlew check -x test
+ script: ./gradlew check
deploy:
stage: deploy
diff --git a/src/main/java/ru/ulstu/grant/page/KiasPage.java b/src/main/java/ru/ulstu/grant/page/KiasPage.java
index ea9bdb4..631f5db 100644
--- a/src/main/java/ru/ulstu/grant/page/KiasPage.java
+++ b/src/main/java/ru/ulstu/grant/page/KiasPage.java
@@ -8,9 +8,9 @@ import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
-import java.util.NoSuchElementException;
public class KiasPage {
+ private final static String KIAS_GRANT_DATE_FORMAT = "dd.MM.yyyy HH:mm";
private WebDriver driver;
public KiasPage(WebDriver webDriver) {
@@ -23,10 +23,9 @@ public class KiasPage {
driver.findElement(By.id("js-ctrlNext")).click();
return true;
}
- } catch (NoSuchElementException e) {
+ } finally {
return false;
}
- return false;
}
public List getPageOfGrants() {
@@ -41,7 +40,7 @@ public class KiasPage {
public Date parseDeadLineDate(WebElement grantElement) throws ParseException {
String deadlineDate = getFirstDeadline(grantElement); //10.06.2019 23:59
- SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
+ SimpleDateFormat formatter = new SimpleDateFormat(KIAS_GRANT_DATE_FORMAT);
return formatter.parse(deadlineDate);
}
From 280c39dae4ddc76db07b21e5d12dbc2d47c59ca9 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 21:32:20 +0400
Subject: [PATCH 66/68] #120 fix variable
---
src/test/java/StudentTaskTest.java | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/src/test/java/StudentTaskTest.java b/src/test/java/StudentTaskTest.java
index f15b55c..f55a679 100644
--- a/src/test/java/StudentTaskTest.java
+++ b/src/test/java/StudentTaskTest.java
@@ -31,7 +31,7 @@ public class StudentTaskTest extends TestTemplate {
new TaskPage(), Arrays.asList("Создать задачу", "/students/task?id=0")
);
- private final String TAG = "ATag";
+ private final String tag = "ATag";
@Autowired
private ApplicationProperties applicationProperties;
@@ -168,13 +168,13 @@ public class StudentTaskTest extends TestTemplate {
String taskName = "Task " + (new Date()).getTime();
taskPage.setName(taskName);
- taskPage.setTag(TAG);
+ taskPage.setTag(tag);
Thread.sleep(1000);
taskPage.addDeadlineDate("01.01.2020", 0);
taskPage.addDeadlineDescription("Description", 0);
taskPage.save();
- Assert.assertTrue(tasksPage.findTaskByTag(taskName, TAG));
+ Assert.assertTrue(tasksPage.findTaskByTag(taskName, tag));
}
@Test
@@ -185,7 +185,7 @@ public class StudentTaskTest extends TestTemplate {
TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey());
- Assert.assertTrue(tasksPage.findTag(TAG));
+ Assert.assertTrue(tasksPage.findTag(tag));
}
@Test
@@ -194,9 +194,9 @@ public class StudentTaskTest extends TestTemplate {
getContext().goTo(applicationProperties.getBaseUrl() + page.getValue().get(1));
TasksPage tasksPage = (TasksPage) getContext().initPage(page.getKey());
- tasksPage.selectTag(TAG);
+ tasksPage.selectTag(tag);
- Assert.assertTrue(tasksPage.findTasksByTag(TAG));
+ Assert.assertTrue(tasksPage.findTasksByTag(tag));
}
@Test
From 0cd3055176e76f2214478755da97830d44ee6bc9 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Sat, 25 May 2019 21:33:06 +0400
Subject: [PATCH 67/68] #120 disable tests
---
.gitlab-ci.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 6709891..fb4c0ed 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -22,7 +22,7 @@ checkRun:
checkStyle:
stage: test
- script: ./gradlew check
+ script: ./gradlew check -x test
deploy:
stage: deploy
From 336a16ff73938acb32188a0f55caca3577961c16 Mon Sep 17 00:00:00 2001
From: Anton Romanov
Date: Mon, 27 May 2019 09:14:24 +0400
Subject: [PATCH 68/68] some refactor
---
.../grant/controller/GrantController.java | 2 +-
src/main/java/ru/ulstu/grant/model/Grant.java | 7 ++--
.../grant/repository/GrantRepository.java | 3 ++
.../ulstu/grant/service/GrantScheduler.java | 2 +-
.../ru/ulstu/grant/service/GrantService.java | 19 +++++----
.../java/ru/ulstu/timeline/model/Event.java | 4 +-
src/main/resources/application.properties | 2 +-
.../grants/fragments/grantLineFragment.html | 3 +-
.../resources/templates/grants/grant.html | 42 +------------------
.../papers/fragments/paperLineFragment.html | 3 +-
10 files changed, 27 insertions(+), 60 deletions(-)
diff --git a/src/main/java/ru/ulstu/grant/controller/GrantController.java b/src/main/java/ru/ulstu/grant/controller/GrantController.java
index 91b0f91..a9c01ed 100644
--- a/src/main/java/ru/ulstu/grant/controller/GrantController.java
+++ b/src/main/java/ru/ulstu/grant/controller/GrantController.java
@@ -43,7 +43,7 @@ public class GrantController {
@GetMapping("/dashboard")
public void getDashboard(ModelMap modelMap) {
- modelMap.put("grants", grantService.findAllDto());
+ modelMap.put("grants", grantService.findAllActiveDto());
}
@GetMapping("/grant")
diff --git a/src/main/java/ru/ulstu/grant/model/Grant.java b/src/main/java/ru/ulstu/grant/model/Grant.java
index e0cd9be..369568f 100644
--- a/src/main/java/ru/ulstu/grant/model/Grant.java
+++ b/src/main/java/ru/ulstu/grant/model/Grant.java
@@ -43,7 +43,8 @@ public class Grant extends BaseEntity implements UserContainer {
IN_WORK("В работе"),
COMPLETED("Завершен"),
FAILED("Провалены сроки"),
- LOADED_FROM_KIAS("Загружен автоматически");
+ LOADED_FROM_KIAS("Загружен автоматически"),
+ SKIPPED("Не интересует");
private String statusName;
@@ -62,14 +63,14 @@ public class Grant extends BaseEntity implements UserContainer {
@Enumerated(value = EnumType.STRING)
private GrantStatus status = GrantStatus.APPLICATION;
- @OneToMany(cascade = CascadeType.ALL)
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "grant_id")
@OrderBy("date")
private List deadlines = new ArrayList<>();
private String comment;
- @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
+ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "grant_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
private List files = new ArrayList<>();
diff --git a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
index ae9fcc8..876a8c1 100644
--- a/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
+++ b/src/main/java/ru/ulstu/grant/repository/GrantRepository.java
@@ -17,4 +17,7 @@ public interface GrantRepository extends JpaRepository, BaseRepo
@Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
+
+ @Query("SELECT g FROM Grant g WHERE (g.status <> 'SKIPPED') AND (g.status <> 'COMPLETED')")
+ List findAllActive();
}
diff --git a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
index fb236af..a2950a6 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantScheduler.java
@@ -31,7 +31,7 @@ public class GrantScheduler {
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished");
}
- @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara")
+ @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started");
try {
diff --git a/src/main/java/ru/ulstu/grant/service/GrantService.java b/src/main/java/ru/ulstu/grant/service/GrantService.java
index 8d65da7..86f8f1b 100644
--- a/src/main/java/ru/ulstu/grant/service/GrantService.java
+++ b/src/main/java/ru/ulstu/grant/service/GrantService.java
@@ -41,7 +41,6 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service
public class GrantService extends BaseService {
- private final static int MAX_DISPLAY_SIZE = 50;
private final Logger log = LoggerFactory.getLogger(GrantService.class);
private final GrantRepository grantRepository;
@@ -80,9 +79,7 @@ public class GrantService extends BaseService {
}
public List findAllDto() {
- List grants = convert(findAll(), GrantDto::new);
- grants.forEach(grantDto -> grantDto.setTitle(StringUtils.abbreviate(grantDto.getTitle(), MAX_DISPLAY_SIZE)));
- return grants;
+ return convert(findAll(), GrantDto::new);
}
public GrantDto findOneDto(Integer id) {
@@ -273,11 +270,7 @@ public class GrantService extends BaseService {
}
public List getAllUncompletedPapers() {
- List papers = paperService.findAllNotCompleted();
- papers.stream()
- .forEach(paper ->
- paper.setTitle(StringUtils.abbreviate(paper.getTitle(), MAX_DISPLAY_SIZE)));
- return papers;
+ return paperService.findAllNotCompleted();
}
public void attachPaper(GrantDto grantDto) {
@@ -335,4 +328,12 @@ public class GrantService extends BaseService {
}
}
}
+
+ public List findAllActiveDto() {
+ return convert(findAllActive(), GrantDto::new);
+ }
+
+ private List findAllActive() {
+ return grantRepository.findAllActive();
+ }
}
diff --git a/src/main/java/ru/ulstu/timeline/model/Event.java b/src/main/java/ru/ulstu/timeline/model/Event.java
index e56c91c..8038f0b 100644
--- a/src/main/java/ru/ulstu/timeline/model/Event.java
+++ b/src/main/java/ru/ulstu/timeline/model/Event.java
@@ -65,8 +65,8 @@ public class Event extends BaseEntity {
private String description;
- @ManyToMany(fetch = FetchType.EAGER)
- private List recipients = new ArrayList();
+ @ManyToMany(fetch = FetchType.LAZY)
+ private List recipients = new ArrayList<>();
@ManyToOne
@JoinColumn(name = "child_id")
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
index cdd7569..f4be778 100644
--- a/src/main/resources/application.properties
+++ b/src/main/resources/application.properties
@@ -35,6 +35,6 @@ liquibase.change-log=classpath:db/changelog-master.xml
ng-tracker.base-url=http://127.0.0.1:8080
ng-tracker.undead-user-login=admin
ng-tracker.dev-mode=true
-ng-tracker.debug_email=romanov73@gmail.com
+ng-tracker.debug_email=
ng-tracker.use-https=false
ng-tracker.check-run=false
\ No newline at end of file
diff --git a/src/main/resources/templates/grants/fragments/grantLineFragment.html b/src/main/resources/templates/grants/fragments/grantLineFragment.html
index dda0e8d..877f1d7 100644
--- a/src/main/resources/templates/grants/fragments/grantLineFragment.html
+++ b/src/main/resources/templates/grants/fragments/grantLineFragment.html
@@ -8,7 +8,8 @@
-
+
+
diff --git a/src/main/resources/templates/grants/grant.html b/src/main/resources/templates/grants/grant.html
index 38047bf..acb7f7b 100644
--- a/src/main/resources/templates/grants/grant.html
+++ b/src/main/resources/templates/grants/grant.html
@@ -186,47 +186,7 @@
diff --git a/src/main/resources/templates/papers/fragments/paperLineFragment.html b/src/main/resources/templates/papers/fragments/paperLineFragment.html
index b703859..40d9c34 100644
--- a/src/main/resources/templates/papers/fragments/paperLineFragment.html
+++ b/src/main/resources/templates/papers/fragments/paperLineFragment.html
@@ -8,7 +8,8 @@