Compare commits

...

129 Commits

Author SHA1 Message Date
romanov73 70c2ab3f8c Изменил(а) на 'README.md' 1 month ago
romanov73 9c2fcef028 Изменил(а) на 'README.md' 1 month ago
Anton Romanov 0a8a5f2df4 Remember me 2 months ago
Anton Romanov 7713078596 Fix header 2 months ago
Anton Romanov e6b4ed9f2c #247 -- Fix paper dates 2 months ago
Anton Romanov 6dc88fdada #247 -- Fix html 2 months ago
Anton Romanov 234b043d72 #247 -- Fix jenkinsfile 2 months ago
Anton Romanov f522ed9b81 #247 -- Fail test 2 months ago
Anton Romanov 6f6a8b0eac #247 -- Fix jenkinsfile 2 months ago
Anton Romanov eb5ad650c9 #247 -- Fix jenkinsfile 2 months ago
Anton Romanov 9274dfc3d0 #247 -- Fix test 2 months ago
Anton Romanov 41b5d42330 #247 -- Add failed test 2 months ago
Anton Romanov c6c0db0232 #247 -- Add failed test 2 months ago
Anton Romanov 6a04b5e037 #247 -- Add test class 2 months ago
Anton Romanov a9c617075f #247 -- Fix jenkins file 2 months ago
romanov73 db4620694c Merge pull request '#247 Remove primefaces dependency' (#248) from 247-restore-mvc into dev
Reviewed-on: #248
2 months ago
Anton Romanov 70c950cdd7 #247 -- Add jenkinsfile 2 months ago
Anton Romanov a9e8336986 #247 -- Fix jpa mapping, update springdoc 2 months ago
Anton Romanov 23797bae9e #247 -- Update spring version, gradle version 2 months ago
Anton Romanov 37c1d0db08 Add user ids 2 months ago
Anton Romanov b49adee62a Add user ids 2 months ago
Anton Romanov c8382c4aea #247 -- Fix html 2 months ago
Anton Romanov 6e40343d6c #247 -- Remove latex and fix paper list 2 months ago
Anton Romanov 55a76daa5a #247 -- Restore mvc 3 months ago
Anton Romanov 5371df1f50 #247 Remove primefaces dependency 3 months ago
Anton Romanov 4ab3637d9c Update README.md 4 years ago
Anton Romanov 893f7ae1f2 add timetable url 4 years ago
Anton Romanov 06f657f5c2 add timetable url 4 years ago
Anton Romanov b13f331f2c fix urls 4 years ago
Anton Romanov 12973109d3 fix params 4 years ago
Anton Romanov 278e2135bb paper to conference 4 years ago
Anton Romanov b662437afe add conferences 4 years ago
Anton Romanov 5ae17fbe83 fix select all 4 years ago
Anton Romanov 3f16c8a078 fix user date 4 years ago
Anton Romanov e3da8c710f fix sout 4 years ago
Anton Romanov 54b992a7f3 try to fix grants kias 4 years ago
Anton Romanov e20fb468f9 fix 4 years ago
Anton Romanov 1a3ffb7bab fix params and hrefs 4 years ago
Anton Romanov d29416fb76 fix deploy script 4 years ago
Anton Romanov 37053d853b Merge branch 'jsf' into 'dev'
Jsf

See merge request romanov73/ng-tracker!119
4 years ago
Anton Romanov b961c8e3dc fix checkstyle 4 years ago
Anton Romanov 3dd6210f42 fix checkstyle 4 years ago
Anton Romanov 5520f19357 show grants 4 years ago
Anton Romanov 2cc3008dc5 complete dashboard 4 years ago
Anton Romanov 708a1a6d32 add dynamic deadlines 4 years ago
Anton Romanov 751195bf96 some layout fixes 4 years ago
Anton Romanov 6adb3fec71 Merge remote-tracking branch 'origin/jsf' into jsf
# Conflicts:
#	src/main/resources/META-INF/resources/admin/user.xhtml
4 years ago
Anton Romanov ae0a1f3532 fix layout 4 years ago
Anton Romanov e167a68bc6 add conference button 4 years ago
Anton Romanov 6b717f26d3 fix selection 4 years ago
Anton Romanov b20ab96b55 fix check unique name of grant 4 years ago
Anton Romanov 2c55293e0e fix check unique name of grant 4 years ago
Anton Romanov a14735699c fix date parsing 4 years ago
Anton Romanov 9f21850767 move patronymic field 4 years ago
Anton Romanov abde7f311c fix user page 4 years ago
Anton Romanov 5333258c62 login field 4 years ago
Anton Romanov 2149dfd32f save user 4 years ago
Anton Romanov 34c5e79cbb edit user 4 years ago
Anton Romanov 2110c21be7 fix editor 4 years ago
Anton Romanov 30e06335e9 fix logo 4 years ago
Anton Romanov c528711431 fix logo 4 years ago
Anton Romanov 0bb9768bda create on submit 4 years ago
Anton Romanov 52d6210875 hide pagination 4 years ago
Anton Romanov 65569732d6 show message on delete 4 years ago
Anton Romanov 1d0c90d932 confirm delete 4 years ago
Anton Romanov 440def2b71 fix layout 4 years ago
Anton Romanov 1460e26127 remove papers 4 years ago
Anton Romanov 1f5cde4b66 relax checkstyle 4 years ago
Anton Romanov 10a99d42cf add delete papers button 4 years ago
Anton Romanov 90c11c6946 show details 4 years ago
Anton Romanov 134f75666c Merge remote-tracking branch 'origin/jsf' into jsf 4 years ago
Anton Romanov b8d492724c image 4 years ago
Anton Romanov bc48a486ee quick add paper 4 years ago
Anton Romanov c36876f7e7 style 4 years ago
Anton Romanov a136acb0b4 show users 5 years ago
Anton Romanov 7d1f5e9059 fix codestyle 5 years ago
Anton Romanov 4c4c1b2015 fix template 5 years ago
Anton Romanov 6b90d7b0c0 fix messages 5 years ago
Anton Romanov fa03edf32d fix messages 5 years ago
Anton Romanov 4e1d99392a fix dependency 5 years ago
Anton Romanov ac55481bc6 add oauth2 google 5 years ago
Anton Romanov 71448364d7 fix login / logout 5 years ago
Anton Romanov c57914db7c auth 5 years ago
Anton Romanov ab20b3843f fix font size 5 years ago
Anton Romanov 268a311a87 add filter 5 years ago
Anton Romanov a67eb23714 send all developer letters to romanov73 5 years ago
Anton Romanov 5ee1f33de1 add papers dashboard 5 years ago
Anton Romanov 107ddb90ac add side commands 5 years ago
Anton Romanov ac6bd13c6c show label for paper status 5 years ago
Anton Romanov e7061f4545 fix columns 5 years ago
Anton Romanov d741bd019a display authors 5 years ago
Anton Romanov 846d94bb46 display paper comment 5 years ago
Anton Romanov 5755cf2f92 save paper 5 years ago
Anton Romanov 7587ff7a51 show paper type 5 years ago
Anton Romanov 6c220355ee display some of paper 5 years ago
Anton Romanov 779f286988 add some menu 5 years ago
Anton Romanov 7753dd104c show paper page 5 years ago
Anton Romanov 48955b9cfd show paper statuses 5 years ago
Anton Romanov 9665653234 show paper list 5 years ago
Anton Romanov 04f545db1c show paper list 5 years ago
Anton Romanov 746f443931 fix primefaces repo 5 years ago
Anton Romanov 1be74769bf fix ports and dependencies 5 years ago
Anton Romanov 2cdec4bcda jsf initial 5 years ago
Anton Romanov a17dac55e2 fix jdk 5 years ago
Anton Romanov 9e6993f136 Merge branch 'move-to-jdk11' into 'dev'
update versions

Closes #73

See merge request romanov73/ng-tracker!34
5 years ago
Anton Romanov 0647438bfb #73 fix jdk 5 years ago
Anton Romanov 41c4ee7997 fix htmlunit js errors 5 years ago
Anton Romanov 9d3ee273f6 fix spring boot version 5 years ago
Anton Romanov 3267138524 fix warnings 5 years ago
Anton Romanov df1bf873ff fix warnings 5 years ago
Anton Romanov 24f447aed7 fix tests 5 years ago
Anton Romanov 36c4e52e37 Merge branch 'dev' into move-to-jdk11
# Conflicts:
#	src/main/java/ru/ulstu/conference/service/ConferenceService.java
#	src/main/java/ru/ulstu/grant/model/Grant.java
#	src/main/java/ru/ulstu/grant/service/GrantService.java
#	src/main/java/ru/ulstu/paper/model/Paper.java
#	src/main/java/ru/ulstu/paper/service/PaperService.java
#	src/main/java/ru/ulstu/project/model/Project.java
#	src/main/java/ru/ulstu/project/model/ProjectDto.java
#	src/main/java/ru/ulstu/students/model/Task.java
#	src/main/java/ru/ulstu/students/service/TaskService.java
#	src/main/java/ru/ulstu/timeline/model/Event.java
#	src/main/java/ru/ulstu/timeline/model/EventDto.java
#	src/main/java/ru/ulstu/timeline/service/EventService.java
#	src/main/java/ru/ulstu/user/service/UserService.java
#	src/main/resources/application.properties
#	src/main/resources/db/changelog-master.xml
#	src/main/resources/public/css/conference.css
#	src/main/resources/public/js/conference.js
#	src/main/resources/public/js/tasks.js
#	src/main/resources/templates/conferences/conference.html
#	src/main/resources/templates/grants/grant.html
#	src/main/resources/templates/papers/paper.html
5 years ago
Anton Romanov 529db0442c fix grant dashboard indicators 5 years ago
Anton Romanov db97892af2 fix grant indicators 5 years ago
Anton Romanov ff19001f1f fix grant doubling cause date comparison 5 years ago
Anton Romanov 2012a58fc2 show active grants 5 years ago
Anton Romanov 4d2d7fa113 fix lambda 5 years ago
Anton Romanov 9393fbe326 fix deprecated imports 5 years ago
Anton Romanov 955bdaa438 fix repository method 5 years ago
Anton Romanov 60dfad5d76 Merge branch 'dev' into move-to-jdk11
# Conflicts:
#	src/main/resources/db/changelog-master.xml
5 years ago
Anton Romanov e16b1da761 fix script 5 years ago
Anton Romanov 09cae66ca4 fix image 5 years ago
Anton Romanov 7684bac74d Merge branch 'dev' into move-to-jdk11
# Conflicts:
#	build.gradle
#	src/main/java/ru/ulstu/grant/model/GrantDto.java
#	src/main/java/ru/ulstu/grant/service/GrantService.java
#	src/main/java/ru/ulstu/paper/model/PaperDto.java
#	src/main/java/ru/ulstu/project/model/Project.java
5 years ago
Anton Romanov 2cf3e52596 #73 merge dev into jdk11 5 years ago
Anton Romanov 167de9bf65 #73 fix deprecated parameters 5 years ago
Anton Romanov 993a034527 #73 restore authentication 5 years ago
Anton Romanov 9bd954ea9b #73 fix new thymeleaf syntax 5 years ago
Anton Romanov 1487affb8e #73 fix deprecated annotations and classes 5 years ago
Anton Romanov e74261184f #73 first fixes by update versions 5 years ago

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

19
Jenkinsfile vendored

@ -0,0 +1,19 @@
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])
}
}
}
}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,30 +0,0 @@
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);
}
}
}

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

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

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

