Compare commits

..

11 Commits

Author SHA1 Message Date
Artem.Arefev
e81ee4d36b #93 codestyle 2019-06-11 01:20:34 +04:00
Artem.Arefev
cbae48c23e #93 users activities analytycs 2019-06-11 01:18:49 +04:00
Artem.Arefev
015a1d7fb8 #93 merged with dev 2019-06-09 01:54:21 +04:00
Artem.Arefev
0bb9d5771f #93 merged with dev 2019-06-09 01:53:01 +04:00
Artem.Arefev
a28b3ea57b #93 resolve stashed conflicts 2019-06-07 12:46:27 +04:00
Artem.Arefev
9bec1d080d #93 completed count 2019-06-05 11:55:51 +04:00
Artem.Arefev
44e3fc2c6e #93 fixes 2019-06-05 11:25:33 +04:00
Artem.Arefev
2adaf7740a #93 removed comment 2019-06-05 10:55:12 +04:00
Artem.Arefev
ed7707c4d8 #93 users activity by date 2019-06-05 10:53:30 +04:00
Artem.Arefev
ea0b8fbaad Merge remote-tracking branch 'origin/dev' into 93-activites-analytics 2019-06-03 02:14:26 +04:00
Artem.Arefev
d1182ea7c3 Merge remote-tracking branch 'origin/dev' into 93-activites-analytics 2019-05-27 02:12:22 +04:00
228 changed files with 6472 additions and 2316 deletions

View File

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

19
Jenkinsfile vendored
View File

@ -1,19 +0,0 @@
pipeline {
agent any
stages {
stage('Test') {
steps {
sh "./gradlew clean test --info"
}
}
}
post {
always {
script {
if (currentBuild.currentResult == 'FAILURE') {
step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "a.romanov@ulstu.ru", sendToIndividuals: true])
}
}
}
}
}

View File