@ -1,23 +0,0 @@
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();
}
}

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

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

@ -1,12 +1,12 @@
package ru.ulstu.core.model; 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.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import ru.ulstu.user.error.UserBlockedException; import ru.ulstu.user.error.UserBlockedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
@Component @Component

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

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

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

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

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

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

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

@ -0,0 +1,69 @@
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;
}
}

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

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

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

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

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

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

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

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

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

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

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

@ -1,8 +1,22 @@
package ru.ulstu.grant.model; 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.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource; import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity; import ru.ulstu.core.model.UserActivity;
@ -13,20 +27,6 @@ import ru.ulstu.project.model.Project;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.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.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
@ -41,24 +41,30 @@ import java.util.Set;
@DiscriminatorValue("GRANT") @DiscriminatorValue("GRANT")
public class Grant extends BaseEntity implements UserActivity, EventSource { public class Grant extends BaseEntity implements UserActivity, EventSource {
public enum GrantStatus { public enum GrantStatus {
APPLICATION("Заявка"), APPLICATION("Заявка", "text-draft"),
ON_COMPETITION("Отправлен на конкурс"), ON_COMPETITION("Отправлен на конкурс", "text-review"),
SUCCESSFUL_PASSAGE("Успешное прохождение"), SUCCESSFUL_PASSAGE("Успешное прохождение", "text-accepted"),
IN_WORK("В работе"), IN_WORK("В работе", "text-primary"),
COMPLETED("Завершен"), COMPLETED("Завершен", "text-success"),
FAILED("Провалены сроки"), FAILED("Провалены сроки", "text-failed"),
LOADED_FROM_KIAS("Загружен автоматически"), LOADED_FROM_KIAS("Загружен автоматически", "text-warning"),
SKIPPED("Не интересует"); SKIPPED("Не интересует", "text-not-accepted");
private String statusName; private final String statusName;
private final String elementClass;
GrantStatus(String statusName) {
GrantStatus(String statusName, String elementClass) {
this.statusName = statusName; this.statusName = statusName;
this.elementClass = elementClass;
} }
public String getStatusName() { public String getStatusName() {
return statusName; return statusName;
} }
public String getElementClass() {
return elementClass;
}
} }
@NotBlank @NotBlank

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

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

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

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

@ -5,9 +5,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.ParseException;
@Service @Service
public class GrantScheduler { public class GrantScheduler {
private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true;
@ -27,18 +24,18 @@ public class GrantScheduler {
@Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara") @Scheduled(cron = "0 0 8 * * MON", zone = "Europe/Samara")
public void checkDeadlineBeforeWeek() { public void checkDeadlineBeforeWeek() {
log.debug("GrantScheduler.checkDeadlineBeforeWeek started"); log.debug("GrantScheduler.checkDeadlineBeforeWeek started");
grantNotificationService.sendDeadlineNotifications(grantService.findAll(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK); grantNotificationService.sendDeadlineNotifications(grantService.findAllActive(), IS_DEADLINE_NOTIFICATION_BEFORE_WEEK);
log.debug("GrantScheduler.checkDeadlineBeforeWeek finished"); log.debug("GrantScheduler.checkDeadlineBeforeWeek finished");
} }
@Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara") @Scheduled(cron = "0 0 8 * * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() { public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started"); log.debug("GrantScheduler.loadGrantsFromKias started");
try { // try {
grantService.createFromKias(); // grantService.createFromKias();
} catch (ParseException | IOException e) { // } catch (ParseException | IOException e) {
e.printStackTrace(); // e.printStackTrace();
} // }
log.debug("GrantScheduler.loadGrantsFromKias finished"); log.debug("GrantScheduler.loadGrantsFromKias finished");
} }
} }

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import ru.ulstu.core.util.DateUtils;
import ru.ulstu.deadline.model.Deadline; import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.deadline.service.DeadlineService; import ru.ulstu.deadline.service.DeadlineService;
import ru.ulstu.file.model.FileDataDto; import ru.ulstu.file.model.FileDataDto;
@ -26,6 +27,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
import java.time.temporal.ChronoUnit;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
@ -78,8 +80,7 @@ public class GrantService extends BaseService {
} }
public GrantDto getExistGrantById(Integer id) { public GrantDto getExistGrantById(Integer id) {
GrantDto grantDto = new GrantDto(findById(id)); return new GrantDto(findById(id));
return grantDto;
} }
public List<Grant> findAll() { public List<Grant> findAll() {
@ -133,7 +134,7 @@ public class GrantService extends BaseService {
} }
@Transactional @Transactional
public Integer update(GrantDto grantDto) throws IOException { private Integer update(GrantDto grantDto) throws IOException {
Grant grant = findById(grantDto.getId()); Grant grant = findById(grantDto.getId());
Set<User> oldAuthors = new HashSet<>(grant.getAuthors()); Set<User> oldAuthors = new HashSet<>(grant.getAuthors());
User oldLeader = grant.getLeader(); User oldLeader = grant.getLeader();
@ -181,7 +182,7 @@ public class GrantService extends BaseService {
filterEmptyDeadlines(grantDto); filterEmptyDeadlines(grantDto);
checkEmptyDeadlines(grantDto, errors); checkEmptyDeadlines(grantDto, errors);
checkEmptyLeader(grantDto, errors); checkEmptyLeader(grantDto, errors);
checkUniqueName(grantDto, errors, grantDto.getId(), "title", "Грант с таким именем уже существует"); checkUniqueName(grantDto, errors, grantDto.getId(), "Грант с таким именем уже существует");
if (errors.hasErrors()) { if (errors.hasErrors()) {
return false; return false;
} }
@ -193,11 +194,11 @@ public class GrantService extends BaseService {
return true; return true;
} }
public boolean saveFromKias(GrantDto grantDto) throws IOException { private boolean saveFromKias(GrantDto grantDto) throws IOException {
grantDto.setName(grantDto.getTitle()); grantDto.setName(grantDto.getTitle());
String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени String title = checkUniqueName(grantDto, grantDto.getId()); //проверка уникальности имени
if (title != null) { if (title != null) {
Grant grantFromDB = grantRepository.findByTitle(title); //грант с таким же названием из бд Grant grantFromDB = grantRepository.findFirstByTitle(title); //грант с таким же названием из бд
if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают if (checkSameDeadline(grantDto, grantFromDB.getId())) { //если дедайны тоже совпадают
return false; return false;
} else { //иначе грант уже был в системе, но в другом году, поэтому надо создать } else { //иначе грант уже был в системе, но в другом году, поэтому надо создать
@ -223,8 +224,8 @@ public class GrantService extends BaseService {
} }
private boolean checkSameDeadline(GrantDto grantDto, Integer id) { private boolean checkSameDeadline(GrantDto grantDto, Integer id) {
Date date = grantDto.getDeadlines().get(0).getDate(); //дата с сайта киас Date date = DateUtils.clearTime(grantDto.getDeadlines().get(0).getDate()); //дата с сайта киас
Date foundGrantDate = deadlineService.findByGrantIdAndDate(id, date); Date foundGrantDate = DateUtils.clearTime(deadlineService.findByGrantIdAndDate(id, date));
return foundGrantDate != null && foundGrantDate.compareTo(date) == 0; return foundGrantDate != null && foundGrantDate.compareTo(date) == 0;
} }
@ -326,16 +327,77 @@ public class GrantService extends BaseService {
return convert(findAllActive(), GrantDto::new); return convert(findAllActive(), GrantDto::new);
} }
private List<Grant> findAllActive() { public List<Grant> findAllActive() {
return grantRepository.findAllActive(); return grantRepository.findAllActive();
} }
public Grant findById(Integer id) { public Grant findById(Integer id) {
return grantRepository.findOne(id); return grantRepository.getOne(id);
} }
@Transactional @Transactional
public void ping(int grantId) throws IOException { public void ping(int grantId) throws IOException {
pingService.addPing(findById(grantId)); 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);
}
} }

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

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

@ -0,0 +1,25 @@
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;
}
}

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

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

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

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

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

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

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

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

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

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

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

@ -1,8 +1,7 @@
package ru.ulstu.paper.controller; package ru.ulstu.paper.controller;
import org.springframework.http.HttpHeaders; import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.http.HttpStatus; import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
@ -17,27 +16,20 @@ import ru.ulstu.paper.model.AutoCompleteData;
import ru.ulstu.paper.model.Paper; import ru.ulstu.paper.model.Paper;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
import ru.ulstu.paper.model.PaperListDto; import ru.ulstu.paper.model.PaperListDto;
import ru.ulstu.paper.model.ReferenceDto;
import ru.ulstu.paper.service.LatexService; import ru.ulstu.paper.service.LatexService;
import ru.ulstu.paper.service.PaperService; import ru.ulstu.paper.service.PaperService;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import java.io.IOException; import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.springframework.util.StringUtils.isEmpty;
@Controller() @Controller()
@RequestMapping(value = "/papers") @RequestMapping(value = "/papers")
@ApiIgnore @Hidden
public class PaperController { public class PaperController {
private final PaperService paperService; private final PaperService paperService;
private final ConferenceService conferenceService; private final ConferenceService conferenceService;
@ -76,7 +68,7 @@ public class PaperController {
} }
@GetMapping("/paper") @GetMapping("/paper")
public void getPapers(ModelMap modelMap, @RequestParam(value = "id") Integer id) { public void getPaper(ModelMap modelMap, @RequestParam(value = "id") Integer id) {
if (id != null && id > 0) { if (id != null && id > 0) {
modelMap.put("paperDto", paperService.findOneDto(id)); modelMap.put("paperDto", paperService.findOneDto(id));
} else { } else {
@ -107,15 +99,6 @@ public class PaperController {
return "/papers/paper"; 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") @ModelAttribute("allStatuses")
public List<Paper.PaperStatus> getPaperStatuses() { public List<Paper.PaperStatus> getPaperStatuses() {
return paperService.getPaperStatuses(); return paperService.getPaperStatuses();
@ -140,29 +123,6 @@ public class PaperController {
return years; 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") @ModelAttribute("autocompleteData")
public AutoCompleteData getAutocompleteData() { public AutoCompleteData getAutocompleteData() {
return paperService.getAutoCompleteData(); return paperService.getAutoCompleteData();
@ -170,7 +130,7 @@ public class PaperController {
private void filterEmptyDeadlines(PaperDto paperDto) { private void filterEmptyDeadlines(PaperDto paperDto) {
paperDto.setDeadlines(paperDto.getDeadlines().stream() paperDto.setDeadlines(paperDto.getDeadlines().stream()
.filter(dto -> dto.getDate() != null || !isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !dto.getDescription().isEmpty())
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
} }

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

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

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

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

@ -1,12 +1,11 @@
package ru.ulstu.paper.model; 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 ru.ulstu.core.model.BaseEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
@Entity @Entity
public class Reference extends BaseEntity { public class Reference extends BaseEntity {

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

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

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

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

@ -22,6 +22,7 @@ import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.time.temporal.ChronoUnit;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -80,9 +81,7 @@ public class PaperService {
} }
public List<PaperDto> findAllDto() { public List<PaperDto> findAllDto() {
List<PaperDto> papers = convert(findAll(), PaperDto::new); return convert(findAll(), PaperDto::new);
papers.forEach(paperDto -> paperDto.setTitle(StringUtils.abbreviate(paperDto.getTitle(), MAX_DISPLAY_SIZE)));
return papers;
} }
public List<Paper> findAllActive() { public List<Paper> findAllActive() {
@ -92,35 +91,38 @@ public class PaperService {
.collect(toList()); .collect(toList());
} }
public List<Paper> findAllActiveByCurrentUser() {
return findAllActive()
.stream()
.filter(paper -> paper.getAuthors().contains(userService.getCurrentUser()))
.collect(toList());
}
public List<PaperDto> findAllActiveDto() { public List<PaperDto> findAllActiveDto() {
return convert(findAllActive(), PaperDto::new); return convert(findAllActive(), PaperDto::new);
} }
public PaperDto findOneDto(Integer id) { public PaperDto findOneDto(Integer id) {
return new PaperDto(paperRepository.findOne(id)); return new PaperDto(paperRepository.findById(id).orElseThrow());
} }
@Transactional @Transactional
public Integer create(PaperDto paperDto) throws IOException { public Integer create(PaperDto paperDto) throws IOException {
Paper newPaper = copyFromDto(new Paper(), paperDto); Paper newPaper = copyFromDto(new Paper(), paperDto);
newPaper = paperRepository.save(newPaper); return create(newPaper).getId();
paperNotificationService.sendCreateNotification(newPaper);
eventService.createFromPaper(newPaper);
return newPaper.getId();
} }
@Transactional @Transactional
public Paper create(Paper paper) { public Paper create(Paper paper) {
Paper newPaper = paperRepository.save(paper); Paper newPaper = paperRepository.save(paper);
newPaper.setCreateDate(new Date());
paperNotificationService.sendCreateNotification(newPaper); paperNotificationService.sendCreateNotification(newPaper);
eventService.createFromPaper(newPaper);
return newPaper; return newPaper;
} }
private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException { private Paper copyFromDto(Paper paper, PaperDto paperDto) throws IOException {
paper.setComment(paperDto.getComment()); paper.setComment(paperDto.getComment());
paper.setUrl(paperDto.getUrl()); paper.setUrl(paperDto.getUrl());
paper.setLatexText(paperDto.getLatexText());
paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate()); paper.setCreateDate(paper.getCreateDate() == null ? new Date() : paper.getCreateDate());
paper.setLocked(paperDto.getLocked()); paper.setLocked(paperDto.getLocked());
paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus()); paper.setStatus(paperDto.getStatus() == null ? DRAFT : paperDto.getStatus());
@ -139,7 +141,7 @@ public class PaperService {
return paper; return paper;
} }
public List<Reference> saveOrCreateReferences(List<ReferenceDto> references) { private List<Reference> saveOrCreateReferences(List<ReferenceDto> references) {
return references return references
.stream() .stream()
.filter(reference -> !reference.getDeleted()) .filter(reference -> !reference.getDeleted())
@ -148,15 +150,15 @@ public class PaperService {
} }
@Transactional @Transactional
public Reference updateReference(ReferenceDto referenceDto) { private Reference updateReference(ReferenceDto referenceDto) {
Reference updateReference = referenceRepository.findOne(referenceDto.getId()); Reference updateReference = referenceRepository.getOne(referenceDto.getId());
copyFromDto(updateReference, referenceDto); copyFromDto(updateReference, referenceDto);
referenceRepository.save(updateReference); referenceRepository.save(updateReference);
return updateReference; return updateReference;
} }
@Transactional @Transactional
public Reference createReference(ReferenceDto referenceDto) { private Reference createReference(ReferenceDto referenceDto) {
Reference newReference = new Reference(); Reference newReference = new Reference();
copyFromDto(newReference, referenceDto); copyFromDto(newReference, referenceDto);
newReference = referenceRepository.save(newReference); newReference = referenceRepository.save(newReference);
@ -176,7 +178,7 @@ public class PaperService {
@Transactional @Transactional
public Integer update(PaperDto paperDto) throws IOException { public Integer update(PaperDto paperDto) throws IOException {
Paper paper = paperRepository.findOne(paperDto.getId()); Paper paper = paperRepository.getOne(paperDto.getId());
Paper.PaperStatus oldStatus = paper.getStatus(); Paper.PaperStatus oldStatus = paper.getStatus();
Set<User> oldAuthors = new HashSet<>(paper.getAuthors()); Set<User> oldAuthors = new HashSet<>(paper.getAuthors());
@ -206,10 +208,29 @@ public class PaperService {
return paper.getId(); 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 @Transactional
public void delete(Integer paperId) { public void delete(Integer paperId) {
Paper paper = paperRepository.findOne(paperId); delete(paperRepository.getOne(paperId));
paperRepository.delete(paper);
} }
public List<Paper.PaperStatus> getPaperStatuses() { public List<Paper.PaperStatus> getPaperStatuses() {
@ -292,19 +313,27 @@ public class PaperService {
} }
} }
public void save(Paper paper) {
if (isEmpty(paper.getId())) {
create(paper);
} else {
update(paper);
}
}
public PaperDto findById(Integer paperId) { public PaperDto findById(Integer paperId) {
return new PaperDto(paperRepository.findOne(paperId)); return new PaperDto(paperRepository.getOne(paperId));
} }
public Paper findPaperById(Integer paperId) { public Paper findPaperById(Integer paperId) {
return paperRepository.findOne(paperId); return paperRepository.getOne(paperId);
} }
public List<Paper> findAllNotSelect(List<Integer> paperIds) { public List<Paper> findAllNotSelect(List<Integer> paperIds) {
if (!paperIds.isEmpty()) { if (!paperIds.isEmpty()) {
return sortPapers(paperRepository.findByIdNotInAndConferencesIsNullAndStatusNot(paperIds, COMPLETED)); return sortPapers(paperRepository.findByIdNotInAndConferenceIsNullAndStatusNot(paperIds, COMPLETED));
} else { } else {
return sortPapers(paperRepository.findByConferencesIsNullAndStatusNot(COMPLETED)); return sortPapers(paperRepository.findByConferenceIsNullAndStatusNot(COMPLETED));
} }
} }
@ -358,7 +387,7 @@ public class PaperService {
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public String getGostReference(ReferenceDto referenceDto) { private String getGostReference(ReferenceDto referenceDto) {
return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.", return MessageFormat.format(referenceDto.getReferenceType() == BOOK ? "{0} {1} - {2}{3}. - {4}с." : "{0} {1}{5} {2}{3}. С. {4}.",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationTitle(), referenceDto.getPublicationTitle(),
@ -368,7 +397,7 @@ public class PaperService {
StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + "."); StringUtils.isEmpty(referenceDto.getJournalOrCollectionTitle()) ? "." : " // " + referenceDto.getJournalOrCollectionTitle() + ".");
} }
public String getSpringerReference(ReferenceDto referenceDto) { private String getSpringerReference(ReferenceDto referenceDto) {
return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}", return MessageFormat.format("{0} ({1}) {2}.{3} {4}pp {5}",
referenceDto.getAuthors(), referenceDto.getAuthors(),
referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "", referenceDto.getPublicationYear() != null ? referenceDto.getPublicationYear().toString() : "",
@ -395,4 +424,22 @@ public class PaperService {
public void ping(int paperId) throws IOException { public void ping(int paperId) throws IOException {
pingService.addPing(findPaperById(paperId)); 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);
}
} }

@ -1,8 +1,17 @@
package ru.ulstu.ping.model; 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.Any;
import org.hibernate.annotations.AnyMetaDef; import org.hibernate.annotations.AnyDiscriminator;
import org.hibernate.annotations.MetaValue; import org.hibernate.annotations.AnyDiscriminatorValue;
import org.hibernate.annotations.AnyKeyJavaClass;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
@ -12,14 +21,6 @@ import ru.ulstu.paper.model.Paper;
import ru.ulstu.project.model.Project; import ru.ulstu.project.model.Project;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.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; import java.util.Date;
@Entity @Entity
@ -36,20 +37,15 @@ public class Ping extends BaseEntity {
@Column(name = "activity_type", insertable = false, updatable = false) @Column(name = "activity_type", insertable = false, updatable = false)
private String activityType; private String activityType;
@Any( @Any
metaColumn = @Column(name = "activity_type"), @AnyDiscriminator(DiscriminatorType.STRING)
fetch = FetchType.LAZY @AnyKeyJavaClass(Integer.class)
)
@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") @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; private UserActivity activity;
public Ping() { public Ping() {

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

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

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

@ -1,8 +1,20 @@
package ru.ulstu.project.model; 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.Fetch;
import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchMode;
import org.hibernate.validator.constraints.NotBlank;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.EventSource; import ru.ulstu.core.model.EventSource;
import ru.ulstu.core.model.UserActivity; import ru.ulstu.core.model.UserActivity;
@ -12,18 +24,6 @@ import ru.ulstu.grant.model.Grant;
import ru.ulstu.timeline.model.Event; import ru.ulstu.timeline.model.Event;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
import javax.persistence.CascadeType;
import javax.persistence.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.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
@ -42,7 +42,7 @@ public class Project extends BaseEntity implements UserActivity, EventSource {
CLOSED("Закрыт"), CLOSED("Закрыт"),
FAILED("Провалены сроки"); FAILED("Провалены сроки");
private String statusName; private final String statusName;
ProjectStatus(String statusName) { ProjectStatus(String statusName) {
this.statusName = statusName; this.statusName = statusName;

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

@ -65,7 +65,7 @@ public class ProjectService {
} }
public ProjectDto findOneDto(Integer id) { public ProjectDto findOneDto(Integer id) {
return new ProjectDto(projectRepository.findOne(id)); return new ProjectDto(projectRepository.getOne(id));
} }
public List<Project.ProjectStatus> getProjectStatuses() { public List<Project.ProjectStatus> getProjectStatuses() {
@ -81,8 +81,8 @@ public class ProjectService {
} }
@Transactional @Transactional
public Project update(ProjectDto projectDto) throws IOException { private Project update(ProjectDto projectDto) throws IOException {
Project project = projectRepository.findOne(projectDto.getId()); Project project = projectRepository.getOne(projectDto.getId());
projectRepository.save(copyFromDto(project, projectDto)); projectRepository.save(copyFromDto(project, projectDto));
eventService.updateProjectDeadlines(project); eventService.updateProjectDeadlines(project);
for (FileDataDto file : projectDto.getFiles().stream() for (FileDataDto file : projectDto.getFiles().stream()
@ -95,8 +95,8 @@ public class ProjectService {
@Transactional @Transactional
public boolean delete(Integer projectId) throws IOException { public boolean delete(Integer projectId) throws IOException {
if (projectRepository.exists(projectId)) { if (projectRepository.existsById(projectId)) {
Project project = projectRepository.findOne(projectId); Project project = projectRepository.getOne(projectId);
projectRepository.delete(project); projectRepository.delete(project);
return true; return true;
} }
@ -108,7 +108,7 @@ public class ProjectService {
project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus()); project.setStatus(projectDto.getStatus() == null ? TECHNICAL_TASK : projectDto.getStatus());
project.setTitle(projectDto.getTitle()); project.setTitle(projectDto.getTitle());
if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) { if (projectDto.getGrant() != null && projectDto.getGrant().getId() != null) {
project.setGrant(grantRepository.findOne(projectDto.getGrant().getId())); project.setGrant(grantRepository.getOne(projectDto.getGrant().getId()));
} }
project.setRepository(projectDto.getRepository()); project.setRepository(projectDto.getRepository());
project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines())); project.setDeadlines(deadlineService.saveOrCreate(projectDto.getDeadlines()));
@ -139,12 +139,11 @@ public class ProjectService {
} }
public Project findById(Integer id) { public Project findById(Integer id) {
return projectRepository.findOne(id); return projectRepository.getOne(id);
} }
public List<User> getProjectExecutors(ProjectDto projectDto) { public List<User> getProjectExecutors(ProjectDto projectDto) {
List<User> users = userService.findAll(); return userService.findAll();
return users;
} }
@Transactional @Transactional
@ -153,12 +152,11 @@ public class ProjectService {
} }
public List<GrantDto> getAllGrants() { public List<GrantDto> getAllGrants() {
List<GrantDto> grants = convert(grantRepository.findAll(), GrantDto::new); return convert(grantRepository.findAll(), GrantDto::new);
return grants;
} }
public List<GrantDto> getProjectGrants(List<Integer> grantIds) { private List<GrantDto> getProjectGrants(List<Integer> grantIds) {
return convert(grantRepository.findAll(grantIds), GrantDto::new); return convert(grantRepository.findAllById(grantIds), GrantDto::new);
} }
public void attachGrant(ProjectDto projectDto) { public void attachGrant(ProjectDto projectDto) {

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

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

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

@ -1,14 +1,14 @@
package ru.ulstu.students.model; 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 org.springframework.format.annotation.DateTimeFormat;
import ru.ulstu.core.model.BaseEntity; 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; import java.util.Date;
@Entity @Entity

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

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

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

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

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

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

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

@ -1,5 +1,6 @@
package ru.ulstu.timeline.controller; package ru.ulstu.timeline.controller;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -13,15 +14,11 @@ import ru.ulstu.core.model.response.Response;
import ru.ulstu.timeline.model.EventDto; import ru.ulstu.timeline.model.EventDto;
import ru.ulstu.timeline.service.EventService; import ru.ulstu.timeline.service.EventService;
import javax.validation.Valid;
import java.util.List; import java.util.List;
import static ru.ulstu.timeline.controller.EventController.URL;
@RestController @RestController
@RequestMapping(URL) @RequestMapping(Constants.API_1_0 + "events")
public class EventController { public class EventController {
public static final String URL = Constants.API_1_0 + "events";
private final EventService eventService; private final EventService eventService;
@ -40,18 +37,18 @@ public class EventController {
} }
@PostMapping @PostMapping
public Response createEvent(@RequestBody @Valid EventDto timelineDto) { public Response<Integer> createEvent(@RequestBody @Valid EventDto timelineDto) {
return new Response(eventService.create(timelineDto)); return new Response<>(eventService.create(timelineDto));
} }
@PutMapping @PutMapping
public Response updateEvent(@RequestBody @Valid EventDto eventDto) { public Response<Integer> updateEvent(@RequestBody @Valid EventDto eventDto) {
return new Response(eventService.update(eventDto)); return new Response<>(eventService.update(eventDto));
} }
@DeleteMapping("/{event-id}") @DeleteMapping("/{event-id}")
public Response delete(@PathVariable("event-id") Integer eventId) { public Response<Boolean> delete(@PathVariable("event-id") Integer eventId) {
eventService.delete(eventId); eventService.delete(eventId);
return new Response(true); return new Response<>(Boolean.TRUE);
} }
} }

@ -1,6 +1,19 @@
package ru.ulstu.timeline.model; package ru.ulstu.timeline.model;
import org.hibernate.validator.constraints.NotBlank; 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.ManyToMany;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import ru.ulstu.conference.model.Conference; import ru.ulstu.conference.model.Conference;
import ru.ulstu.core.model.BaseEntity; import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.grant.model.Grant; import ru.ulstu.grant.model.Grant;
@ -9,19 +22,6 @@ import ru.ulstu.project.model.Project;
import ru.ulstu.students.model.Task; import ru.ulstu.students.model.Task;
import ru.ulstu.user.model.User; import ru.ulstu.user.model.User;
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.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -31,7 +31,7 @@ public class Event extends BaseEntity {
public enum EventStatus { public enum EventStatus {
POSSIBLE("Возможное"), NEW("Новое"), IN_PROGRESS("В процессе"), COMPLETED("Завершено"); POSSIBLE("Возможное"), NEW("Новое"), IN_PROGRESS("В процессе"), COMPLETED("Завершено");
private String name; private final String name;
EventStatus(String name) { EventStatus(String name) {
this.name = name; this.name = name;

@ -2,7 +2,8 @@ package ru.ulstu.timeline.model;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import ru.ulstu.conference.model.ConferenceDto; import ru.ulstu.conference.model.ConferenceDto;
import ru.ulstu.grant.model.GrantDto; import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.paper.model.PaperDto; import ru.ulstu.paper.model.PaperDto;
@ -10,7 +11,6 @@ import ru.ulstu.project.model.ProjectDto;
import ru.ulstu.students.model.TaskDto; import ru.ulstu.students.model.TaskDto;
import ru.ulstu.user.model.UserDto; import ru.ulstu.user.model.UserDto;
import javax.validation.constraints.NotNull;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;

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

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

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

Loading…
Cancel
Save