@ -9,4 +9,6 @@
4. Получить проект для обучения бакалавров современым технологиям разработки.
5. Создать систему хранения и трансляции опыта между участниками научной группы.
[Для разворачивания проекта и ведения разработки ознакомьтесь с wiki](https://git.athene.tech/romanov73/ng-tracker/wiki/home)
[Демо версия доступна здесь](http://193.110.3.124:8080)
[Для разворачивания проекта и ведения разработки ознакомьтесь с wiki](https://gitlab.com/romanov73/ng-tracker/wikis/home)

View File

@ -1,19 +1,34 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.4'
id 'io.spring.dependency-management' version '1.1.4'
id 'checkstyle'
buildscript {
ext {
versionSpringBoot = '1.5.10.RELEASE'
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath group: 'org.springframework.boot', name: 'spring-boot-gradle-plugin', version: versionSpringBoot
}
}
group 'ru.ulstu'
version '0.1.0-SNAPSHOT'
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'checkstyle'
mainClassName = 'ru.ulstu.NgTrackerApplication'
build.dependsOn checkstyleMain
bootRun.dependsOn checkstyleMain
java {
sourceCompatibility = '17'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
bootRun {
systemProperties = System.properties
@ -49,7 +64,7 @@ checkstyle {
checkstyle
}
dependencies {
dependencies{
assert project.hasProperty("checkstyleVersion")
checkstyle "com.puppycrawl.tools:checkstyle:${checkstyleVersion}"
@ -61,16 +76,9 @@ task health(dependsOn: [
'checkstyleMain'
])
test {
useJUnitPlatform()
}
jar {
enabled = false
}
bootJar {
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
baseName = 'ng-tracker'
}
compileJava {
@ -82,39 +90,45 @@ repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-jetty'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation'
implementation group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect'
implementation group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity6'
implementation group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner'
implementation group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5'
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
implementation group: 'org.liquibase', name: 'liquibase-core', version: '4.27.0'
implementation group: 'com.mattbertolini', name: 'liquibase-slf4j', version: '2.0.0'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
implementation group: 'org.webjars', name: 'bootstrap', version: '5.3.3'
runtimeOnly group: 'org.webjars', name: 'bootstrap-select', version: '1.4.2'
implementation group: 'org.webjars', name: 'jquery', version: '3.7.1'
implementation group: 'org.webjars', name: 'jquery-easing', version: '1.4.1'
implementation group: 'org.webjars', name: 'font-awesome', version: '4.7.0'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.8.0'
implementation group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.35.0'
implementation group: 'xalan', name: 'xalan', version: '2.7.2'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-test'
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.10.2'
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
compile.exclude module: "bcmail-jdk14"
compile.exclude module: "bcprov-jdk14"
compile.exclude module: "bctsp-jdk14"
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jetty'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-springsecurity4'
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-afterburner'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate5'
compile group: 'postgresql', name: 'postgresql', version: '9.1-901.jdbc4'
compile group: 'org.liquibase', name: 'liquibase-core', version: '3.5.3'
compile group: 'com.mattbertolini', name: 'liquibase-slf4j', version: '2.0.0'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.7'
compile group: 'org.webjars', name: 'bootstrap', version: '4.1.0'
compile group: 'org.webjars', name: 'bootstrap-select', version: '1.13.3'
compile group: 'org.webjars', name: 'jquery', version: '3.3.1-1'
compile group: 'org.webjars.npm', name: 'jquery.easing', version: '1.4.1'
compile group: 'org.webjars', name: 'font-awesome', version: '4.7.0'
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.6.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0'
compile group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.35.0'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-support', version: '3.3.1'
testCompile group: 'com.google.guava', name: 'guava', version: '21.0'
}

View File

@ -169,4 +169,4 @@
</module>
</module>
</module>

View File

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

View File

@ -2,6 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip

View File

@ -0,0 +1,17 @@
package ru.ulstu.activity.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.activity.service.ActivityService;
@Controller()
@RequestMapping(value = "/activities")
public class ActivityController {
private ActivityService activityService;
public ActivityController(ActivityService activityService) {
this.activityService = activityService;
}
}

View File

@ -0,0 +1,81 @@
package ru.ulstu.activity.model;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.model.User;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
@Entity
@Table(name = "activity")
public class Activity extends BaseEntity {
public enum ActivityState {
TOOK_IN_WORK("Взято в работу"),
COMPLETED("Выполнено");
private String statusName;
ActivityState(String statusName) {
this.statusName = statusName;
}
public String getStatusName() {
return this.statusName;
}
}
@ManyToOne()
@JoinColumn(name = "user_id")
private User user;
@Temporal(value = TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
@Enumerated(value = EnumType.STRING)
@Column(name = "state")
private ActivityState activityState;
public Activity(User user, ActivityState activityState) {
this.user = user;
this.date = new Date();
this.activityState = activityState;
}
public Activity() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public ActivityState getActivityState() {
return activityState;
}
public void setActivityState(ActivityState activityState) {
this.activityState = activityState;
}
}

View File

@ -0,0 +1,38 @@
package ru.ulstu.activity.model;
public class ActivityElement {
private int startedCount = 0;
private int completedCount = 0;
public ActivityElement() {
}
public ActivityElement(int startedCount, int completedCount) {
this.startedCount = startedCount;
this.completedCount = completedCount;
}
public int getStartedCount() {
return startedCount;
}
public void setStartedCount(int startedCount) {
this.startedCount = startedCount;
}
public int getCompletedCount() {
return completedCount;
}
public void setCompletedCount(int completedCount) {
this.completedCount = completedCount;
}
public void incrementStartedCount() {
this.startedCount++;
}
public void incrementCompletedCount() {
this.completedCount++;
}
}

View File

@ -0,0 +1,19 @@
package ru.ulstu.activity.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.activity.model.Activity;
import java.util.Date;
import java.util.List;
public interface ActivityRepository extends JpaRepository<Activity, Integer> {
@Query("SELECT a FROM Activity a WHERE (:userId IS NULL OR a.user.id = :userId) " +
"AND (CAST(:dateFrom AS date) IS NULL OR :dateFrom < a.date) " +
"AND (CAST(:dateTo AS date) IS NULL OR :dateTo > a.date)")
List<Activity> getByUserAndDateInterval(@Param("userId") Integer userId,
@Param("dateFrom") Date dateFrom,
@Param("dateTo") Date dateTo);
}

View File

@ -0,0 +1,56 @@
package ru.ulstu.activity.service;
import org.springframework.stereotype.Service;
import ru.ulstu.activity.model.Activity;
import ru.ulstu.activity.model.ActivityElement;
import ru.ulstu.activity.repository.ActivityRepository;
import ru.ulstu.user.model.User;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ActivityService {
private ActivityRepository activityRepository;
public ActivityService(ActivityRepository activityRepository) {
this.activityRepository = activityRepository;
}
public void createActivity(List<User> users, Activity.ActivityState state) {
List<Activity> activities = new ArrayList<>();
for (User user : users) {
activities.add(new Activity(user, state));
}
activityRepository.save(activities);
}
public Map<String, ActivityElement> getUsersActivity(Integer userId, Date dateFrom, Date dateTo) {
List<Activity> activities = activityRepository.getByUserAndDateInterval(userId, dateFrom, dateTo);
Map<String, ActivityElement> dateActivities = new HashMap<>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
for (Activity activity : activities) {
String dt = formatter.format(activity.getDate());
ActivityElement element;
if (!dateActivities.containsKey(dt)) {
element = new ActivityElement();
} else {
element = dateActivities.get(dt);
}
switch (activity.getActivityState()) {
case TOOK_IN_WORK:
element.incrementStartedCount();
break;
case COMPLETED:
element.incrementCompletedCount();
break;
}
dateActivities.put(dt, element);
}
return dateActivities;
}
}

View File

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

View File

@ -1,8 +1,6 @@
package ru.ulstu.conference.controller;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@ -16,7 +14,9 @@ import ru.ulstu.conference.model.ConferenceFilterDto;
import ru.ulstu.conference.model.ConferenceUser;
import ru.ulstu.conference.service.ConferenceService;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
@ -29,7 +29,7 @@ import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@Controller()
@RequestMapping(value = "/conferences")
@Hidden
@ApiIgnore
public class ConferenceController {
private final ConferenceService conferenceService;

View File

@ -1,19 +1,8 @@
package ru.ulstu.conference.model;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.validation.constraints.NotBlank;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
@ -23,6 +12,19 @@ import ru.ulstu.paper.model.Paper;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
@ -61,21 +63,18 @@ public class Conference extends BaseEntity implements UserActivity, EventSource
@OrderBy("date")
private List<Deadline> deadlines = new ArrayList<>();
@OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinColumn(name = "conference_id")
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@JoinTable(name = "paper_conference",
joinColumns = {@JoinColumn(name = "conference_id")},
inverseJoinColumns = {@JoinColumn(name = "paper_id")})
@Fetch(FetchMode.SUBSELECT)
private List<Paper> papers = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "conference_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
private List<ConferenceUser> users = new ArrayList<>();
public Conference() {
}
public Conference(@NotBlank String title) {
this.title = title;
}
public String getTitle() {
return title;
}

View File

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

View File

@ -2,17 +2,18 @@ package ru.ulstu.conference.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.model.User;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "users_conference")
public class ConferenceUser extends BaseEntity {
@ -21,7 +22,7 @@ public class ConferenceUser extends BaseEntity {
INTRAMURAL("Очная"),
EXTRAMURAL("Заочная");
private final String participationName;
private String participationName;
Participation(String name) {
this.participationName = name;
@ -37,7 +38,7 @@ public class ConferenceUser extends BaseEntity {
REPORT("Доклад"),
PRESENTATION("Презентация");
private final String depositName;
private String depositName;
Deposit(String name) {
this.depositName = name;
@ -68,7 +69,6 @@ public class ConferenceUser extends BaseEntity {
public ConferenceUser(User user) {
this.user = user;
this.deposit = Deposit.REPORT;
}
@JsonCreator

View File

@ -13,7 +13,7 @@ import java.util.List;
public interface ConferenceRepository extends JpaRepository<Conference, Integer>, BaseRepository {
@Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " +
"AND (YEAR(c.beginDate) = :year OR :year IS NULL) ORDER BY c.beginDate DESC")
"AND (YEAR(c.beginDate) = :year OR :year IS NULL) ORDER BY begin_date DESC")
List<Conference> findByUserAndYear(@Param("user") User user, @Param("year") Integer year);
@Query("SELECT c FROM Conference c WHERE c.beginDate > :date")
@ -28,7 +28,7 @@ public interface ConferenceRepository extends JpaRepository<Conference, Integer>
@Override
@Query("SELECT title FROM Conference c WHERE (c.title = :name) AND (:id IS NULL OR c.id != :id) ")
List<String> findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
@Query("SELECT c FROM Conference c LEFT JOIN c.users u WHERE (:user IS NULL OR u.user = :user) " +
"AND (u.participation = 'INTRAMURAL') AND (c.beginDate <= CURRENT_DATE) AND (c.endDate >= CURRENT_DATE)")

View File

@ -1,5 +1,6 @@
package ru.ulstu.conference.service;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Service;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.util.DateUtils;
@ -56,27 +57,27 @@ public class ConferenceNotificationService {
}
private void sendMessageDeadline(Conference conference) {
Map<String, Object> variables = Map.of("conference", conference);
Map<String, Object> variables = ImmutableMap.of("conference", conference);
sendForAllParticipants(variables, conference, TEMPLATE_DEADLINE, String.format(TITLE_DEADLINE, conference.getTitle()));
}
public void sendCreateNotification(Conference conference) {
Map<String, Object> variables = Map.of("conference", conference);
sendForAllUsers(variables, String.format(TITLE_CREATE, conference.getTitle()));
Map<String, Object> variables = ImmutableMap.of("conference", conference);
sendForAllUsers(variables, TEMPLATE_CREATE, String.format(TITLE_CREATE, conference.getTitle()));
}
public void updateDeadlineNotification(Conference conference) {
Map<String, Object> variables = Map.of("conference", conference);
Map<String, Object> variables = ImmutableMap.of("conference", conference);
sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DEADLINES, String.format(TITLE_UPDATE_DEADLINES, conference.getTitle()));
}
public void updateConferencesDatesNotification(Conference conference, Date oldBeginDate, Date oldEndDate) {
Map<String, Object> variables = Map.of("conference", conference, "oldBeginDate", oldBeginDate, "oldEndDate", oldEndDate);
Map<String, Object> variables = ImmutableMap.of("conference", conference, "oldBeginDate", oldBeginDate, "oldEndDate", oldEndDate);
sendForAllParticipants(variables, conference, TEMPLATE_UPDATE_DATES, String.format(TITLE_UPDATE_DATES, conference.getTitle()));
}
private void sendForAllUsers(Map<String, Object> variables, String title) {
userService.findAll().forEach(user -> mailService.sendEmailFromTemplate(variables, user, ConferenceNotificationService.TEMPLATE_CREATE, title));
private void sendForAllUsers(Map<String, Object> variables, String template, String title) {
userService.findAll().forEach(user -> mailService.sendEmailFromTemplate(variables, user, template, title));
}
private void sendForAllParticipants(Map<String, Object> variables, Conference conference, String template, String title) {
@ -106,7 +107,7 @@ public class ConferenceNotificationService {
}
private void sendMessagePing(Conference conference) {
Map<String, Object> variables = Map.of("conference", conference);
Map<String, Object> variables = ImmutableMap.of("conference", conference);
sendForAllParticipants(variables, conference, TEMPLATE_PING, String.format(TITLE_PING, conference.getTitle()));
}
}

View File

@ -11,26 +11,25 @@ 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.core.util.DateUtils;
import ru.ulstu.deadline.model.Deadline;
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;
import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
import static org.springframework.util.ObjectUtils.isEmpty;
import static ru.ulstu.core.util.StreamApiUtils.convert;
@ -67,7 +66,7 @@ public class ConferenceService extends BaseService {
}
public ConferenceDto getExistConferenceById(Integer id) {
ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.getOne(id));
ConferenceDto conferenceDto = new ConferenceDto(conferenceRepository.findOne(id));
conferenceDto.setNotSelectedPapers(getNotSelectPapers(conferenceDto.getPaperIds()));
conferenceDto.setDisabledTakePart(isCurrentUserParticipant(conferenceDto.getUsers()));
return conferenceDto;
@ -81,7 +80,7 @@ public class ConferenceService extends BaseService {
public List<Conference> findAll() {
return conferenceRepository.findAll(Sort.by(Sort.Direction.DESC, "beginDate"));
return conferenceRepository.findAll(new Sort(Sort.Direction.DESC, "beginDate"));
}
public List<ConferenceDto> findAllDto() {
@ -98,6 +97,7 @@ public class ConferenceService extends BaseService {
checkUniqueName(conferenceDto,
errors,
conferenceDto.getId(),
"title",
"Конференция с таким именем уже существует");
if (errors.hasErrors()) {
return false;
@ -112,63 +112,43 @@ public class ConferenceService extends BaseService {
return true;
}
public Conference save(Conference conference) {
if (isEmpty(conference.getId())) {
return create(conference);
} else {
return update(conference);
}
}
@Transactional
public Conference create(ConferenceDto conferenceDto) throws IOException {
return create(copyFromDto(new Conference(), conferenceDto));
Conference newConference = copyFromDto(new Conference(), conferenceDto);
newConference = conferenceRepository.save(newConference);
conferenceNotificationService.sendCreateNotification(newConference);
eventService.createFromObject(newConference, Collections.emptyList(), false, "конференции");
return newConference;
}
@Transactional
public Conference create(Conference conference) {
conference = conferenceRepository.save(conference);
conferenceNotificationService.sendCreateNotification(conference);
return conference;
}
@Transactional
private Conference update(ConferenceDto conferenceDto) throws IOException {
return update(copyFromDto(conferenceRepository.getOne(conferenceDto.getId()), conferenceDto));
}
@Transactional
private Conference update(Conference conference) {
Conference oldConference = conferenceRepository.getOne(conference.getId());
List<Deadline> oldDeadlines = oldConference.getDeadlines().stream()
public Conference update(ConferenceDto conferenceDto) throws IOException {
Conference conference = conferenceRepository.findOne(conferenceDto.getId());
List<Deadline> oldDeadlines = conference.getDeadlines().stream()
.map(this::copyDeadline)
.collect(Collectors.toList());
Date oldBeginDate = conference.getBeginDate();
Date oldEndDate = conference.getEndDate();
conferenceRepository.save(conference);
conferenceRepository.save(copyFromDto(conference, conferenceDto));
eventService.updateConferenceDeadlines(conference);
sendNotificationAfterUpdateDeadlines(conference, oldDeadlines);
if (!conference.getBeginDate().equals(oldBeginDate) || !conference.getEndDate().equals(oldEndDate)) {
conferenceNotificationService.updateConferencesDatesNotification(conference, oldBeginDate, oldEndDate);
}
conferenceDto.getRemovedDeadlineIds().forEach(deadlineService::remove);
return conference;
}
@Transactional
public boolean delete(Integer conferenceId) {
if (conferenceRepository.existsById(conferenceId)) {
eventService.removeConferencesEvent(conferenceRepository.getOne(conferenceId));
conferenceRepository.deleteById(conferenceId);
if (conferenceRepository.exists(conferenceId)) {
eventService.removeConferencesEvent(conferenceRepository.findOne(conferenceId));
conferenceRepository.delete(conferenceId);
return true;
}
return false;
}
@Transactional
public boolean delete(List<Conference> conferences) {
conferences.forEach(conference -> delete(conference.getId()));
return true;
}
public ConferenceDto addDeadline(ConferenceDto conferenceDto) {
conferenceDto.getDeadlines().add(new Deadline());
return conferenceDto;
@ -254,7 +234,7 @@ public class ConferenceService extends BaseService {
return convert(findAllActive(), ConferenceDto::new);
}
public List<Conference> findAllActive() {
private List<Conference> findAllActive() {
return conferenceRepository.findAllActive(new Date());
}
@ -268,8 +248,8 @@ public class ConferenceService extends BaseService {
conferenceRepository.updatePingConference(conferenceDto.getId());
}
public Conference findOne(Integer conferenceId) {
return conferenceRepository.getOne(conferenceId);
private Conference findOne(Integer conferenceId) {
return conferenceRepository.findOne(conferenceId);
}
public void setChartData(ModelMap modelMap) {
@ -314,7 +294,7 @@ public class ConferenceService extends BaseService {
return newDeadline;
}
private void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) {
public void checkEmptyFieldsOfDeadline(ConferenceDto conferenceDto, Errors errors) {
for (Deadline deadline : conferenceDto.getDeadlines()) {
if (deadline.getDate() == null || deadline.getDescription().isEmpty()) {
errors.rejectValue("deadlines", "errorCode", "Все поля дедлайна должны быть заполнены");
@ -337,22 +317,4 @@ public class ConferenceService extends BaseService {
public Conference getActiveConferenceByUser(User user) {
return conferenceRepository.findActiveByUser(user);
}
public Conference createByTitle(String newConferenceTitle) {
Conference conference = new Conference(newConferenceTitle);
conference.setBeginDate(DateUtils.localDateToDate(DateUtils.convertToLocalDate(new Date()).plus(1, ChronoUnit.WEEKS)));
conference.setEndDate(DateUtils.localDateToDate(DateUtils.convertToLocalDate(new Date()).plus(2, ChronoUnit.WEEKS)));
conference.getUsers().add(new ConferenceUser(userService.getCurrentUser()));
conference.getDeadlines().add(deadlineService.createWithOffset(new Date(), 1, ChronoUnit.WEEKS));
return save(conference);
}
public List<Conference> findAllActiveByCurrentUser() {
return findAllActive()
.stream()
.filter(conference -> conference.getUsers()
.stream()
.anyMatch(user -> user.getUser().equals(userService.getCurrentUser())))
.collect(toList());
}
}

View File

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

View File

@ -1,6 +1,6 @@
package ru.ulstu.configuration;
import jakarta.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

View File

@ -22,4 +22,4 @@ public class Constants {
public static final String PASSWORD_RESET_PAGE = "/reset";
public static final int RESET_KEY_LENGTH = 6;
}
}

View File

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

View File

@ -1,10 +1,10 @@
package ru.ulstu.configuration;
import nz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.extras.springsecurity6.dialect.SpringSecurityDialect;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
@ -17,17 +17,30 @@ public class MailTemplateConfiguration {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver);
templateEngine.addTemplateResolver(emailTemplateResolver());
templateEngine.addTemplateResolver(mvcTemplateResolver());
templateEngine.addDialect(new LayoutDialect());
templateEngine.addDialect(sec);
return templateEngine;
}
private ClassLoaderTemplateResolver emailTemplateResolver() {
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("/mail_templates/");
emailTemplateResolver.setTemplateMode("HTML");
emailTemplateResolver.setPrefix("mail_templates/");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setOrder(1);
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
public ClassLoaderTemplateResolver mvcTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("templates");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setOrder(2);
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
}

View File

@ -3,10 +3,10 @@ package ru.ulstu.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/{articlename:\\w+}");

View File

@ -5,16 +5,14 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
@ -25,12 +23,10 @@ import ru.ulstu.user.service.UserService;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
@Autowired
private Environment env;
@Value("${server.http.port}")
private int httpPort;
@Value("${server.port}")
@ -57,61 +53,66 @@ public class SecurityConfiguration {
this.authenticationFailureHandler = authenticationFailureHandler;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable);
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable();
if (applicationProperties.isDevMode()) {
log.debug("Security disabled");
http.authorizeHttpRequests((authz) -> authz
http.authorizeRequests()
.anyRequest()
.permitAll()
);
http.anonymous((anonymousCustomizer) -> anonymousCustomizer
.permitAll();
http.anonymous()
.principal("admin")
.authorities(UserRoleConstants.ADMIN)
);
.authorities(UserRoleConstants.ADMIN);
} else {
log.debug("Security enabled");
http.authorizeHttpRequests((authz) -> authz
.requestMatchers(UserController.ACTIVATE_URL).permitAll()
.requestMatchers(Constants.PASSWORD_RESET_REQUEST_PAGE).permitAll()
.requestMatchers(Constants.PASSWORD_RESET_PAGE).permitAll()
.requestMatchers("/users/block").permitAll()
.requestMatchers(UserController.URL + UserController.REGISTER_URL).permitAll()
.requestMatchers(UserController.URL + UserController.ACTIVATE_URL).permitAll()
.requestMatchers(UserController.URL + UserController.PASSWORD_RESET_REQUEST_URL).permitAll()
.requestMatchers(UserController.URL + UserController.PASSWORD_RESET_URL).permitAll()
.requestMatchers("/swagger-ui.html").hasAuthority(UserRoleConstants.ADMIN)
.anyRequest().authenticated())
.formLogin((formLoginCustomizer) -> formLoginCustomizer
.loginPage("/login")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.permitAll()
)
.rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret"))
.logout((logoutCustomizer) -> logoutCustomizer
.logoutSuccessHandler(logoutSuccessHandler)
.logoutSuccessUrl(Constants.LOGOUT_URL)
.invalidateHttpSession(false)
.clearAuthentication(true)
.deleteCookies(Constants.COOKIES_NAME)
.permitAll()
);
http.csrf(AbstractHttpConfigurer::disable);
http.authorizeRequests()
.antMatchers(UserController.ACTIVATE_URL).permitAll()
.antMatchers(Constants.PASSWORD_RESET_REQUEST_PAGE).permitAll()
.antMatchers(Constants.PASSWORD_RESET_PAGE).permitAll()
.antMatchers("/users/block").permitAll()
.antMatchers(UserController.URL + UserController.REGISTER_URL).permitAll()
.antMatchers(UserController.URL + UserController.ACTIVATE_URL).permitAll()
.antMatchers(UserController.URL + UserController.PASSWORD_RESET_REQUEST_URL).permitAll()
.antMatchers(UserController.URL + UserController.PASSWORD_RESET_URL).permitAll()
.antMatchers("/swagger-ui.html").hasAuthority(UserRoleConstants.ADMIN)
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.permitAll()
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.logoutSuccessUrl(Constants.LOGOUT_URL)
.invalidateHttpSession(false)
.clearAuthentication(true)
.deleteCookies(Constants.COOKIES_NAME)
.permitAll();
}
return http.build();
if (applicationProperties.isUseHttps()) {
http.portMapper()
.http(httpPort)
.mapsTo(httpsPort)
.and()
.requiresChannel()
.anyRequest()
.requiresSecure();
}
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring()
.requestMatchers("/css/**",
"/javax.faces.resource/**",
"/js/**",
"/templates/**",
"/webjars/**",
"/img/**");
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/css/**")
.antMatchers("/js/**")
.antMatchers("/templates/**")
.antMatchers("/webjars/**")
.antMatchers("/img/**");
}
@Autowired

View File

@ -0,0 +1,23 @@
package ru.ulstu.configuration;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket swaggerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error")))
.build();
}
}

View File

@ -1,115 +1,116 @@
package ru.ulstu.core.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.model.ErrorConstants;
import ru.ulstu.core.model.response.Response;
import ru.ulstu.core.model.response.ResponseExtended;
import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.service.UserService;
import java.util.Set;
import java.util.stream.Collectors;
//@ControllerAdvice
public class AdviceController {
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private final UserService userService;
public AdviceController(UserService userService) {
this.userService = userService;
}
@ModelAttribute("flashMessage")
public String getFlashMessage() {
return null;
}
private Response<Void> handleException(ErrorConstants error) {
log.warn(error.toString());
return new Response<>(error);
}
private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) {
log.warn(error.toString());
return new ResponseExtended<>(error, errorData);
}
@ExceptionHandler(EntityIdIsNullException.class)
public Response<Void> handleEntityIdIsNullException(Throwable e) {
return handleException(ErrorConstants.ID_IS_NULL);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
final Set<String> errors = e.getBindingResult().getAllErrors().stream()
.filter(error -> error instanceof FieldError)
.map(error -> ((FieldError) error).getField())
.collect(Collectors.toSet());
return handleException(ErrorConstants.VALIDATION_ERROR, errors);
}
@ExceptionHandler(UserIdExistsException.class)
public Response<Void> handleUserIdExistsException(Throwable e) {
return handleException(ErrorConstants.USER_ID_EXISTS);
}
@ExceptionHandler(UserActivationError.class)
public ResponseExtended<String> handleUserActivationError(Throwable e) {
return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
}
@ExceptionHandler(UserLoginExistsException.class)
public ResponseExtended<String> handleUserLoginExistsException(Throwable e) {
return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
}
@ExceptionHandler(UserEmailExistsException.class)
public ResponseExtended<String> handleUserEmailExistsException(Throwable e) {
return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
}
@ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseExtended<String> handleUserNotFoundException(Throwable e) {
return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
}
@ExceptionHandler(UserNotActivatedException.class)
public Response<Void> handleUserNotActivatedException(Throwable e) {
return handleException(ErrorConstants.USER_NOT_ACTIVATED);
}
@ExceptionHandler(UserResetKeyError.class)
public ResponseExtended<String> handleUserResetKeyError(Throwable e) {
return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
}
@ExceptionHandler(UserIsUndeadException.class)
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) {
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
}
@ExceptionHandler(UserSendingMailException.class)
public ResponseExtended<String> handleUserSendingMailException(Throwable e) {
return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage());
}
}
package ru.ulstu.core.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.model.ErrorConstants;
import ru.ulstu.core.model.response.Response;
import ru.ulstu.core.model.response.ResponseExtended;
import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.service.UserService;
import java.util.Set;
import java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
private final UserService userService;
public AdviceController(UserService userService) {
this.userService = userService;
}
@ModelAttribute("flashMessage")
public String getFlashMessage() {
return null;
}
private Response<Void> handleException(ErrorConstants error) {
log.warn(error.toString());
return new Response<>(error);
}
private <E> ResponseExtended<E> handleException(ErrorConstants error, E errorData) {
log.warn(error.toString());
return new ResponseExtended<>(error, errorData);
}
@ExceptionHandler(EntityIdIsNullException.class)
public Response<Void> handleEntityIdIsNullException(Throwable e) {
return handleException(ErrorConstants.ID_IS_NULL);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseExtended<Set<String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
final Set<String> errors = e.getBindingResult().getAllErrors().stream()
.filter(error -> error instanceof FieldError)
.map(error -> ((FieldError) error).getField())
.collect(Collectors.toSet());
return handleException(ErrorConstants.VALIDATION_ERROR, errors);
}
@ExceptionHandler(UserIdExistsException.class)
public Response<Void> handleUserIdExistsException(Throwable e) {
return handleException(ErrorConstants.USER_ID_EXISTS);
}
@ExceptionHandler(UserActivationError.class)
public ResponseExtended<String> handleUserActivationError(Throwable e) {
return handleException(ErrorConstants.USER_ACTIVATION_ERROR, e.getMessage());
}
@ExceptionHandler(UserLoginExistsException.class)
public ResponseExtended<String> handleUserLoginExistsException(Throwable e) {
return handleException(ErrorConstants.USER_LOGIN_EXISTS, e.getMessage());
}
@ExceptionHandler(UserEmailExistsException.class)
public ResponseExtended<String> handleUserEmailExistsException(Throwable e) {
return handleException(ErrorConstants.USER_EMAIL_EXISTS, e.getMessage());
}
@ExceptionHandler(UserPasswordsNotValidOrNotMatchException.class)
public Response<Void> handleUserPasswordsNotValidOrNotMatchException(Throwable e) {
return handleException(ErrorConstants.USER_PASSWORDS_NOT_VALID_OR_NOT_MATCH);
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseExtended<String> handleUserNotFoundException(Throwable e) {
return handleException(ErrorConstants.USER_NOT_FOUND, e.getMessage());
}
@ExceptionHandler(UserNotActivatedException.class)
public Response<Void> handleUserNotActivatedException(Throwable e) {
return handleException(ErrorConstants.USER_NOT_ACTIVATED);
}
@ExceptionHandler(UserResetKeyError.class)
public ResponseExtended<String> handleUserResetKeyError(Throwable e) {
return handleException(ErrorConstants.USER_RESET_ERROR, e.getMessage());
}
@ExceptionHandler(UserIsUndeadException.class)
public ResponseExtended<String> handleUserIsUndeadException(Throwable e) {
return handleException(ErrorConstants.USER_UNDEAD_ERROR, e.getMessage());
}
@ExceptionHandler(UserSendingMailException.class)
public ResponseExtended<String> handleUserSendingMailException(Throwable e) {
return handleException(ErrorConstants.USER_SENDING_MAIL_EXCEPTION, e.getMessage());
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,6 +6,5 @@ import java.util.Set;
public interface UserActivity {
String getTitle();
Set<User> getActivityUsers();
}

View File

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

View File

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

View File

@ -1,69 +0,0 @@
package ru.ulstu.core.navigation;
public class Page {
public static final String INDEX = "/index.html";
public static final String PAPER = "/paper/paper.html";
public static final String PAPER_LIST = "/paper/papers.html";
public static final String PAPER_DASHBOARD = "/paper/dashboard.html";
public static final String GRANT = "/grant/grant.html";
public static final String GRANT_LIST = "/grant/grants.html";
public static final String GRANT_DASHBOARD = "/grant/dashboard.html";
public static final String USER_LIST = "/admin/users.html";
public static final String LOGOUT = "/logout";
public static final String CONFERENCE = "/conference/conference.html";
public static final String CONFERENCE_DASHBOARD = "/conference/dashboard.html";
public static final String CONFERENCE_LIST = "/conference/conferences.html";
public static final String PROJECT_DASHBOARD = "/conference/dashboard.html";
public String getIndex() {
return INDEX;
}
public String getPaperList() {
return PAPER_LIST;
}
public String getPaperDashboard() {
return PAPER_DASHBOARD;
}
public String getUserList() {
return USER_LIST;
}
public String getLogout() {
return LOGOUT;
}
public String getGrantList() {
return GRANT_LIST;
}
public String getGrantDashboard() {
return GRANT_DASHBOARD;
}
public String getPaper() {
return PAPER;
}
public String getGrant() {
return GRANT;
}
public String getConferenceDashboard() {
return CONFERENCE_DASHBOARD;
}
public String getProjectDashboard() {
return PROJECT_DASHBOARD;
}
public String getConference() {
return CONFERENCE;
}
public String getConferenceList() {
return CONFERENCE_LIST;
}
}

View File

@ -1,14 +1,14 @@
package ru.ulstu.core.repository;
import jakarta.persistence.EntityManager;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import java.io.Serializable;
public class JpaDetachableRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
implements JpaDetachableRepository<T, ID> {
private final EntityManager entityManager;
private EntityManager entityManager;
public JpaDetachableRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);

View File

@ -14,12 +14,9 @@ import java.util.List;
public class DateUtils {
public static Date clearTime(Date date) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
@ -63,10 +60,4 @@ public class DateUtils {
cal.add(Calendar.YEAR, count);
return cal.getTime();
}
public static LocalDate convertToLocalDate(Date dateToConvert) {
return dateToConvert.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
}
}

View File

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

View File

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

View File

@ -2,15 +2,15 @@ package ru.ulstu.deadline.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.user.model.User;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.List;
import java.util.Objects;
@ -20,7 +20,7 @@ public class Deadline extends BaseEntity {
private String description;
@Temporal(value = TemporalType.DATE)
@Temporal(value = TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
@ -108,7 +108,9 @@ public class Deadline extends BaseEntity {
}
return getId().equals(deadline.getId()) &&
description.equals(deadline.description) &&
date.equals(deadline.date);
date.equals(deadline.date) &&
executors.equals(deadline.executors) &&
done.equals(deadline.done);
}
@Override

View File

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

View File

@ -2,11 +2,9 @@ package ru.ulstu.deadline.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.repository.DeadlineRepository;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@ -28,8 +26,8 @@ public class DeadlineService {
}
@Transactional
private Deadline update(Deadline deadline) {
Deadline updateDeadline = deadlineRepository.getOne(deadline.getId());
public Deadline update(Deadline deadline) {
Deadline updateDeadline = deadlineRepository.findOne(deadline.getId());
updateDeadline.setDate(deadline.getDate());
updateDeadline.setDescription(deadline.getDescription());
updateDeadline.setExecutors(deadline.getExecutors());
@ -49,33 +47,12 @@ public class DeadlineService {
return newDeadline;
}
public Deadline create(Date date) {
Deadline deadline = new Deadline();
deadline.setDate(date);
return create(deadline);
}
public Deadline create(String description, Date date) {
Deadline deadline = new Deadline();
deadline.setDate(date);
deadline.setDescription(description);
return create(deadline);
}
@Transactional
public void remove(Integer deadlineId) {
deadlineRepository.deleteById(deadlineId);
deadlineRepository.delete(deadlineId);
}
public Date findByGrantIdAndDate(Integer id, Date date) {
return deadlineRepository.findByGrantIdAndDate(id, date);
}
public Deadline createWithOffset(Date date, long value, ChronoUnit chronoUnit) {
return create(DateUtils.localDateToDate(DateUtils.convertToLocalDate(date).plus(value, chronoUnit)));
}
public void delete(List<Deadline> deadlines) {
deadlineRepository.deleteInBatch(deadlines);
}
}

View File

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

View File

@ -1,10 +1,10 @@
package ru.ulstu.file.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity

View File

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

View File

@ -1,7 +1,5 @@
package ru.ulstu.grant.controller;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@ -18,7 +16,9 @@ import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.service.GrantService;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
@ -29,7 +29,7 @@ import static ru.ulstu.core.controller.Navigation.REDIRECT_TO;
@Controller()
@RequestMapping(value = "/grants")
@Hidden
@ApiIgnore
public class GrantController {
private final GrantService grantService;

View File

@ -1,22 +1,8 @@
package ru.ulstu.grant.model;
import jakarta.persistence.CascadeType;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
@ -25,8 +11,23 @@ import ru.ulstu.file.model.FileData;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.activity.model.Activity;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@ -41,30 +42,24 @@ import java.util.Set;
@DiscriminatorValue("GRANT")
public class Grant extends BaseEntity implements UserActivity, EventSource {
public enum GrantStatus {
APPLICATION("Заявка", "text-draft"),
ON_COMPETITION("Отправлен на конкурс", "text-review"),
SUCCESSFUL_PASSAGE("Успешное прохождение", "text-accepted"),
IN_WORK("В работе", "text-primary"),
COMPLETED("Завершен", "text-success"),
FAILED("Провалены сроки", "text-failed"),
LOADED_FROM_KIAS("Загружен автоматически", "text-warning"),
SKIPPED("Не интересует", "text-not-accepted");
APPLICATION("Заявка"),
ON_COMPETITION("Отправлен на конкурс"),
SUCCESSFUL_PASSAGE("Успешное прохождение"),
IN_WORK("В работе"),
COMPLETED("Завершен"),
FAILED("Провалены сроки"),
LOADED_FROM_KIAS("Загружен автоматически"),
SKIPPED("Не интересует");
private final String statusName;
private final String elementClass;
private String statusName;
GrantStatus(String statusName, String elementClass) {
GrantStatus(String statusName) {
this.statusName = statusName;
this.elementClass = elementClass;
}
public String getStatusName() {
return statusName;
}
public String getElementClass() {
return elementClass;
}
}
@NotBlank
@ -179,6 +174,17 @@ public class Grant extends BaseEntity implements UserActivity, EventSource {
return getAuthors();
}
public Activity.ActivityState getCommonActivityState() {
switch (this.status) {
case IN_WORK:
return Activity.ActivityState.TOOK_IN_WORK;
case COMPLETED:
return Activity.ActivityState.COMPLETED;
default:
return null;
}
}
public User getLeader() {
return leader;
}

View File

@ -2,8 +2,8 @@ package ru.ulstu.grant.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
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;

View File

@ -1,8 +1,12 @@
package ru.ulstu.grant.page;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTableDataCell;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import java.text.ParseException;
@ -35,8 +39,7 @@ public class KiasPage {
}
public String getGrantTitle(DomNode grant) {
return ((DomNode) grant.getFirstByXPath("td[2]")).getTextContent() + " "
+ ((DomNode) grant.getFirstByXPath("td[@class='tertiary']/a")).getTextContent();
return ((DomNode)grant.getFirstByXPath("td[@class='tertiary']/a")).getTextContent();
}
public Date parseDeadLineDate(DomNode grantElement) throws ParseException {
@ -46,10 +49,10 @@ public class KiasPage {
}
private String getFirstDeadline(DomNode grantElement) {
return ((DomNode) grantElement.getFirstByXPath("td[5]")).getTextContent();
return ((DomNode)grantElement.getFirstByXPath("td[5]")).getTextContent();
}
public boolean isTableRowGrantLine(DomNode grantElement) {
return !((HtmlTableRow) grantElement).getAttribute("class").contains("pagerSavedHeightSpacer");
public boolean isTrGrantLine(DomNode grantElement) {
return !((HtmlTableRow)grantElement).getAttribute("class").contains("pagerSavedHeightSpacer");
}
}
}

View File

@ -12,13 +12,13 @@ public interface GrantRepository extends JpaRepository<Grant, Integer>, BaseRepo
List<Grant> findByStatus(Grant.GrantStatus status);
Grant findFirstByTitle(String title);
Grant findByTitle(String title);
Grant findGrantById(Integer grantId);
@Override
@Query("SELECT title FROM Grant g WHERE (g.title = :name) AND (:id IS NULL OR g.id != :id) ")
List<String> findByNameAndNotId(@Param("name") String name, @Param("id") Integer 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<Grant> findAllActive();

View File

@ -1,5 +1,6 @@
package ru.ulstu.grant.service;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Service;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.grant.model.Grant;
@ -45,22 +46,22 @@ public class GrantNotificationService {
}
private void sendMessageDeadline(Grant grant) {
Map<String, Object> variables = Map.of("grant", grant);
Map<String, Object> variables = ImmutableMap.of("grant", grant);
sendForAllAuthors(variables, grant, TEMPLATE_DEADLINE, String.format(TITLE_DEADLINE, grant.getTitle()));
}
public void sendCreateNotification(Grant grant) {
Map<String, Object> variables = Map.of("grant", grant);
Map<String, Object> variables = ImmutableMap.of("grant", grant);
sendForAllAuthors(variables, grant, TEMPLATE_CREATE, String.format(TITLE_CREATE, grant.getTitle()));
}
public void sendAuthorsChangeNotification(Grant grant, Set<User> oldAuthors) {
Map<String, Object> variables = Map.of("grant", grant, "oldAuthors", oldAuthors);
Map<String, Object> variables = ImmutableMap.of("grant", grant, "oldAuthors", oldAuthors);
sendForAllAuthors(variables, grant, TEMPLATE_AUTHORS_CHANGED, String.format(TITLE_AUTHORS_CHANGED, grant.getTitle()));
}
public void sendLeaderChangeNotification(Grant grant, User oldLeader) {
Map<String, Object> variables = Map.of("grant", grant, "oldLeader", oldLeader);
Map<String, Object> variables = ImmutableMap.of("grant", grant, "oldLeader", oldLeader);
sendForAllAuthors(variables, grant, TEMPLATE_LEADER_CHANGED, String.format(TITLE_LEADER_CHANGED, grant.getTitle()));
}

View File

@ -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;
@ -24,18 +27,18 @@ public class GrantScheduler {
@Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara")
public void checkDeadlineBeforeWeek() {
log.debug("GrantScheduler.checkDeadlineBeforeWeek started");
grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished");
}
@Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started");
// try {
// grantService.createFromKias();
// } catch (ParseException | IOException e) {
// e.printStackTrace();
// }
try {
grantService.createFromKias();
} catch (ParseException | IOException e) {
e.printStackTrace();
}
log.debug("GrantScheduler.loadGrantsFromKias finished");
}
}

View File

@ -6,7 +6,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.activity.service.ActivityService;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
@ -27,7 +27,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.text.ParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
@ -55,6 +55,7 @@ public class GrantService extends BaseService {
private final GrantNotificationService grantNotificationService;
private final KiasService kiasService;
private final PingService pingService;
private final ActivityService activityService;
public GrantService(GrantRepository grantRepository,
FileService fileService,
@ -65,7 +66,8 @@ public class GrantService extends BaseService {
EventService eventService,
GrantNotificationService grantNotificationService,
KiasService kiasService,
PingService pingService) {
PingService pingService,
ActivityService activityService) {
this.grantRepository = grantRepository;
this.kiasService = kiasService;
this.baseRepository = grantRepository;
@ -77,10 +79,12 @@ public class GrantService extends BaseService {
this.eventService = eventService;
this.grantNotificationService = grantNotificationService;
this.pingService = pingService;
this.activityService = activityService;
}
public GrantDto getExistGrantById(Integer id) {
return new GrantDto(findById(id));
GrantDto grantDto = new GrantDto(findById(id));
return grantDto;
}
public List<Grant> findAll() {
@ -96,6 +100,7 @@ public class GrantService extends BaseService {
Grant newGrant = copyFromDto(new Grant(), grantDto);
newGrant = grantRepository.save(newGrant);
eventService.createFromObject(newGrant, Collections.emptyList(), false, "гранта");
activityService.createActivity(new ArrayList<>(newGrant.getAuthors()), newGrant.getCommonActivityState());
grantNotificationService.sendCreateNotification(newGrant);
return newGrant;
}
@ -134,10 +139,11 @@ public class GrantService extends BaseService {
}
@Transactional
private Integer update(GrantDto grantDto) throws IOException {
public Integer update(GrantDto grantDto) throws IOException {
Grant grant = findById(grantDto.getId());
Set<User> oldAuthors = new HashSet<>(grant.getAuthors());
User oldLeader = grant.getLeader();
Grant.GrantStatus oldStatus = grant.getStatus();
for (FileDataDto file : grantDto.getFiles().stream()
.filter(f -> f.isDeleted() && f.getId() != null)
.collect(toList())) {
@ -159,6 +165,9 @@ public class GrantService extends BaseService {
if (grant.getLeader() != oldLeader) {
grantNotificationService.sendLeaderChangeNotification(grant, oldLeader);
}
if (grant.getStatus() != oldStatus) {
activityService.createActivity(new ArrayList<>(grant.getAuthors()), grant.getCommonActivityState());
}
eventService.updateGrantDeadlines(grant);
return grant.getId();
}
@ -182,7 +191,7 @@ public class GrantService extends BaseService {
filterEmptyDeadlines(grantDto);
checkEmptyDeadlines(grantDto, errors);
checkEmptyLeader(grantDto, errors);
checkUniqueName(grantDto, errors, grantDto.getId(), "Грант с таким именем уже существует");
checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует");
if (errors.hasErrors()) {
return false;
}
@ -194,11 +203,11 @@ public class GrantService extends BaseService {
return true;
}
private boolean saveFromKias(GrantDto grantDto) throws IOException {
public boolean saveFromKias(GrantDto grantDto) throws IOException {
grantDto.setName(grantDto.getTitle());
String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени
if (title != null) {
Grant grantFromDB = grantRepository.findFirstByTitle(title); //грант с таким же названием из бд
Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд
if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают
return false;
} else { //иначе грант уже был в системе, но в другом году, поэтому надо создать
@ -224,8 +233,8 @@ public class GrantService extends BaseService {
}
private boolean checkSameDeadline(GrantDto grantDto, Integer id) {
Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас
Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date));
Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас
Date foundGrantDate = deadlineService.findByGrantIdAndDate(id, date);
return foundGrantDate != null && foundGrantDate.compareTo(date) == 0;
}
@ -327,77 +336,16 @@ public class GrantService extends BaseService {
return convert(findAllActive(), GrantDto::new);
}
public List<Grant> findAllActive() {
private List<Grant> findAllActive() {
return grantRepository.findAllActive();
}
public Grant findById(Integer id) {
return grantRepository.getOne(id);
return grantRepository.findOne(id);
}
@Transactional
public void ping(int grantId) throws IOException {
pingService.addPing(findById(grantId));
}
public void save(Grant grant) {
if (isEmpty(grant.getId())) {
create(grant);
} else {
update(grant);
}
}
@Transactional
public Grant create(Grant grant) {
Grant newGrant = grantRepository.save(grant);
grantNotificationService.sendCreateNotification(newGrant);
return newGrant;
}
@Transactional
public Integer update(Grant newGrant) {
Grant oldGrant = grantRepository.getOne(newGrant.getId());
//Grant.GrantStatus oldStatus = oldGrant.getStatus();
Set<User> oldAuthors = new HashSet<>(oldGrant.getAuthors());
newGrant = grantRepository.save(newGrant);
for (User author : newGrant.getAuthors()) {
if (!oldAuthors.contains(author)) {
grantNotificationService.sendCreateNotification(newGrant);
}
}
// if (newGrant.getStatus() != oldStatus) {
// grantNotificationService.statusChangeNotification(newPaper, oldStatus);
// }
return newGrant.getId();
}
public void createByTitle(String newGrantTitle) {
Grant grant = new Grant();
grant.setTitle(newGrantTitle);
grant.setStatus(APPLICATION);
grant.getAuthors().add(userService.getCurrentUser());
grant.setLeader(userService.getCurrentUser());
grant.getDeadlines().add(deadlineService.createWithOffset(new Date(), 1, ChronoUnit.WEEKS));
create(grant);
}
public List<Grant> findAllActiveByCurrentUser() {
return findAllActive()
.stream()
.filter(grant -> grant.getAuthors().contains(userService.getCurrentUser()) ||
grant.getLeader().equals(userService.getCurrentUser()))
.collect(toList());
}
public void delete(List<Grant> grants) {
grants.forEach(grant -> delete(grant));
}
public void delete(Grant grant) {
deadlineService.delete(grant.getDeadlines());
grantRepository.delete(grant);
}
}

View File

@ -1,7 +1,9 @@
package ru.ulstu.grant.service;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.springframework.stereotype.Service;
import ru.ulstu.configuration.ApplicationProperties;
@ -23,18 +25,18 @@ public class KiasService {
private final static String CONTEST_TYPE = "-1";
private final UserService userService;
private final ApplicationProperties applicationProperties;
public KiasService(UserService userService,
ApplicationProperties applicationProperties) {
this.userService = userService;
this.applicationProperties = applicationProperties;
}
public List<GrantDto> getNewGrantsDto() throws ParseException, IOException {
Integer leaderId = userService.findOneByLoginIgnoreCase("admin").getId();
List<GrantDto> grants = new ArrayList<>();
try (WebClient webClient = new WebClient()) {
webClient.setJavaScriptTimeout(60 * 1000);
webClient.getOptions().setThrowExceptionOnScriptError(false);
try (final WebClient webClient = new WebClient()) {
for (Integer year : generateGrantYears()) {
final HtmlPage page = webClient.getPage(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, year));
grants.addAll(getKiasGrants(page));
@ -44,7 +46,7 @@ public class KiasService {
return grants;
}
private List<GrantDto> getKiasGrants(HtmlPage page) throws ParseException {
public List<GrantDto> getKiasGrants(HtmlPage page) throws ParseException {
List<GrantDto> newGrants = new ArrayList<>();
KiasPage kiasPage = new KiasPage(page);
do {
@ -56,7 +58,7 @@ public class KiasService {
private List<GrantDto> getGrantsFromPage(KiasPage kiasPage) throws ParseException {
List<GrantDto> grants = new ArrayList<>();
for (DomNode grantElement : kiasPage.getPageOfGrants()) {
if (kiasPage.isTableRowGrantLine(grantElement)) {
if (kiasPage.isTrGrantLine(grantElement)) {
GrantDto grantDto = new GrantDto(
kiasPage.getGrantTitle(grantElement),
kiasPage.parseDeadLineDate(grantElement));

View File

@ -1,16 +1,16 @@
package ru.ulstu.index.controller;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import ru.ulstu.core.controller.AdviceController;
import ru.ulstu.user.service.UserService;
import springfox.documentation.annotations.ApiIgnore;
@Controller()
@RequestMapping(value = "/index")
@Hidden
@ApiIgnore
public class IndexController extends AdviceController {
public IndexController(UserService userService) {
super(userService);
@ -20,4 +20,4 @@ public class IndexController extends AdviceController {
public void currentUser(ModelMap modelMap) {
//нужен здесь для добавления параметров на стартовой странице
}
}
}

View File

@ -1,25 +0,0 @@
package ru.ulstu.index.model;
public class Section {
private final String title;
private final String image;
private final String href;
public Section(String title, String href, String image) {
this.title = title;
this.image = image;
this.href = href;
}
public String getTitle() {
return title;
}
public String getImage() {
return image;
}
public String getHref() {
return href;
}
}

View File

@ -2,8 +2,6 @@ package ru.ulstu.name;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface BaseRepository {
List<String> findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
String findByNameAndNotId(@Param("name") String name, @Param("id") Integer id);
}

View File

@ -3,34 +3,21 @@ package ru.ulstu.name;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public abstract class BaseService {
public BaseRepository baseRepository;
protected void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String errorMessage) {
if (nameContainer.getName().equals(getUnique(baseRepository.findByNameAndNotId(nameContainer.getName(), id)))) {
errors.rejectValue("title", "errorCode", errorMessage);
public void checkUniqueName(NameContainer nameContainer, Errors errors, Integer id, String checkField, String errorMessage) {
if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) {
errors.rejectValue(checkField, "errorCode", errorMessage);
}
}
protected String checkUniqueName(NameContainer nameContainer, Integer id) {
String foundName = getUnique(baseRepository.findByNameAndNotId(nameContainer.getName(), id));
if (nameContainer.getName().equals(foundName)) {
return foundName;
public String checkUniqueName(NameContainer nameContainer, Integer id) {
if (nameContainer.getName().equals(baseRepository.findByNameAndNotId(nameContainer.getName(), id))) {
return baseRepository.findByNameAndNotId(nameContainer.getName(), id);
}
return null;
}
private String getUnique(List<String> names) {
return Optional.ofNullable(names)
.orElse(new ArrayList<>())
.stream()
.findAny()
.orElse(null);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,10 +1,10 @@
package ru.ulstu.odin.model;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import ru.ulstu.odin.model.annotation.OdinString;
import ru.ulstu.odin.model.annotation.OdinString.OdinStringType;
import javax.validation.constraints.Size;
import java.lang.reflect.Field;
import static ru.ulstu.odin.model.annotation.OdinString.OdinStringType.EMAIL;

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
package ru.ulstu.paper.controller;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@ -16,20 +17,27 @@ import ru.ulstu.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.service.LatexService;
import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.springframework.util.StringUtils.isEmpty;
@Controller()
@RequestMapping(value = "/papers")
@Hidden
@ApiIgnore
public class PaperController {
private final PaperService paperService;
private final ConferenceService conferenceService;
@ -68,7 +76,7 @@ public class PaperController {
}
@GetMapping("/paper")
public void getPaper(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
public void getPapers(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) {
modelMap.put("paperDto", paperService.findOneDto(id));
} else {
@ -99,6 +107,15 @@ public class PaperController {
return "/papers/paper";
}
@PostMapping(value = "/paper", params = "addReference")
public String addReference(@Valid PaperDto paperDto, Errors errors) {
if (errors.hasErrors()) {
return "/papers/paper";
}
paperDto.getReferences().add(new ReferenceDto());
return "/papers/paper";
}
@ModelAttribute("allStatuses")
public List<Paper.PaperStatus> getPaperStatuses() {
return paperService.getPaperStatuses();
@ -123,6 +140,29 @@ public class PaperController {
return years;
}
@ModelAttribute("allFormatStandards")
public List<ReferenceDto.FormatStandard> getFormatStandards() {
return paperService.getFormatStandards();
}
@ModelAttribute("allReferenceTypes")
public List<ReferenceDto.ReferenceType> getReferenceTypes() {
return paperService.getReferenceTypes();
}
@PostMapping("/generatePdf")
public ResponseEntity<byte[]> getPdfFile(PaperDto paper) throws IOException, InterruptedException {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename='" +
URLEncoder.encode(paper.getTitle() + ".pdf", UTF_8.toString()) + "'");
return new ResponseEntity<>(latexService.generatePdfFromLatexFile(paper), headers, HttpStatus.OK);
}
@PostMapping("/getFormattedReferences")
public ResponseEntity<String> getFormattedReferences(PaperDto paperDto) {
return new ResponseEntity<>(paperService.getFormattedReferences(paperDto), new HttpHeaders(), HttpStatus.OK);
}
@ModelAttribute("autocompleteData")
public AutoCompleteData getAutocompleteData() {
return paperService.getAutoCompleteData();
@ -130,7 +170,7 @@ public class PaperController {
private void filterEmptyDeadlines(PaperDto paperDto) {
paperDto.setDeadlines(paperDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !dto.getDescription().isEmpty())
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription()))
.collect(Collectors.toList()));
}
}

View File

@ -1,6 +1,5 @@
package ru.ulstu.paper.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@ -17,6 +16,7 @@ import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.service.PaperService;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
@ -40,7 +40,7 @@ public class PaperRestController {
@GetMapping("/{paper-id}")
public Response<PaperDto> getPaper(@PathVariable("paper-id") Integer paperId) {
return new Response<>(paperService.findById(paperId));
return new Response(paperService.findById(paperId));
}
@PostMapping
@ -56,7 +56,7 @@ public class PaperRestController {
@DeleteMapping("/{paper-id}")
public Response<Boolean> delete(@PathVariable("paper-id") Integer paperId) throws IOException {
paperService.delete(paperId);
return new Response<>(Boolean.TRUE);
return new Response<>(true);
}
@PostMapping("/filter")

View File

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

View File

@ -1,23 +1,8 @@
package ru.ulstu.paper.model;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.validation.constraints.NotBlank;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.springframework.format.annotation.DateTimeFormat;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
@ -26,8 +11,22 @@ import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.activity.model.Activity;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
@ -41,30 +40,24 @@ import java.util.Set;
@DiscriminatorValue("PAPER")
public class Paper extends BaseEntity implements UserActivity, EventSource {
public enum PaperStatus {
ATTENTION("Обратить внимание", "text-warning"),
ON_PREPARATION("На подготовке", "text-primary"),
ON_REVIEW("Отправлена на проверку", "text-review"),
ACCEPTED("Принята", "text-accepted"),
NOT_ACCEPTED("Не принята", "text-not-accepted"),
COMPLETED("Завершена (опубликована)", "text-success"),
DRAFT("Черновик", "text-draft"),
FAILED("Провалены сроки", "text-failed");
ATTENTION("Обратить внимание"),
ON_PREPARATION("На подготовке"),
ON_REVIEW("Отправлена на проверку"),
ACCEPTED("Принята"),
NOT_ACCEPTED("Не принята"),
COMPLETED("Завершена (опубликована)"),
DRAFT("Черновик"),
FAILED("Провалены сроки");
private final String statusName;
private final String elementClass;
private String statusName;
PaperStatus(String name, String elementClass) {
PaperStatus(String name) {
this.statusName = name;
this.elementClass = elementClass;
}
public String getStatusName() {
return statusName;
}
public String getElementClass() {
return elementClass;
}
}
public enum PaperType {
@ -73,7 +66,7 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
SCOPUS("Scopus"),
WEB_OF_SCIENCE("Web Of Science");
private final String typeName;
private String typeName;
PaperType(String name) {
this.typeName = name;
@ -95,15 +88,13 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
@Column(name = "create_date")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSXXX")
private Date createDate = new Date();
@Column(name = "update_date")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSXXX")
private Date updateDate = new Date();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "paper_id", unique = true)
@Fetch(FetchMode.SUBSELECT)
@OrderBy("date")
@ -126,9 +117,12 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
@ManyToMany(fetch = FetchType.EAGER)
private Set<User> authors = new HashSet<>();
@ManyToOne()
@JoinColumn(name = "conference_id")
private Conference conference;
@Column(name = "latex_text")
private String latexText;
@ManyToMany(mappedBy = "papers")
private List<Conference> conferences;
@ManyToMany(mappedBy = "papers")
private List<Grant> grants;
@ -208,7 +202,7 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
@Override
public List<User> getRecipients() {
return new ArrayList<>(authors);
return new ArrayList(authors);
}
@Override
@ -244,12 +238,20 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
this.url = url;
}
public Conference getConference() {
return conference;
public String getLatexText() {
return latexText;
}
public void setConference(Conference conference) {
this.conference = conference;
public void setLatexText(String latexText) {
this.latexText = latexText;
}
public List<Conference> getConferences() {
return conferences;
}
public void setConferences(List<Conference> conferences) {
this.conferences = conferences;
}
public List<Grant> getGrants() {
@ -313,12 +315,24 @@ public class Paper extends BaseEntity implements UserActivity, EventSource {
Objects.equals(events, paper.events) &&
Objects.equals(files, paper.files) &&
Objects.equals(authors, paper.authors) &&
Objects.equals(conference, paper.conference) &&
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, conference, grants);
return Objects.hash(super.hashCode(), title, status, type, createDate, updateDate, deadlines, comment, url, locked, events, files, authors, latexText, conferences, grants);
}
public Activity.ActivityState getCommonActivityState() {
switch (this.status) {
case ON_PREPARATION:
return Activity.ActivityState.TOOK_IN_WORK;
case COMPLETED:
return Activity.ActivityState.COMPLETED;
default:
return null;
}
}
}

View File

@ -2,15 +2,13 @@ package ru.ulstu.paper.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -28,9 +26,7 @@ public class PaperDto {
private String title;
private Paper.PaperStatus status;
private Paper.PaperType type;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSXXX")
private Date createDate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSXXX")
private Date updateDate;
@NotEmpty
private List<Deadline> deadlines = new ArrayList<>();
@ -93,9 +89,10 @@ public class PaperDto {
this.deadlines = paper.getDeadlines();
this.comment = paper.getComment();
this.url = paper.getUrl();
this.latexText = paper.getLatexText();
this.locked = paper.getLocked();
this.files = convert(paper.getFiles(), FileDataDto::new);
this.authorIds = convert(paper.getAuthors(), BaseEntity::getId);
this.authorIds = convert(paper.getAuthors(), user -> user.getId());
this.authors = convert(paper.getAuthors(), UserDto::new);
this.references = convert(paper.getReferences(), ReferenceDto::new);
}
@ -215,7 +212,7 @@ public class PaperDto {
public String getAuthorsString() {
return StringUtils.abbreviate(authors
.stream()
.map(UserDto::getLastName)
.map(author -> author.getLastName())
.collect(Collectors.joining(", ")), MAX_AUTHORS_LENGTH);
}

View File

@ -1,11 +1,12 @@
package ru.ulstu.paper.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
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 {

View File

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

View File

@ -21,7 +21,7 @@ public interface PaperRepository extends JpaRepository<Paper, Integer> {
List<Paper> findByStatusNot(Paper.PaperStatus status);
List<Paper> findByConferenceIsNullAndStatusNot(Paper.PaperStatus status);
List<Paper> findByConferencesIsNullAndStatusNot(Paper.PaperStatus status);
List<Paper> findByIdNotInAndConferenceIsNullAndStatusNot(List<Integer> paperIds, Paper.PaperStatus status);
List<Paper> findByIdNotInAndConferencesIsNullAndStatusNot(List<Integer> paperIds, Paper.PaperStatus status);
}

View File

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

View File

@ -1,5 +1,6 @@
package ru.ulstu.paper.service;
import com.google.common.collect.ImmutableMap;
import org.springframework.stereotype.Service;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.paper.model.Paper;
@ -45,22 +46,22 @@ public class PaperNotificationService {
}
private void sendMessageDeadline(Paper paper) {
Map<String, Object> variables = Map.of("paper", paper);
Map<String, Object> variables = ImmutableMap.of("paper", paper);
sendForAllAuhtors(variables, paper, TEMPLATE_DEADLINE, TITLE_DEADLINE);
}
public void sendCreateNotification(Paper paper) {
Map<String, Object> variables = Map.of("paper", paper);
Map<String, Object> variables = ImmutableMap.of("paper", paper);
sendForAllAuhtors(variables, paper, TEMPLATE_CREATE, TITLE_CREATE);
}
public void statusChangeNotification(Paper paper, Paper.PaperStatus oldStatus) {
Map<String, Object> variables = Map.of("paper", paper, "oldStatus", oldStatus);
Map<String, Object> variables = ImmutableMap.of("paper", paper, "oldStatus", oldStatus);
sendForAllAuhtors(variables, paper, TEMPLATE_STATUS_CHANGED, TITLE_STATUS_CHANGED);
}
public void sendFailedNotification(Paper paper, Paper.PaperStatus oldStatus) {
Map<String, Object> variables = Map.of("paper", paper, "oldStatus", oldStatus);
Map<String, Object> variables = ImmutableMap.of("paper", paper, "oldStatus", oldStatus);
sendForAllAuhtors(variables, paper, TEMPLATE_FAILED, TITLE_FAILED);
}

View File

@ -3,6 +3,7 @@ package ru.ulstu.paper.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.activity.service.ActivityService;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
@ -22,7 +23,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
@ -57,6 +58,7 @@ public class PaperService {
private final EventService eventService;
private final ReferenceRepository referenceRepository;
private final PingService pingService;
private final ActivityService activityService;
public PaperService(PaperRepository paperRepository,
ReferenceRepository referenceRepository,
@ -65,7 +67,8 @@ public class PaperService {
UserService userService,
DeadlineService deadlineService,
EventService eventService,
PingService pingService) {
PingService pingService,
ActivityService activityService) {
this.paperRepository = paperRepository;
this.referenceRepository = referenceRepository;
this.fileService = fileService;
@ -74,6 +77,7 @@ public class PaperService {
this.deadlineService = deadlineService;
this.eventService = eventService;
this.pingService = pingService;
this.activityService = activityService;
}
public List<Paper> findAll() {
@ -81,7 +85,9 @@ public class PaperService {
}
public List<PaperDto> findAllDto() {
return convert(findAll(), PaperDto::new);
List<PaperDto> papers = convert(findAll(), PaperDto::new);
papers.forEach(paperDto -> paperDto.setTitle(StringUtils.abbreviate(paperDto.getTitle(), MAX_DISPLAY_SIZE)));
return papers;
}
public List<Paper> findAllActive() {
@ -91,38 +97,35 @@ public class PaperService {
.collect(toList());
}
public List<Paper> findAllActiveByCurrentUser() {
return findAllActive()
.stream()
.filter(paper -> paper.getAuthors().contains(userService.getCurrentUser()))
.collect(toList());
}
public List<PaperDto> findAllActiveDto() {
return convert(findAllActive(), PaperDto::new);
}
public PaperDto findOneDto(Integer id) {
return new PaperDto(paperRepository.findById(id).orElseThrow());
return new PaperDto(paperRepository.findOne(id));
}
@Transactional
public Integer create(PaperDto paperDto) throws IOException {
Paper newPaper = copyFromDto(new Paper(), paperDto);
return create(newPaper).getId();
newPaper = paperRepository.save(newPaper);
paperNotificationService.sendCreateNotification(newPaper);
eventService.createFromPaper(newPaper);
return newPaper.getId();
}
@Transactional
public Paper create(Paper paper) {
Paper newPaper = paperRepository.save(paper);
newPaper.setCreateDate(new Date());
paperNotificationService.sendCreateNotification(newPaper);
eventService.createFromPaper(newPaper);
return newPaper;
}
private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException {
paper.setComment(paperDto.getComment());
paper.setUrl(paperDto.getUrl());
paper.setLatexText(paperDto.getLatexText());
paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate());
paper.setLocked(paperDto.getLocked());
paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus());
@ -141,7 +144,7 @@ public class PaperService {
return paper;
}
private List<Reference> saveOrCreateReferences(List<ReferenceDto> references) {
public List<Reference> saveOrCreateReferences(List<ReferenceDto> references) {
return references
.stream()
.filter(reference -> !reference.getDeleted())
@ -150,15 +153,15 @@ public class PaperService {
}
@Transactional
private Reference updateReference(ReferenceDto referenceDto) {
Reference updateReference = referenceRepository.getOne(referenceDto.getId());
public Reference updateReference(ReferenceDto referenceDto) {
Reference updateReference = referenceRepository.findOne(referenceDto.getId());
copyFromDto(updateReference, referenceDto);
referenceRepository.save(updateReference);
return updateReference;
}
@Transactional
private Reference createReference(ReferenceDto referenceDto) {
public Reference createReference(ReferenceDto referenceDto) {
Reference newReference = new Reference();
copyFromDto(newReference, referenceDto);
newReference = referenceRepository.save(newReference);
@ -178,7 +181,7 @@ public class PaperService {
@Transactional
public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.getOne(paperDto.getId());
Paper paper = paperRepository.findOne(paperDto.getId());
Paper.PaperStatus oldStatus = paper.getStatus();
Set<User> oldAuthors = new HashSet<>(paper.getAuthors());
@ -203,34 +206,16 @@ public class PaperService {
if (paper.getStatus() != oldStatus) {
paperNotificationService.statusChangeNotification(paper, oldStatus);
activityService.createActivity(new ArrayList<>(paper.getAuthors()), paper.getCommonActivityState());
}
return paper.getId();
}
@Transactional
public Integer update(Paper newPaper) {
Paper oldPaper = paperRepository.getOne(newPaper.getId());
Paper.PaperStatus oldStatus = oldPaper.getStatus();
Set<User> oldAuthors = new HashSet<>(oldPaper.getAuthors());
newPaper.setUpdateDate(new Date());
newPaper = paperRepository.save(newPaper);
for (User author : newPaper.getAuthors()) {
if (!oldAuthors.contains(author)) {
paperNotificationService.sendCreateNotification(newPaper);
}
}
if (newPaper.getStatus() != oldStatus) {
paperNotificationService.statusChangeNotification(newPaper, oldStatus);
}
return newPaper.getId();
}
@Transactional
public void delete(Integer paperId) {
delete(paperRepository.getOne(paperId));
Paper paper = paperRepository.findOne(paperId);
paperRepository.delete(paper);
}
public List<Paper.PaperStatus> getPaperStatuses() {
@ -262,7 +247,9 @@ public class PaperService {
paper = paperRepository.save(paper);
paperNotificationService.sendCreateNotification(paper);
eventService.createFromPaper(paper);
activityService.createActivity(new ArrayList<>(paper.getAuthors()), paper.getCommonActivityState());
return paper;
}
@ -313,27 +300,19 @@ public class PaperService {
}
}
public void save(Paper paper) {
if (isEmpty(paper.getId())) {
create(paper);
} else {
update(paper);
}
}
public PaperDto findById(Integer paperId) {
return new PaperDto(paperRepository.getOne(paperId));
return new PaperDto(paperRepository.findOne(paperId));
}
public Paper findPaperById(Integer paperId) {
return paperRepository.getOne(paperId);
return paperRepository.findOne(paperId);
}
public List<Paper> findAllNotSelect(List<Integer> paperIds) {
if (!paperIds.isEmpty()) {
return sortPapers(paperRepository.findByIdNotInAndConferenceIsNullAndStatusNot(paperIds, COMPLETED));
return sortPapers(paperRepository.findByIdNotInAndConferencesIsNullAndStatusNot(paperIds, COMPLETED));
} else {
return sortPapers(paperRepository.findByConferenceIsNullAndStatusNot(COMPLETED));
return sortPapers(paperRepository.findByConferencesIsNullAndStatusNot(COMPLETED));
}
}
@ -387,7 +366,7 @@ public class PaperService {
.collect(Collectors.toList()));
}
private String getGostReference(ReferenceDto referenceDto) {
public String getGostReference(ReferenceDto referenceDto) {
return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.",
referenceDto.getAuthors(),
referenceDto.getPublicationTitle(),
@ -397,7 +376,7 @@ public class PaperService {
StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + ".");
}
private String getSpringerReference(ReferenceDto referenceDto) {
public String getSpringerReference(ReferenceDto referenceDto) {
return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}",
referenceDto.getAuthors(),
referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "",
@ -424,22 +403,4 @@ public class PaperService {
public void ping(int paperId) throws IOException {
pingService.addPing(findPaperById(paperId));
}
public void createByTitle(String newPaperTitle) {
Paper paper = new Paper();
paper.setTitle(newPaperTitle);
paper.setStatus(DRAFT);
paper.getAuthors().add(userService.getCurrentUser());
paper.getDeadlines().add(deadlineService.createWithOffset(new Date(), 1, ChronoUnit.WEEKS));
create(paper);
}
public void delete(List<Paper> papers) {
papers.forEach(paper -> delete(paper));
}
public void delete(Paper paper) {
deadlineService.delete(paper.getDeadlines());
paperRepository.delete(paper);
}
}

View File

@ -1,17 +1,8 @@
package ru.ulstu.ping.model;
import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorType;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import org.hibernate.annotations.Any;
import org.hibernate.annotations.AnyDiscriminator;
import org.hibernate.annotations.AnyDiscriminatorValue;
import org.hibernate.annotations.AnyKeyJavaClass;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity;
@ -21,6 +12,14 @@ import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project;
import ru.ulstu.user.model.User;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
@Entity
@ -37,15 +36,20 @@ public class Ping extends BaseEntity {
@Column(name = "activity_type", insertable = false, updatable = false)
private String activityType;
@Any
@AnyDiscriminator(DiscriminatorType.STRING)
@AnyKeyJavaClass(Integer.class)
@Any(
metaColumn = @Column(name = "activity_type"),
fetch = FetchType.LAZY
)
@AnyMetaDef(
idType = "integer", metaType = "string",
metaValues = {
@MetaValue(targetEntity = Conference.class, value = "CONFERENCE"),
@MetaValue(targetEntity = Paper.class, value = "PAPER"),
@MetaValue(targetEntity = Project.class, value = "PROJECT"),
@MetaValue(targetEntity = Grant.class, value = "GRANT")
}
)
@JoinColumn(name = "activity_id")
@Column(name = "activity_type")
@AnyDiscriminatorValue(entity = Conference.class, discriminator = "CONFERENCE")
@AnyDiscriminatorValue(entity = Paper.class, discriminator = "PAPER")
@AnyDiscriminatorValue(entity = Project.class, discriminator = "PROJECT")
@AnyDiscriminatorValue(entity = Grant.class, discriminator = "GRANT")
private UserActivity activity;
public Ping() {

View File

@ -1,5 +1,6 @@
package ru.ulstu.ping.service;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
@ -14,7 +15,6 @@ import ru.ulstu.user.service.MailService;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
@ -51,8 +51,8 @@ public class PingScheduler {
}
for (PingInfo pingInfo : pingInfos) {
mailService.sendEmailFromTemplate(Map.of("pings", pingInfo.getPings()),
pingInfo.getUser(), "pingsInfoWeekEmail", PING_MAIL_SUBJECT);
mailService.sendEmailFromTemplate(ImmutableMap.of("pings", pingInfo.getPings()),
pingInfo.getUser(), "pingsInfoWeekEmail", PING_MAIL_SUBJECT);
}
}
}

View File

@ -17,18 +17,20 @@ import java.util.List;
public class PingService {
private final PingRepository pingRepository;
private final UserService userService;
private final PingScheduler pingScheduler;
public PingService(PingRepository pingRepository,
UserService userService,
PingScheduler pingScheduler) {
this.pingRepository = pingRepository;
this.userService = userService;
this.pingScheduler = pingScheduler;
}
@Transactional
public Ping addPing(UserActivity activity) throws IOException {
Ping newPing = new Ping(new Date(), userService.getCurrentUser());
//newPing.setActivity(activity);
newPing.setActivity(activity);
return pingRepository.save(newPing);
}

View File

@ -1,7 +1,5 @@
package ru.ulstu.project.controller;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@ -18,7 +16,9 @@ import ru.ulstu.project.model.Project;
import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.project.service.ProjectService;
import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@ -27,7 +27,7 @@ import static org.springframework.util.StringUtils.isEmpty;
@Controller()
@RequestMapping(value = "/projects")
@Hidden
@ApiIgnore
public class ProjectController {
private final ProjectService projectService;

View File

@ -1,20 +1,8 @@
package ru.ulstu.project.model;
import jakarta.persistence.CascadeType;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity;
@ -22,8 +10,21 @@ import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileData;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.activity.model.Activity;
import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@ -42,7 +43,7 @@ public class Project extends BaseEntity implements UserActivity, EventSource {
CLOSED("Закрыт"),
FAILED("Провалены сроки");
private final String statusName;
private String statusName;
ProjectStatus(String statusName) {
this.statusName = statusName;
@ -106,6 +107,17 @@ public class Project extends BaseEntity implements UserActivity, EventSource {
event.setProject(this);
}
public Activity.ActivityState getCommonActivityState() {
switch (this.status) {
case IN_WORK:
return Activity.ActivityState.TOOK_IN_WORK;
case CLOSED:
return Activity.ActivityState.COMPLETED;
default:
return null;
}
}
public void setTitle(String title) {
this.title = title;
}

View File

@ -2,7 +2,7 @@ package ru.ulstu.project.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.NotEmpty;
import org.thymeleaf.util.StringUtils;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.file.model.FileDataDto;

View File

@ -3,6 +3,7 @@ package ru.ulstu.project.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;
import ru.ulstu.activity.service.ActivityService;
import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto;
import ru.ulstu.file.service.FileService;
@ -17,6 +18,7 @@ import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@ -37,14 +39,15 @@ public class ProjectService {
private final EventService eventService;
private final UserService userService;
private final PingService pingService;
private final ActivityService activityService;
public ProjectService(ProjectRepository projectRepository,
DeadlineService deadlineService,
GrantRepository grantRepository,
FileService fileService,
EventService eventService,
UserService userService,
PingService pingService) {
PingService pingService,
ActivityService activityService) {
this.projectRepository = projectRepository;
this.deadlineService = deadlineService;
this.grantRepository = grantRepository;
@ -52,6 +55,7 @@ public class ProjectService {
this.eventService = eventService;
this.userService = userService;
this.pingService = pingService;
this.activityService = activityService;
}
public List<Project> findAll() {
@ -65,7 +69,7 @@ public class ProjectService {
}
public ProjectDto findOneDto(Integer id) {
return new ProjectDto(projectRepository.getOne(id));
return new ProjectDto(projectRepository.findOne(id));
}
public List<Project.ProjectStatus> getProjectStatuses() {
@ -77,12 +81,17 @@ public class ProjectService {
Project newProject = copyFromDto(new Project(), projectDto);
newProject = projectRepository.save(newProject);
eventService.createFromObject(newProject, Collections.emptyList(), false, "проекта");
activityService.createActivity(new ArrayList<>(newProject.getExecutors()), newProject.getCommonActivityState());
return newProject;
}
@Transactional
private Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.getOne(projectDto.getId());
public Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.findOne(projectDto.getId());
if (project.getStatus() != projectDto.getStatus()) {
activityService.createActivity(new ArrayList<>(project.getExecutors()), project.getCommonActivityState());
}
projectRepository.save(copyFromDto(project, projectDto));
eventService.updateProjectDeadlines(project);
for (FileDataDto file : projectDto.getFiles().stream()
@ -95,8 +104,8 @@ public class ProjectService {
@Transactional
public boolean delete(Integer projectId) throws IOException {
if (projectRepository.existsById(projectId)) {
Project project = projectRepository.getOne(projectId);
if (projectRepository.exists(projectId)) {
Project project = projectRepository.findOne(projectId);
projectRepository.delete(project);
return true;
}
@ -108,7 +117,7 @@ public class ProjectService {
project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus());
project.setTitle(projectDto.getTitle());
if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) {
project.setGrant(grantRepository.getOne(projectDto.getGrant().getId()));
project.setGrant(grantRepository.findOne(projectDto.getGrant().getId()));
}
project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
@ -139,11 +148,12 @@ public class ProjectService {
}
public Project findById(Integer id) {
return projectRepository.getOne(id);
return projectRepository.findOne(id);
}
public List<User> getProjectExecutors(ProjectDto projectDto) {
return userService.findAll();
List<User> users = userService.findAll();
return users;
}
@Transactional
@ -152,11 +162,12 @@ public class ProjectService {
}
public List<GrantDto> getAllGrants() {
return convert(grantRepository.findAll(), GrantDto::new);
List<GrantDto> grants = convert(grantRepository.findAll(), GrantDto::new);
return grants;
}
private List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAllById(grantIds), GrantDto::new);
public List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAll(grantIds), GrantDto::new);
}
public void attachGrant(ProjectDto projectDto) {

View File

@ -11,7 +11,7 @@ public abstract class EntityCreateStrategy<T extends UserActivity> {
protected abstract void createEntity(User user);
private void createDefaultEntityIfNeed(List<User> allUsers, List<? extends UserActivity> entities) {
protected void createDefaultEntityIfNeed(List<User> allUsers, List<? extends UserActivity> entities) {
allUsers.forEach(user -> {
if (entities
.stream()

View File

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

View File

@ -1,7 +1,5 @@
package ru.ulstu.students.controller;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
@ -17,7 +15,9 @@ import ru.ulstu.students.model.TaskDto;
import ru.ulstu.students.model.TaskFilterDto;
import ru.ulstu.students.service.TaskService;
import ru.ulstu.tags.model.Tag;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
@ -29,7 +29,7 @@ import static ru.ulstu.students.controller.Navigation.TASK_PAGE;
@Controller()
@RequestMapping(value = "/students")
@Hidden
@ApiIgnore
public class TaskController {
private final TaskService taskService;

View File

@ -1,14 +1,14 @@
package ru.ulstu.students.model;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
@Entity

View File

@ -1,28 +1,30 @@
package ru.ulstu.students.model;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.validation.constraints.NotBlank;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.tags.model.Tag;
import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
@ -37,7 +39,7 @@ public class Task extends BaseEntity implements EventSource {
FAILED("Провалены сроки"),
LOADED_FROM_KIAS("Загружен автоматически");
private final String statusName;
private String statusName;
TaskStatus(String name) {
this.statusName = name;
@ -53,10 +55,17 @@ public class Task extends BaseEntity implements EventSource {
private String description;
@Transient
private UserService userService;
public Task() {
}
public Task(UserService userService) {
this.userService = userService;
}
@Enumerated(value = EnumType.STRING)
private TaskStatus status = TaskStatus.IN_WORK;

View File

@ -2,8 +2,8 @@ package ru.ulstu.students.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotEmpty;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.tags.model.Tag;

View File

@ -11,16 +11,16 @@ import java.util.List;
public interface TaskRepository extends JpaRepository<Task, Integer> {
@Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY t.createDate DESC")
@Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date DESC")
List<Task> filterNew(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag);
@Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY t.createDate ASC")
@Query("SELECT t FROM Task t WHERE (t.status = :status OR :status IS NULL) AND (:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date ASC")
List<Task> filterOld(@Param("status") Task.TaskStatus status, @Param("tag") Tag tag);
@Query("SELECT t FROM Task t WHERE(:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY t.createDate DESC")
@Query("SELECT t FROM Task t WHERE(:tag IS NULL OR :tag MEMBER OF t.tags) ORDER BY create_date DESC")
List<Task> findByTag(@Param("tag") Tag tag);
@Query("SELECT t FROM Task t WHERE (t.createDate >= :date) ORDER BY t.createDate DESC")
@Query("SELECT t FROM Task t WHERE (t.createDate >= :date) ORDER BY create_date DESC")
List<Task> findAllYear(@Param("date") Date date);

View File

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

View File

@ -55,7 +55,7 @@ public class TaskService {
}
public List<Task> findAll() {
return taskRepository.findAll(Sort.by(Sort.Direction.DESC, "createDate"));
return taskRepository.findAll(new Sort(Sort.Direction.DESC, "createDate"));
}
public List<TaskDto> findAllDto() {
@ -65,7 +65,7 @@ public class TaskService {
}
public TaskDto findOneDto(Integer id) {
return new TaskDto(taskRepository.getOne(id));
return new TaskDto(taskRepository.findOne(id));
}
public List<TaskDto> filter(TaskFilterDto filterDto) {
@ -101,8 +101,8 @@ public class TaskService {
}
@Transactional
private Integer update(TaskDto taskDto) throws IOException {
Task task = taskRepository.getOne(taskDto.getId());
public Integer update(TaskDto taskDto) throws IOException {
Task task = taskRepository.findOne(taskDto.getId());
taskRepository.save(copyFromDto(task, taskDto));
eventService.updateTaskDeadlines(task);
return task.getId();
@ -110,13 +110,13 @@ public class TaskService {
@Transactional
public boolean delete(Integer taskId) throws IOException {
if (taskRepository.existsById(taskId)) {
Task scheduleTask = taskRepository.getOne(taskId);
if (taskRepository.exists(taskId)) {
Task scheduleTask = taskRepository.findOne(taskId);
Scheduler sch = schedulerRepository.findOneByTask(scheduleTask);
if (sch != null) {
schedulerRepository.deleteById(sch.getId());
schedulerRepository.delete(sch.getId());
}
taskRepository.deleteById(taskId);
taskRepository.delete(taskId);
return true;
}
return false;

View File

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

View File

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

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