From f8a43bc264249009236e1c4f248840e0e0b54365 Mon Sep 17 00:00:00 2001 From: Timon Borter Date: Wed, 26 Jul 2023 13:04:04 +0200 Subject: [PATCH] feat(deps): major spring upgrade notable dependency upgrades: * jhipsterDependenciesVersion=8.0.0-beta.2 * springBootVersion=3.1.1 * openapiPluginVersion=7.0.0-beta --- .github/workflows/preview.yml | 2 +- .gitignore | 1 + build.gradle | 173 +++++----- gradle.properties | 44 +-- gradle/cache.gradle | 7 + gradle/liquibase.gradle | 72 +++++ gradle/profile_dev.gradle | 21 +- gradle/profile_prod.gradle | 20 +- gradle/sonar.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 2 +- settings.gradle | 3 +- src/main/docker/app.yml | 4 +- src/main/docker/postgresql.yml | 2 +- src/main/docker/redis-cluster.yml | 12 +- src/main/docker/redis.yml | 2 +- .../docker/redis/Redis-Cluster.Dockerfile | 2 +- .../bbortt/event/planner/EventPlannerApp.java | 25 +- .../event/planner/GeneratedByJHipster.java | 3 +- .../planner/aop/logging/LoggingAspect.java | 12 +- .../audit/AsyncEntityAuditEventWriter.java | 20 +- .../audit/EntityAuditEventListener.java | 10 +- .../planner/config/AsyncConfiguration.java | 4 +- .../planner/config/CacheConfiguration.java | 22 +- .../planner/config/DatabaseConfiguration.java | 2 +- .../planner/config/JacksonConfiguration.java | 24 +- .../config/LiquibaseConfiguration.java | 16 +- .../planner/config/LocaleConfiguration.java | 3 +- .../config/LoggingAspectConfiguration.java | 5 +- .../planner/config/LoggingConfiguration.java | 11 +- .../planner/config/OpenApiConfiguration.java | 4 +- .../planner/config/SecurityConfiguration.java | 130 ++++---- .../StaticResourcesWebConfiguration.java | 7 +- .../event/planner/config/WebConfigurer.java | 20 +- .../config/WebsocketConfiguration.java | 16 +- .../domain/AbstractAuditingEntity.java | 15 +- .../event/planner/domain/Authority.java | 13 +- .../planner/domain/EntityAuditEvent.java | 17 +- .../bbortt/event/planner/domain/Event.java | 21 +- .../bbortt/event/planner/domain/Location.java | 23 +- .../bbortt/event/planner/domain/Member.java | 41 +-- .../bbortt/event/planner/domain/Project.java | 14 +- .../bbortt/event/planner/domain/User.java | 21 +- .../event/planner/mail/MailService.java | 29 +- .../mail/ProjectInvitationMailFactory.java | 6 +- .../planner/mail/ServletRequestUtil.java | 5 +- .../planner/repository/EventRepository.java | 8 +- .../repository/LocationRepository.java | 9 +- .../planner/repository/MemberRepository.java | 7 +- .../security/oauth2/AudienceValidator.java | 4 +- .../event/planner/service/EventService.java | 16 +- .../planner/service/LocationService.java | 22 +- .../event/planner/service/MemberService.java | 25 +- .../event/planner/service/ProjectService.java | 30 +- .../event/planner/service/UserService.java | 27 +- .../planner/service/dto/AdminUserDTO.java | 6 +- .../event/planner/service/dto/EventDTO.java | 4 +- .../planner/service/dto/LocationDTO.java | 4 +- .../event/planner/service/dto/MemberDTO.java | 7 +- .../event/planner/service/dto/ProjectDTO.java | 4 +- .../planner/service/mapper/EventMapper.java | 5 +- .../planner/service/mapper/ProjectMapper.java | 7 +- .../planner/service/mapper/UserMapper.java | 9 +- .../web/api/ProjectApiDelegateImpl.java | 6 +- .../web/api/ProjectEventsApiDelegateImpl.java | 4 +- .../api/ProjectLocationApiDelegateImpl.java | 6 +- .../web/api/ProjectMemberApiDelegateImpl.java | 8 +- .../planner/web/api/mapper/TimeUtils.java | 3 +- .../filter/OAuth2RefreshTokensWebFilter.java | 11 +- .../planner/web/filter/SpaWebFilter.java | 36 +++ .../planner/web/rest/AccountResource.java | 9 +- .../planner/web/rest/EntityAuditResource.java | 4 +- .../event/planner/web/rest/EventResource.java | 43 ++- .../planner/web/rest/LocationResource.java | 43 ++- .../planner/web/rest/LogoutResource.java | 5 +- .../planner/web/rest/MemberResource.java | 43 ++- .../planner/web/rest/ProjectResource.java | 32 +- .../planner/web/rest/PublicUserResource.java | 14 +- .../rest/errors/BadRequestAlertException.java | 31 +- .../errors/EntityNotFoundAlertException.java | 21 +- .../web/rest/errors/ExceptionTranslator.java | 300 +++++++++++------- .../planner/web/rest/util/PaginationUtil.java | 4 +- .../web/websocket/ActivityService.java | 17 +- src/main/resources/config/application-dev.yml | 4 +- .../resources/config/application-prod.yml | 10 +- src/main/resources/config/application.yml | 38 ++- src/main/resources/logback-spring.xml | 22 +- src/main/resources/swagger/api.yml | 45 ++- src/main/resources/templates/error.html | 4 +- .../event/planner/TechnicalStructureTest.java | 13 +- .../config/PostgreSqlTestContainer.java | 6 +- .../planner/config/RedisTestContainer.java | 8 +- ...tainersSpringContextCustomizerFactory.java | 45 +++ ...tainersSpringContextCustomizerFactory.java | 48 +++ .../StaticResourcesWebConfigurerTest.java | 17 +- ...tainersSpringContextCustomizerFactory.java | 97 ------ .../planner/config/WebConfigurerTest.java | 33 +- .../config/timezone/HibernateTimeZoneIT.java | 19 +- .../event/planner/mail/MailServiceTest.java | 29 +- .../ProjectInvitationMailFactoryTest.java | 14 +- .../planner/repository/EventRepositoryIT.java | 13 +- .../repository/LocationRepositoryIT.java | 11 +- .../repository/MemberRepositoryIT.java | 12 +- .../repository/ProjectRepositoryIT.java | 17 +- .../repository/timezone/DateTimeWrapper.java | 17 +- .../security/SecurityUtilsUnitTest.java | 17 +- .../planner/service/LocationServiceIT.java | 12 +- .../planner/service/MemberServiceIT.java | 17 +- .../planner/service/MemberServiceTest.java | 2 +- .../planner/service/ProjectServiceIT.java | 11 +- .../planner/service/ProjectServiceTest.java | 33 +- .../service/mapper/MemberMapperTest.java | 20 +- .../event/planner/web/api/ProjectApiIT.java | 21 +- .../event/planner/web/api/ProjectApiTest.java | 20 +- .../planner/web/api/ProjectEventsApiIT.java | 31 +- .../planner/web/api/ProjectEventsApiTest.java | 2 +- .../planner/web/api/ProjectLocationApiIT.java | 19 +- .../planner/web/api/ProjectMemberApiIT.java | 28 +- .../planner/web/api/ProjectMemberApiTest.java | 30 +- .../planner/web/filter/SpaWebFilterIT.java | 84 +++++ .../planner/web/rest/AccountResourceIT.java | 14 +- .../web/rest/ClientForwardControllerTest.java | 83 ----- .../planner/web/rest/EventResourceIT.java | 45 +-- .../planner/web/rest/LocationResourceIT.java | 39 ++- .../planner/web/rest/LogoutResourceIT.java | 21 +- .../planner/web/rest/MemberResourceIT.java | 41 ++- .../planner/web/rest/ProjectResourceIT.java | 38 ++- .../web/rest/PublicUserResourceIT.java | 19 +- .../event/planner/web/rest/TestUtil.java | 27 +- .../planner/web/rest/UserResourceIT.java | 17 +- .../rest/errors/ExceptionTranslatorIT.java | 2 +- .../ExceptionTranslatorTestController.java | 13 +- .../web/rest/util/PaginationUtilTest.java | 14 +- src/test/resources/META-INF/spring.factories | 3 +- .../resources/config/application-testdev.yml | 4 +- .../resources/config/application-testprod.yml | 4 +- src/test/resources/config/application.yml | 2 +- src/test/resources/logback.xml | 17 +- webpack/webpack.custom.js | 12 +- 138 files changed, 1748 insertions(+), 1278 deletions(-) create mode 100644 gradle/cache.gradle create mode 100644 gradle/liquibase.gradle create mode 100644 src/main/java/io/github/bbortt/event/planner/web/filter/SpaWebFilter.java create mode 100644 src/test/java/io/github/bbortt/event/planner/config/RedisTestContainersSpringContextCustomizerFactory.java create mode 100644 src/test/java/io/github/bbortt/event/planner/config/SqlTestContainersSpringContextCustomizerFactory.java delete mode 100644 src/test/java/io/github/bbortt/event/planner/config/TestContainersSpringContextCustomizerFactory.java create mode 100644 src/test/java/io/github/bbortt/event/planner/web/filter/SpaWebFilterIT.java delete mode 100644 src/test/java/io/github/bbortt/event/planner/web/rest/ClientForwardControllerTest.java diff --git a/.github/workflows/preview.yml b/.github/workflows/preview.yml index 1757a2ac0..3a5c96368 100644 --- a/.github/workflows/preview.yml +++ b/.github/workflows/preview.yml @@ -25,4 +25,4 @@ jobs: distribution: 'temurin' java-version: ${{ matrix.java-version }} - name: Backend Tests - run: ./gradlew -DsourceCompatibility=${{ matrix.java-version }} test integrationTest -x webapp -x webapp_test + run: ./gradlew -DjavaVersion=${{ matrix.java-version }} test integrationTest -x webapp -x webapp_test diff --git a/.gitignore b/.gitignore index b6160e6bb..d9c2dc92b 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ ###################### # Node ###################### +.npm/ /node/ node_tmp/ node_modules/ diff --git a/build.gradle b/build.gradle index fc1b14c35..60d3fba1c 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,5 @@ plugins { + id "com.diffplug.spotless" id "com.github.andygoossens.gradle-modernizer-plugin" id "com.github.node-gradle.node" id "com.google.cloud.tools.jib" @@ -22,12 +23,13 @@ version = "${version}" description = "Event planning tool." -sourceCompatibility = "${sourceCompatibility}" +sourceCompatibility = "${javaVersion}" +targetCompatibility = "${javaVersion}" assert System.properties["java.specification.version"] == "17" || "18" || "19" wrapper { - gradleVersion = "7.4.2" + gradleVersion = "8.2.1" } repositories { @@ -55,6 +57,16 @@ springBoot { } +gitProperties { + failOnNoGitDirectory = false + keys = ["git.branch", "git.commit.id.abbrev", "git.commit.id.describe"] +} + +tasks.withType(com.gorylenko.GenerateGitPropertiesTask).configureEach { + outputs.doNotCacheIf("Task is always executed") { true } +} + + dependencies { // import JHipster dependencies BOM if (!project.hasProperty("gae")) { @@ -63,26 +75,22 @@ dependencies { // Use ", version: jhipsterDependenciesVersion, changing: true" if you want // to use a SNAPSHOT release instead of a stable release - implementation group: "tech.jhipster", name: "jhipster-framework" - implementation "javax.annotation:javax.annotation-api" - implementation "org.springframework.boot:spring-boot-starter-cache" + implementation "tech.jhipster:jhipster-framework" + implementation "jakarta.annotation:jakarta.annotation-api" implementation "com.fasterxml.jackson.module:jackson-module-jaxb-annotations" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-hibernate6" implementation "com.fasterxml.jackson.datatype:jackson-datatype-hppc" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" - implementation "org.redisson:redisson" testImplementation "org.testcontainers:junit-jupiter" testImplementation "org.testcontainers:testcontainers" - implementation "org.springdoc:springdoc-openapi-webmvc-core" + implementation "org.springdoc:springdoc-openapi-starter-webmvc-api" implementation "com.zaxxer:HikariCP" implementation "org.apache.commons:commons-lang3" implementation "org.openapitools:jackson-databind-nullable:${jacksonDatabindNullableVersion}" - implementation "com.github.ben-manes.caffeine:caffeine:${caffeineVersion}" - annotationProcessor "org.hibernate:hibernate-jpamodelgen:${hibernateVersion}" - implementation "org.hibernate:hibernate-core" + implementation "com.github.ben-manes.caffeine:caffeine" + annotationProcessor "org.hibernate.orm:hibernate-jpamodelgen:${hibernateVersion}" + implementation "org.hibernate.orm:hibernate-core" implementation "org.hibernate.validator:hibernate-validator" - implementation "org.liquibase:liquibase-core" - liquibaseRuntime "org.liquibase:liquibase-core" implementation "org.mapstruct:mapstruct:${mapstructVersion}" annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}" annotationProcessor "org.springframework.boot:spring-boot-configuration-processor:${springBootVersion}" @@ -97,9 +105,12 @@ dependencies { testImplementation "org.springframework.boot:spring-boot-starter-test" testImplementation "org.springframework.boot:spring-boot-test" testImplementation "org.springframework.security:spring-security-test" - testImplementation "com.tngtech.archunit:archunit-junit5-api:${archunitJunit5Version}" - testRuntimeOnly "com.tngtech.archunit:archunit-junit5-engine:${archunitJunit5Version}" - implementation "org.zalando:problem-spring-web" + testImplementation("com.tngtech.archunit:archunit-junit5-api:${archunitJunit5Version}") { + exclude group: "org.slf4j", module: "slf4j-api" + } + testRuntimeOnly("com.tngtech.archunit:archunit-junit5-engine:${archunitJunit5Version}") { + exclude group: "org.slf4j", module: "slf4j-api" + } implementation "org.springframework.boot:spring-boot-starter-undertow" implementation "org.springframework.boot:spring-boot-starter-websocket" implementation "org.springframework.boot:spring-boot-starter-oauth2-client" @@ -108,9 +119,7 @@ dependencies { implementation "io.micrometer:micrometer-registry-prometheus" implementation "io.dropwizard.metrics:metrics-core" implementation "org.springframework.security:spring-security-messaging" - liquibaseRuntime sourceSets.main.compileClasspath - liquibaseRuntime "org.liquibase.ext:liquibase-hibernate5:${liquibaseHibernate5Version}" - //jhipster-needle-gradle-dependency - JHipster will add additional dependencies here + // jhipster-needle-gradle-dependency - JHipster will add additional dependencies here } compileJava.dependsOn processResources @@ -119,14 +128,6 @@ processResources.dependsOn bootBuildInfo configurations { providedRuntime implementation.exclude module: "spring-boot-starter-tomcat" - all { - resolutionStrategy { - // Inherited version from Spring Boot can't be used because of regressions: - // To be removed as soon as spring-boot use the same version - force "org.liquibase:liquibase-core:4.23.0" - force "org.yaml:snakeyaml:1.33" - } - } } @@ -160,26 +161,17 @@ nohttp { source.include "build.gradle", "README.md" } - -if (!project.hasProperty("runList")) { - project.ext.runList = "main" +spotless { + java { + target 'src/*/java/**/*.java' + removeUnusedImports() + } } if (project.hasProperty("gae")) { - apply plugin: "maven" - apply plugin: "org.springframework.boot.experimental.thin-launcher" - apply plugin: "io.spring.dependency-management" - - dependencyManagement { - imports { - mavenBom "tech.jhipster:jhipster-dependencies:${jhipsterDependenciesVersion}" - } - } - appengineStage.dependsOn thinResolve - task createPom { - def basePath = "build/resources/main/META-INF/maven" + def basePath = 'build/resources/main/META-INF/maven' doLast { pom { withXml(dependencyManagement.pomConfigurer) @@ -202,11 +194,12 @@ task openApiGenerateBackend(type: org.openapitools.generator.gradle.plugin.tasks configOptions = [ delegatePattern: "true", useOptional : "true", + useSpringBoot3 : "true", useTags : "true", title : "eventplanner" ] validateSpec = true - importMappings = [Problem: "org.zalando.problem.Problem"] + importMappings = [Problem:"org.springframework.http.ProblemDetail"] } task openApiGenerateFrontend(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) { @@ -246,7 +239,7 @@ test { // uncomment if the tests reports are not generated // see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484 // ignoreFailures true - reports.html.enabled = false + reports.html.required = false } task testReport(type: TestReport) { @@ -272,59 +265,65 @@ task cleanResources(type: Delete) { delete "build/resources" } -task webapp_test(type: NpmTask, dependsOn: "npm_install") { +task webapp_test(type: NpmTask) { + inputs.property('appVersion', project.version) + inputs.files("package-lock.json") + .withPropertyName('package-lock') + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.files("build.gradle") + .withPropertyName('build.gradle') + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.files("angular.json") + .withPropertyName('angular.json') + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.files("tsconfig.json", "tsconfig.app.json") + .withPropertyName("tsconfig") + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.dir("webpack/") + .withPropertyName("webpack/") + .withPathSensitivity(PathSensitivity.RELATIVE) + inputs.dir("src/main/webapp/") + .withPropertyName("webapp-source-dir") + .withPathSensitivity(PathSensitivity.RELATIVE) + + outputs.dir("build/test-results/jest/") + .withPropertyName("jest-result-dir") + outputs.file("build/test-results/TESTS-results-jest.xml") + .withPropertyName("jest-result") + outputs.file("build/test-results/clover.xml") + .withPropertyName("clover-result") + + dependsOn npmInstall,compileTestJava args = ["run", "webapp:test"] } -// Copy local node and npm to a fixed location for npmw -def fixedNode = tasks.register("fixedNode", Copy) { - from nodeSetup - into "build/node" -} -tasks.named("nodeSetup").configure { finalizedBy fixedNode } - -def fixedNpm = tasks.register("fixedNpm", Copy) { - from npmSetup - into "build/node" -} -tasks.named("npmSetup").configure { finalizedBy fixedNpm } - -test.dependsOn webapp_test - - -project.ext.diffChangelogFile = "src/main/resources/config/liquibase/changelog/" + new Date().format("yyyyMMddHHmmss") + "_changelog.xml" +if (project.hasProperty("nodeInstall")) { + node { + version = "18.16.1" + npmVersion = "9.8.0" + download = true + } -liquibase { - activities { - main { - driver "org.postgresql.Driver" - url "jdbc:postgresql://localhost:5432/eventplanner" - username "eventplanner" - password "" - changeLogFile "src/main/resources/config/liquibase/master.xml" - defaultSchemaName "" - logLevel "debug" - classpath "src/main/resources/" - } - diffLog { - driver "org.postgresql.Driver" - url "jdbc:postgresql://localhost:5432/eventplanner" - username "eventplanner" - password "" - changeLogFile project.ext.diffChangelogFile - referenceUrl "hibernate:spring:io.github.bbortt.event.planner.domain?dialect=tech.jhipster.domain.util.FixedPostgreSQL10Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy" - defaultSchemaName "" - logLevel "debug" - classpath "$buildDir/classes/java/main" - excludeObjects "oauth_access_token, oauth_approvals, oauth_client_details, oauth_client_token, oauth_code, oauth_refresh_token" - } + // Copy local node and npm to a fixed location for npmw + def fixedNode = tasks.register("fixedNode", Copy) { + from nodeSetup + into 'build/node' } + tasks.named("nodeSetup").configure { finalizedBy fixedNode } - runList = project.ext.runList + def fixedNpm = tasks.register("fixedNpm", Copy) { + from npmSetup + into 'build/node' + } + tasks.named("npmSetup").configure { finalizedBy fixedNpm } } +test.dependsOn webapp_test + +apply from: "gradle/cache.gradle" apply from: "gradle/docker.gradle" +apply from: "gradle/liquibase.gradle" apply from: "gradle/sonar.gradle" //jhipster-needle-gradle-apply-from - JHipster will add additional gradle scripts to be applied here diff --git a/gradle.properties b/gradle.properties index fd5a7b803..629f91099 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,37 +2,39 @@ rootProject.name=event-planner # Build information +javaVersion=17 profile=dev -sourceCompatibility=17 version=0.1.0 # Dependency versions -jhipsterDependenciesVersion=7.9.3 +jhipsterDependenciesVersion=8.0.0-beta.2 # The spring-boot version should match the one managed by -# https://mvnrepository.com/artifact/tech.jhipster/jhipster-dependencies/7.9.3 -springBootVersion=2.7.10 +# https://mvnrepository.com/artifact/tech.jhipster/jhipster-dependencies/8.0.0-beta.2 +springBootVersion=3.1.1 # The hibernate version should match the one managed by -# https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/2.7.3 --> -hibernateVersion=5.6.10.Final -mapstructVersion=1.5.2.Final -archunitJunit5Version=0.22.0 -jacksonDatabindNullableVersion=0.2.3 -caffeineVersion=3.1.1 -liquibaseHibernate5Version=4.15.0 -liquibaseTaskPrefix=liquibase +# https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/3.1.1 --> +hibernateVersion=6.1.7.Final +mapstructVersion=1.5.5.Final +archunitJunit5Version=1.0.1 +jacksonDatabindNullableVersion=0.2.6 -jaxbRuntimeVersion=4.0.0 +jaxbRuntimeVersion=4.0.3 # gradle plugin version -jibPluginVersion=3.2.1 +jibPluginVersion=3.3.2 gitPropertiesPluginVersion=2.4.1 -gradleNodePluginVersion=3.4.0 -liquibasePluginVersion=2.1.1 -sonarqubePluginVersion=3.4.0.2513 -openapiPluginVersion=6.0.1 -noHttpCheckstyleVersion=0.0.10 -checkstyleVersion=10.3.2 -modernizerPluginVersion=1.6.2 +gradleNodePluginVersion=5.0.0 +sonarqubePluginVersion=4.2.1.3168 +spotlessPluginVersion=6.19.0 +openapiPluginVersion=7.0.0-beta +noHttpCheckstyleVersion=0.0.11 +checkstyleVersion=10.12.1 +modernizerPluginVersion=1.8.0 + +liquibaseTaskPrefix=liquibase +liquibasePluginVersion=2.2.0 +liquibaseVersion=4.20.0 +liquibaseHibernate6Version=4.20.0 # jhipster-needle-gradle-property - JHipster will add additional properties here diff --git a/gradle/cache.gradle b/gradle/cache.gradle new file mode 100644 index 000000000..5e155bbdb --- /dev/null +++ b/gradle/cache.gradle @@ -0,0 +1,7 @@ +dependencies { + implementation "org.springframework.boot:spring-boot-starter-cache" + implementation "org.redisson:redisson" + implementation "org.hibernate.orm:hibernate-jcache" + testImplementation "org.testcontainers:junit-jupiter" + testImplementation "org.testcontainers:testcontainers" +} diff --git a/gradle/liquibase.gradle b/gradle/liquibase.gradle new file mode 100644 index 000000000..cd1aaf982 --- /dev/null +++ b/gradle/liquibase.gradle @@ -0,0 +1,72 @@ +configurations { + liquibaseRuntime.extendsFrom sourceSets.main.compileClasspath +} + + +dependencies { + implementation "org.liquibase:liquibase-core" + liquibaseRuntime "org.liquibase:liquibase-core" + // Dependency required to parse options. Refer to https://github.com/liquibase/liquibase-gradle-plugin/tree/Release_2.2.0#news. + liquibaseRuntime "info.picocli:picocli:4.7.4" + + liquibaseRuntime "org.liquibase.ext:liquibase-hibernate6:${liquibaseHibernate6Version}" + liquibaseRuntime "org.postgresql:postgresql" +} + + +project.ext.diffChangelogFile = "src/main/resources/config/liquibase/changelog/" + new Date().format("yyyyMMddHHmmss") + "_changelog.xml" +if (!project.hasProperty("runList")) { + project.ext.runList = "main" +} + + +liquibase { + activities { + main { + driver "org.postgresql.Driver" + url "jdbc:postgresql://localhost:5432/eventplanner" + username "eventplanner" + password "" + changeLogFile "src/main/resources/config/liquibase/master.xml" + defaultSchemaName "" + logLevel "debug" + classpath "src/main/resources/" + } + diffLog { + driver "org.postgresql.Driver" + url "jdbc:postgresql://localhost:5432/eventplanner" + username "eventplanner" + password "" + changeLogFile project.ext.diffChangelogFile + referenceUrl "hibernate:spring:io.github.bbortt.event.planner.domain?dialect=org.hibernate.dialect.PostgreSQLDialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy" + defaultSchemaName "" + logLevel "debug" + classpath "$buildDir/classes/java/main" + excludeObjects "oauth_access_token, oauth_approvals, oauth_client_details, oauth_client_token, oauth_code, oauth_refresh_token" + } + } + + runList = project.ext.runList +} + + +liquibaseDiff.dependsOn compileJava +liquibaseDiffChangelog.dependsOn compileJava + + +configurations { + all { + resolutionStrategy { + // Inherited version from Spring Boot can't be used because of regressions: + // To be removed as soon as spring-boot use the same version + force "org.liquibase:liquibase-core:4.20.0" + } + } +} + + +ext { + if (project.hasProperty("no-liquibase")) { + springProfiles += ",no-liquibase" + } +} diff --git a/gradle/profile_dev.gradle b/gradle/profile_dev.gradle index 2696561ed..a6b7c2ab4 100644 --- a/gradle/profile_dev.gradle +++ b/gradle/profile_dev.gradle @@ -1,3 +1,15 @@ +configurations { + all { + resolutionStrategy { + // TODO drop forced version. Refer to https://github.com/jhipster/generator-jhipster/issues/22579 + force "org.hibernate.orm:hibernate-core:${hibernateVersion}" + // TODO drop forced version. Refer to https://github.com/jhipster/generator-jhipster/issues/22579 + force "org.hibernate.orm:hibernate-jcache:${hibernateVersion}" + } + } +} + + dependencies { developmentOnly "org.springframework.boot:spring-boot-devtools:${springBootVersion}" implementation "org.postgresql:postgresql" @@ -5,6 +17,7 @@ dependencies { testImplementation "org.testcontainers:postgresql" } + def profiles = "dev" if (project.hasProperty("no-liquibase")) { profiles += ",no-liquibase" @@ -13,6 +26,7 @@ if (project.hasProperty("tls")) { profiles += ",tls" } + springBoot { buildInfo { properties { @@ -21,10 +35,12 @@ springBoot { } } + bootRun { args = ["--spring.profiles.active=${profiles}"] } + task webapp(type: NpmTask, dependsOn: "openApiGenerateFrontend") { inputs.property('appVersion', project.version) inputs.files("package-lock.json") @@ -54,6 +70,7 @@ task webapp(type: NpmTask, dependsOn: "openApiGenerateFrontend") { environment = [APP_VERSION: project.version] } + processResources { inputs.property('version', version) inputs.property('springProfiles', profiles) @@ -67,6 +84,7 @@ processResources { } } + task integrationTest(type: Test) { maxHeapSize = "1G" useJUnitPlatform() @@ -81,9 +99,10 @@ task integrationTest(type: Test) { // uncomment if the tests reports are not generated // see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484 // ignoreFailures true - reports.html.enabled = false + reports.html.required = false } integrationTest.dependsOn test + processResources.dependsOn webapp bootJar.dependsOn processResources diff --git a/gradle/profile_prod.gradle b/gradle/profile_prod.gradle index 58b2b205c..724947b12 100644 --- a/gradle/profile_prod.gradle +++ b/gradle/profile_prod.gradle @@ -1,9 +1,22 @@ +configurations { + all { + resolutionStrategy { + // TODO drop forced version. Refer to https://github.com/jhipster/generator-jhipster/issues/22579 + force "org.hibernate.orm:hibernate-core:${hibernateVersion}" + // TODO drop forced version. Refer to https://github.com/jhipster/generator-jhipster/issues/22579 + force "org.hibernate.orm:hibernate-jcache:${hibernateVersion}" + } + } +} + + dependencies { implementation "org.postgresql:postgresql" liquibaseRuntime "org.postgresql:postgresql" testImplementation "org.testcontainers:postgresql" } + def profiles = "prod" if (project.hasProperty("no-liquibase")) { profiles += ",no-liquibase" @@ -17,19 +30,23 @@ if (project.hasProperty("e2e")) { profiles += ",e2e" } + springBoot { buildInfo() } + bootRun { args = ["--spring.profiles.active=${profiles}"] } + task webapp(type: NpmTask, dependsOn: ["npm_install", "openApiGenerateFrontend"]) { args = ["run", "webapp:prod"] environment = [APP_VERSION: project.version] } + processResources { inputs.property('version', version) inputs.property('springProfiles', profiles) @@ -43,6 +60,7 @@ processResources { } } + task integrationTest(type: Test) { maxHeapSize = "1G" useJUnitPlatform() @@ -57,7 +75,7 @@ task integrationTest(type: Test) { // uncomment if the tests reports are not generated // see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484 // ignoreFailures true - reports.html.enabled = false + reports.html.required = false } integrationTest.dependsOn test diff --git a/gradle/sonar.gradle b/gradle/sonar.gradle index bdd9c8a9c..4a6edcda6 100644 --- a/gradle/sonar.gradle +++ b/gradle/sonar.gradle @@ -8,7 +8,7 @@ jacocoTestReport { sourceDirectories.from = files(sourceSets.main.java.srcDirs) reports { - xml.enabled = true + xml.required = true } } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index aa991fcea..84a0b92f9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/settings.gradle b/settings.gradle index 54fac570a..1d4113708 100644 --- a/settings.gradle +++ b/settings.gradle @@ -10,10 +10,11 @@ pluginManagement { id "com.gorylenko.gradle-git-properties" version "${gitPropertiesPluginVersion}" id "org.openapi.generator" version "${openapiPluginVersion}" id "com.github.node-gradle.node" version "${gradleNodePluginVersion}" - id "org.liquibase.gradle" version "${liquibasePluginVersion}" id "org.sonarqube" version "${sonarqubePluginVersion}" + id "com.diffplug.spotless" version "${spotlessPluginVersion}" id "io.spring.nohttp" version "${noHttpCheckstyleVersion}" id "com.github.andygoossens.gradle-modernizer-plugin" version "${modernizerPluginVersion}" + id "org.liquibase.gradle" version "${liquibasePluginVersion}" //jhipster-needle-gradle-plugin-management-plugins - JHipster will add additional entries here } } diff --git a/src/main/docker/app.yml b/src/main/docker/app.yml index 981786ce0..e1bb65e25 100644 --- a/src/main/docker/app.yml +++ b/src/main/docker/app.yml @@ -22,7 +22,7 @@ services: ports: - 127.0.0.1:8080:8080 eventplanner-postgresql: - image: postgres:15.2-alpine + image: postgres:15.3-alpine # volumes: # - ~/volumes/jhipster/eventplanner/postgresql/:/var/lib/postgresql/data/ environment: @@ -34,7 +34,7 @@ services: ports: - 127.0.0.1:5432:5432 eventplanner-redis: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine # If you want to expose these ports outside your dev PC, # remove the "127.0.0.1:" prefix ports: diff --git a/src/main/docker/postgresql.yml b/src/main/docker/postgresql.yml index be371116e..a9aa65e37 100644 --- a/src/main/docker/postgresql.yml +++ b/src/main/docker/postgresql.yml @@ -2,7 +2,7 @@ version: '3.8' services: eventplanner-postgresql: - image: postgres:15.2-alpine + image: postgres:15.3-alpine # volumes: # - ~/volumes/jhipster/eventplanner/postgresql/:/var/lib/postgresql/data/ environment: diff --git a/src/main/docker/redis-cluster.yml b/src/main/docker/redis-cluster.yml index bb6fa315f..8b5888281 100644 --- a/src/main/docker/redis-cluster.yml +++ b/src/main/docker/redis-cluster.yml @@ -2,7 +2,7 @@ version: '3.8' services: eventplanner-redis: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' @@ -13,7 +13,7 @@ services: ports: - '6379:6379' eventplanner-redis-1: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' @@ -24,7 +24,7 @@ services: ports: - '16379:6379' eventplanner-redis-2: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' @@ -35,7 +35,7 @@ services: ports: - '26379:6379' eventplanner-redis-3: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' @@ -46,7 +46,7 @@ services: ports: - '36379:6379' eventplanner-redis-4: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' @@ -57,7 +57,7 @@ services: ports: - '46379:6379' eventplanner-redis-5: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine command: - 'redis-server' - '--port 6379' diff --git a/src/main/docker/redis.yml b/src/main/docker/redis.yml index 1fa832ab8..a8fc6987f 100644 --- a/src/main/docker/redis.yml +++ b/src/main/docker/redis.yml @@ -2,7 +2,7 @@ version: '3.8' services: eventplanner-redis: - image: redis:7.0.10-alpine + image: redis:7.0.12-alpine # If you want to expose these ports outside your dev PC, # remove the "127.0.0.1:" prefix ports: diff --git a/src/main/docker/redis/Redis-Cluster.Dockerfile b/src/main/docker/redis/Redis-Cluster.Dockerfile index 07d940e6e..af82f8c07 100644 --- a/src/main/docker/redis/Redis-Cluster.Dockerfile +++ b/src/main/docker/redis/Redis-Cluster.Dockerfile @@ -1,4 +1,4 @@ -FROM redis:7.0.10-alpine +FROM redis:7.0.12-alpine RUN apt update && \ apt install \ diff --git a/src/main/java/io/github/bbortt/event/planner/EventPlannerApp.java b/src/main/java/io/github/bbortt/event/planner/EventPlannerApp.java index b60736b3b..6d40a0ef3 100644 --- a/src/main/java/io/github/bbortt/event/planner/EventPlannerApp.java +++ b/src/main/java/io/github/bbortt/event/planner/EventPlannerApp.java @@ -2,12 +2,7 @@ import io.github.bbortt.event.planner.config.ApplicationProperties; import io.github.bbortt.event.planner.config.CRLFLogConverter; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Optional; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,11 +14,17 @@ import tech.jhipster.config.DefaultProfileUtil; import tech.jhipster.config.JHipsterConstants; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Optional; + @SpringBootApplication -@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) +@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) public class EventPlannerApp { - private static final Logger log = LoggerFactory.getLogger(EventPlannerApp.class); + private static final Logger logger = LoggerFactory.getLogger(EventPlannerApp.class); private final Environment env; @@ -45,7 +46,7 @@ public void initApplication() { activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION) ) { - log.error( + logger.error( "You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time." ); } @@ -53,7 +54,7 @@ public void initApplication() { activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD) ) { - log.error( + logger.error( "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time." ); } @@ -82,9 +83,9 @@ private static void logApplicationStartup(Environment env) { try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { - log.warn("The host name could not be determined, using `localhost` as fallback"); + logger.warn("The host name could not be determined, using `localhost` as fallback"); } - log.info( + logger.info( CRLFLogConverter.CRLF_SAFE_MARKER, "\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + diff --git a/src/main/java/io/github/bbortt/event/planner/GeneratedByJHipster.java b/src/main/java/io/github/bbortt/event/planner/GeneratedByJHipster.java index 70d293ee8..c6b620cc0 100644 --- a/src/main/java/io/github/bbortt/event/planner/GeneratedByJHipster.java +++ b/src/main/java/io/github/bbortt/event/planner/GeneratedByJHipster.java @@ -1,10 +1,11 @@ package io.github.bbortt.event.planner; +import jakarta.annotation.Generated; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.annotation.Generated; @Generated(value = "JHipster", comments = "Generated by JHipster 7.9.3") @Retention(RetentionPolicy.SOURCE) diff --git a/src/main/java/io/github/bbortt/event/planner/aop/logging/LoggingAspect.java b/src/main/java/io/github/bbortt/event/planner/aop/logging/LoggingAspect.java index 70cb93607..722f6caa0 100644 --- a/src/main/java/io/github/bbortt/event/planner/aop/logging/LoggingAspect.java +++ b/src/main/java/io/github/bbortt/event/planner/aop/logging/LoggingAspect.java @@ -97,18 +97,18 @@ public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { - Logger log = logger(joinPoint); - if (log.isDebugEnabled()) { - log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); + Logger logger = logger(joinPoint); + if (logger.isDebugEnabled()) { + logger.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); - if (log.isDebugEnabled()) { - log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); + if (logger.isDebugEnabled()) { + logger.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { - log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); + logger.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); throw e; } } diff --git a/src/main/java/io/github/bbortt/event/planner/audit/AsyncEntityAuditEventWriter.java b/src/main/java/io/github/bbortt/event/planner/audit/AsyncEntityAuditEventWriter.java index b36c9728a..5f6955fb7 100644 --- a/src/main/java/io/github/bbortt/event/planner/audit/AsyncEntityAuditEventWriter.java +++ b/src/main/java/io/github/bbortt/event/planner/audit/AsyncEntityAuditEventWriter.java @@ -22,7 +22,7 @@ @Profile("!testdev & !testprod") public class AsyncEntityAuditEventWriter implements EntityAuditEventWriter { - private final Logger log = LoggerFactory.getLogger(AsyncEntityAuditEventWriter.class); + private static final Logger logger = LoggerFactory.getLogger(AsyncEntityAuditEventWriter.class); private final EntityAuditEventRepository auditingEntityRepository; @@ -45,14 +45,14 @@ public AsyncEntityAuditEventWriter( */ @Async public void writeAuditEvent(Object target, EntityAuditAction action) { - log.debug("-------------- Post {} audit --------------", action.value()); + logger.debug("-------------- Post {} audit --------------", action.value()); try { EntityAuditEvent auditedEntity = prepareAuditEntity(target, action); if (auditedEntity != null) { auditingEntityRepository.save(auditedEntity); } } catch (Exception e) { - log.error("Exception while persisting audit entity for {} error: {}", target, e); + logger.error("Exception while persisting audit entity for {} error: {}", target, e); } } @@ -70,7 +70,7 @@ private EntityAuditEvent prepareAuditEntity(final Object entity, EntityAuditActi auditedEntity.setEntityType(entityClass.getName()); Object entityId; String entityData; - log.trace("Getting Entity Id and Content"); + logger.trace("Getting Entity Id and Content"); try { Field privateLongField = entityClass.getDeclaredField("id"); privateLongField.setAccessible(true); @@ -78,7 +78,7 @@ private EntityAuditEvent prepareAuditEntity(final Object entity, EntityAuditActi privateLongField.setAccessible(false); entityData = objectMapper.writeValueAsString(entity); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | IOException e) { - log.error("Exception while getting entity ID and content {}", e); + logger.error("Exception while getting entity ID and content {}", e); // returning null as we don't want to raise an application exception here return null; } @@ -94,22 +94,22 @@ private EntityAuditEvent prepareAuditEntity(final Object entity, EntityAuditActi auditedEntity.setModifiedDate(abstractAuditEntity.getLastModifiedDate()); calculateVersion(auditedEntity); } - log.trace("Audit Entity --> {} ", auditedEntity.toString()); + logger.trace("Audit Entity --> {} ", auditedEntity.toString()); return auditedEntity; } private void calculateVersion(EntityAuditEvent auditedEntity) { - log.trace("Version calculation. for update/remove"); + logger.trace("Version calculation. for update/remove"); Integer lastCommitVersion = auditingEntityRepository.findMaxCommitVersion( auditedEntity.getEntityType(), auditedEntity.getEntityId() ); - log.trace("Last commit version of entity => {}", lastCommitVersion); + logger.trace("Last commit version of entity => {}", lastCommitVersion); if (lastCommitVersion != null && lastCommitVersion != 0) { - log.trace("Present. Adding version.."); + logger.trace("Present. Adding version.."); auditedEntity.setCommitVersion(lastCommitVersion + 1); } else { - log.trace("No entities.. Adding new version 1"); + logger.trace("No entities.. Adding new version 1"); auditedEntity.setCommitVersion(1); } } diff --git a/src/main/java/io/github/bbortt/event/planner/audit/EntityAuditEventListener.java b/src/main/java/io/github/bbortt/event/planner/audit/EntityAuditEventListener.java index 97a92402f..f5ad9d2c6 100644 --- a/src/main/java/io/github/bbortt/event/planner/audit/EntityAuditEventListener.java +++ b/src/main/java/io/github/bbortt/event/planner/audit/EntityAuditEventListener.java @@ -1,9 +1,9 @@ package io.github.bbortt.event.planner.audit; import io.github.bbortt.event.planner.domain.enumeration.EntityAuditAction; -import javax.persistence.PostPersist; -import javax.persistence.PostRemove; -import javax.persistence.PostUpdate; +import jakarta.persistence.PostPersist; +import jakarta.persistence.PostRemove; +import jakarta.persistence.PostUpdate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; @@ -11,7 +11,7 @@ public class EntityAuditEventListener extends AuditingEntityListener { - private final Logger log = LoggerFactory.getLogger(EntityAuditEventListener.class); + private static final Logger logger = LoggerFactory.getLogger(EntityAuditEventListener.class); private static EntityAuditEventWriter entityAuditEventWriter; @@ -37,7 +37,7 @@ public void writeEvent(Object target, EntityAuditAction action) { try { entityAuditEventWriter.writeAuditEvent(target, action); } catch (Exception e) { - log.error("Exception while persisting delete audit entity {}", e); + logger.error("Exception while persisting delete audit entity {}", e); } } diff --git a/src/main/java/io/github/bbortt/event/planner/config/AsyncConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/AsyncConfiguration.java index b9dec16b9..2edc7c131 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/AsyncConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/AsyncConfiguration.java @@ -21,7 +21,7 @@ @Profile("!testdev & !testprod") public class AsyncConfiguration implements AsyncConfigurer { - private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); + private static final Logger logger = LoggerFactory.getLogger(AsyncConfiguration.class); private final TaskExecutionProperties taskExecutionProperties; @@ -32,7 +32,7 @@ public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { - log.debug("Creating Async Task Executor"); + logger.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); diff --git a/src/main/java/io/github/bbortt/event/planner/config/CacheConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/CacheConfiguration.java index c722059b5..a951d39f6 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/CacheConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/CacheConfiguration.java @@ -1,10 +1,6 @@ package io.github.bbortt.event.planner.config; -import java.net.URI; -import java.util.concurrent.TimeUnit; -import javax.cache.configuration.MutableConfiguration; -import javax.cache.expiry.CreatedExpiryPolicy; -import javax.cache.expiry.Duration; +import org.hibernate.cache.jcache.ConfigSettings; import org.redisson.Redisson; import org.redisson.config.ClusterServersConfig; import org.redisson.config.Config; @@ -13,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.info.GitProperties; import org.springframework.cache.annotation.EnableCaching; @@ -22,6 +19,12 @@ import tech.jhipster.config.JHipsterProperties; import tech.jhipster.config.cache.PrefixedKeyGenerator; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.expiry.CreatedExpiryPolicy; +import javax.cache.expiry.Duration; +import java.net.URI; +import java.util.concurrent.TimeUnit; + @Configuration @EnableCaching @ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis") @@ -67,12 +70,19 @@ public javax.cache.configuration.Configuration jcacheConfigurati return RedissonConfiguration.fromInstance(Redisson.create(config), jcacheConfig); } + @Bean + public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(javax.cache.CacheManager cm) { + return hibernateProperties -> hibernateProperties.put(ConfigSettings.CACHE_MANAGER, cm); + } + @Bean public JCacheManagerCustomizer cacheManagerCustomizer(javax.cache.configuration.Configuration jcacheConfiguration) { return cm -> { createCache(cm, io.github.bbortt.event.planner.repository.UserRepository.USERS_BY_LOGIN_CACHE, jcacheConfiguration); createCache(cm, io.github.bbortt.event.planner.repository.UserRepository.USERS_BY_EMAIL_CACHE, jcacheConfiguration); - createCache(cm, io.github.bbortt.event.planner.domain.EntityAuditEvent.class.getName(), jcacheConfiguration); + createCache(cm, io.github.bbortt.event.planner.domain.User.class.getName(), jcacheConfiguration); + createCache(cm, io.github.bbortt.event.planner.domain.Authority.class.getName(), jcacheConfiguration); + createCache(cm, io.github.bbortt.event.planner.domain.User.class.getName() + ".authorities", jcacheConfiguration); // jhipster-needle-redis-add-entry }; } diff --git a/src/main/java/io/github/bbortt/event/planner/config/DatabaseConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/DatabaseConfiguration.java index f0e1cc896..c20aaec5a 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/DatabaseConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/DatabaseConfiguration.java @@ -6,7 +6,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration +@EnableTransactionManagement @EnableJpaRepositories({ "io.github.bbortt.event.planner.repository" }) @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") -@EnableTransactionManagement public class DatabaseConfiguration {} diff --git a/src/main/java/io/github/bbortt/event/planner/config/JacksonConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/JacksonConfiguration.java index 07ec2aeb5..23bfdaa4d 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/JacksonConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/JacksonConfiguration.java @@ -1,12 +1,10 @@ package io.github.bbortt.event.planner.config; -import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; +import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.zalando.problem.jackson.ProblemModule; -import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration public class JacksonConfiguration { @@ -29,23 +27,7 @@ public Jdk8Module jdk8TimeModule() { * Support for Hibernate types in Jackson. */ @Bean - public Hibernate5Module hibernate5Module() { - return new Hibernate5Module(); - } - - /* - * Module for serialization/deserialization of RFC7807 Problem. - */ - @Bean - public ProblemModule problemModule() { - return new ProblemModule(); - } - - /* - * Module for serialization/deserialization of ConstraintViolationProblem. - */ - @Bean - public ConstraintViolationProblemModule constraintViolationProblemModule() { - return new ConstraintViolationProblemModule(); + public Hibernate6Module hibernate6Module() { + return new Hibernate6Module(); } } diff --git a/src/main/java/io/github/bbortt/event/planner/config/LiquibaseConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/LiquibaseConfiguration.java index 8034d792f..37bbbc3a5 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/LiquibaseConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/LiquibaseConfiguration.java @@ -1,7 +1,6 @@ package io.github.bbortt.event.planner.config; -import java.util.concurrent.Executor; -import javax.sql.DataSource; + import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,10 +16,13 @@ import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.liquibase.SpringLiquibaseUtil; +import javax.sql.DataSource; +import java.util.concurrent.Executor; + @Configuration public class LiquibaseConfiguration { - private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); + private static final Logger logger = LoggerFactory.getLogger(LiquibaseConfiguration.class); private final Environment env; @@ -31,15 +33,15 @@ public LiquibaseConfiguration(Environment env) { @Bean public SpringLiquibase liquibase( @Qualifier("taskExecutor") Executor executor, - @LiquibaseDataSource ObjectProvider liquibaseDataSource, LiquibaseProperties liquibaseProperties, + @LiquibaseDataSource ObjectProvider liquibaseDataSource, ObjectProvider dataSource, DataSourceProperties dataSourceProperties ) { // If you don't want Liquibase to start asynchronously, substitute by this: // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( - env, + this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, @@ -54,7 +56,7 @@ public SpringLiquibase liquibase( liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); - liquibase.setLabels(liquibaseProperties.getLabels()); + liquibase.setLabelFilter(liquibaseProperties.getLabelFilter()); liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); @@ -62,7 +64,7 @@ public SpringLiquibase liquibase( liquibase.setShouldRun(false); } else { liquibase.setShouldRun(liquibaseProperties.isEnabled()); - log.debug("Configuring Liquibase"); + logger.debug("Configuring Liquibase"); } return liquibase; } diff --git a/src/main/java/io/github/bbortt/event/planner/config/LocaleConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/LocaleConfiguration.java index 66ad2a0af..35b28856c 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/LocaleConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/LocaleConfiguration.java @@ -3,7 +3,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; -import org.springframework.web.servlet.config.annotation.*; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import tech.jhipster.config.locale.AngularCookieLocaleResolver; diff --git a/src/main/java/io/github/bbortt/event/planner/config/LoggingAspectConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/LoggingAspectConfiguration.java index 488c2e1e9..32a77b055 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/LoggingAspectConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/LoggingAspectConfiguration.java @@ -1,7 +1,10 @@ package io.github.bbortt.event.planner.config; import io.github.bbortt.event.planner.aop.logging.LoggingAspect; -import org.springframework.context.annotation.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import tech.jhipster.config.JHipsterConstants; diff --git a/src/main/java/io/github/bbortt/event/planner/config/LoggingConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/LoggingConfiguration.java index e903de125..882bef196 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/LoggingConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/LoggingConfiguration.java @@ -1,17 +1,20 @@ package io.github.bbortt.event.planner.config; -import static tech.jhipster.config.logging.LoggingUtils.*; - import ch.qos.logback.classic.LoggerContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.HashMap; -import java.util.Map; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import tech.jhipster.config.JHipsterProperties; +import java.util.HashMap; +import java.util.Map; + +import static tech.jhipster.config.logging.LoggingUtils.addContextListener; +import static tech.jhipster.config.logging.LoggingUtils.addJsonConsoleAppender; +import static tech.jhipster.config.logging.LoggingUtils.addLogstashTcpSocketAppender; + /* * Configures the console and Logstash log appenders from the app properties */ diff --git a/src/main/java/io/github/bbortt/event/planner/config/OpenApiConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/OpenApiConfiguration.java index 729746ec9..2be956609 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/OpenApiConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/OpenApiConfiguration.java @@ -1,6 +1,6 @@ package io.github.bbortt.event.planner.config; -import org.springdoc.core.GroupedOpenApi; +import org.springdoc.core.models.GroupedOpenApi; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -25,7 +25,7 @@ public GroupedOpenApi apiFirstGroupedOpenAPI( return GroupedOpenApi .builder() .group("openapi") - .addOpenApiCustomiser(jhipsterOpenApiCustomizer) + .addOpenApiCustomizer(jhipsterOpenApiCustomizer) .packagesToScan(API_FIRST_PACKAGE) .pathsToMatch(properties.getDefaultIncludePattern()) .build(); diff --git a/src/main/java/io/github/bbortt/event/planner/config/SecurityConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/SecurityConfiguration.java index d719be11e..b89ac70b3 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/SecurityConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/SecurityConfiguration.java @@ -1,106 +1,106 @@ package io.github.bbortt.event.planner.config; -import io.github.bbortt.event.planner.security.*; +import io.github.bbortt.event.planner.security.AuthoritiesConstants; import io.github.bbortt.event.planner.security.SecurityUtils; import io.github.bbortt.event.planner.security.oauth2.AudienceValidator; import io.github.bbortt.event.planner.security.oauth2.CustomClaimConverter; import io.github.bbortt.event.planner.security.oauth2.JwtGrantedAuthorityConverter; -import java.util.*; +import io.github.bbortt.event.planner.web.filter.SpaWebFilter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; -import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; -import org.springframework.security.oauth2.jwt.*; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtDecoders; +import org.springframework.security.oauth2.jwt.JwtValidators; +import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; -import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; -import org.springframework.web.filter.CorsFilter; -import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport; import tech.jhipster.config.JHipsterProperties; +import tech.jhipster.web.filter.CookieCsrfFilter; -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -@Import(SecurityProblemSupport.class) +import java.util.HashSet; +import java.util.Set; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableMethodSecurity(securedEnabled = true) public class SecurityConfiguration { private final JHipsterProperties jHipsterProperties; - private final CorsFilter corsFilter; - @Value("${spring.security.oauth2.client.provider.oidc.issuer-uri}") private String issuerUri; - private final SecurityProblemSupport problemSupport; - - public SecurityConfiguration(CorsFilter corsFilter, JHipsterProperties jHipsterProperties, SecurityProblemSupport problemSupport) { - this.corsFilter = corsFilter; - this.problemSupport = problemSupport; + public SecurityConfiguration(JHipsterProperties jHipsterProperties) { this.jHipsterProperties = jHipsterProperties; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - // @formatter:off http - .csrf() - .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) - .and() - .addFilterBefore(corsFilter, CsrfFilter.class) - .exceptionHandling() - .authenticationEntryPoint(problemSupport) - .accessDeniedHandler(problemSupport) - .and() - .headers() - .contentSecurityPolicy(jHipsterProperties.getSecurity().getContentSecurityPolicy()) - .and() - .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN) - .and() - .permissionsPolicy().policy("camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()") - .and() - .frameOptions().sameOrigin() - .and() - .authorizeRequests() - .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() - .antMatchers("/app/**/*.{js,html}").permitAll() - .antMatchers("/i18n/**").permitAll() - .antMatchers("/content/**").permitAll() - .antMatchers("/swagger-ui/**").permitAll() - .antMatchers("/test/**").permitAll() - .antMatchers("/api/authenticate").permitAll() - .antMatchers("/api/auth-info").permitAll() - .antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN) - .antMatchers("/api/**").authenticated() - .antMatchers("/websocket/**").authenticated() - .antMatchers("/management/health").permitAll() - .antMatchers("/management/health/**").permitAll() - .antMatchers("/management/info").permitAll() - .antMatchers("/management/prometheus").permitAll() - .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) - .and() - .oauth2Login() - .and() - .oauth2ResourceServer() - .jwt() - .jwtAuthenticationConverter(authenticationConverter()) - .and() - .and() - .oauth2Client(); + .cors(withDefaults()) + .csrf(csrf -> + csrf + .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) + // See https://stackoverflow.com/q/74447118/65681 + .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()) + ) + .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) + .addFilterAfter(new CookieCsrfFilter(), BasicAuthenticationFilter.class) + .headers(headers -> + headers + .contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy())) + .frameOptions(FrameOptionsConfig::sameOrigin) + .referrerPolicy(referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)) + .permissionsPolicy(permissions -> + permissions.policy( + "camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()" + ) + ) + ) + .authorizeHttpRequests(authz -> + // prettier-ignore + authz + .requestMatchers("/", "/index.html", "/*.js", "/*.map", "/*.css").permitAll() + .requestMatchers("/*.ico", "/*.png", "/*.svg", "/*.webapp").permitAll() + .requestMatchers("/app/**").permitAll() + .requestMatchers("/i18n/**").permitAll() + .requestMatchers("/content/**").permitAll() + .requestMatchers("/swagger-ui/**").permitAll() + .requestMatchers("/api/authenticate").permitAll() + .requestMatchers("/api/auth-info").permitAll() + .requestMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN) + .requestMatchers("/api/**").authenticated() + .requestMatchers("/websocket/**").authenticated() + .requestMatchers("/v3/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN) + .requestMatchers("/management/health").permitAll() + .requestMatchers("/management/health/**").permitAll() + .requestMatchers("/management/info").permitAll() + .requestMatchers("/management/prometheus").permitAll() + .requestMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) + ) + .oauth2Login(withDefaults()) + .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(authenticationConverter()))) + .oauth2Client(); return http.build(); - // @formatter:on } Converter authenticationConverter() { diff --git a/src/main/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfiguration.java index 1b486c0da..1fe5d641b 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfiguration.java @@ -1,6 +1,5 @@ package io.github.bbortt.event.planner.config; -import java.util.concurrent.TimeUnit; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.http.CacheControl; @@ -10,11 +9,13 @@ import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; +import java.util.concurrent.TimeUnit; + @Configuration -@Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION }) +@Profile({JHipsterConstants.SPRING_PROFILE_PRODUCTION}) public class StaticResourcesWebConfiguration implements WebMvcConfigurer { - protected static final String[] RESOURCE_LOCATIONS = new String[] { + protected static final String[] RESOURCE_LOCATIONS = new String[]{ "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/", diff --git a/src/main/java/io/github/bbortt/event/planner/config/WebConfigurer.java b/src/main/java/io/github/bbortt/event/planner/config/WebConfigurer.java index 34cc43a6f..66cd8a122 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/WebConfigurer.java +++ b/src/main/java/io/github/bbortt/event/planner/config/WebConfigurer.java @@ -1,12 +1,7 @@ package io.github.bbortt.event.planner.config; -import static java.net.URLDecoder.decode; - -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.server.WebServerFactory; @@ -22,6 +17,12 @@ import org.springframework.web.filter.CorsFilter; import tech.jhipster.config.JHipsterProperties; +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; + +import static java.net.URLDecoder.decode; + /** * Configuration of web application with Servlet 3.0 APIs. */ @@ -58,8 +59,7 @@ public void customize(WebServerFactory server) { } private void setLocationForStaticAssets(WebServerFactory server) { - if (server instanceof ConfigurableServletWebServerFactory) { - ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server; + if (server instanceof ConfigurableServletWebServerFactory servletWebServer) { File root; String prefixPath = resolvePathPrefix(); root = new File(prefixPath + "build/resources/main/static/"); @@ -73,7 +73,7 @@ private void setLocationForStaticAssets(WebServerFactory server) { * Resolve path prefix to static resources. */ private String resolvePathPrefix() { - String fullExecutablePath = decode(getClass().getResource("").getPath(), StandardCharsets.UTF_8); + String fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8); String rootPath = Paths.get(".").toUri().normalize().getPath(); String extractedPath = fullExecutablePath.replace(rootPath, ""); int extractionEndIndex = extractedPath.indexOf("build/"); diff --git a/src/main/java/io/github/bbortt/event/planner/config/WebsocketConfiguration.java b/src/main/java/io/github/bbortt/event/planner/config/WebsocketConfiguration.java index adb03f299..27390478c 100644 --- a/src/main/java/io/github/bbortt/event/planner/config/WebsocketConfiguration.java +++ b/src/main/java/io/github/bbortt/event/planner/config/WebsocketConfiguration.java @@ -1,20 +1,28 @@ package io.github.bbortt.event.planner.config; import io.github.bbortt.event.planner.security.AuthoritiesConstants; -import java.security.Principal; -import java.util.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.server.*; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.web.socket.WebSocketHandler; -import org.springframework.web.socket.config.annotation.*; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.server.HandshakeInterceptor; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; import tech.jhipster.config.JHipsterProperties; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; + @Configuration @EnableWebSocketMessageBroker public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer { diff --git a/src/main/java/io/github/bbortt/event/planner/domain/AbstractAuditingEntity.java b/src/main/java/io/github/bbortt/event/planner/domain/AbstractAuditingEntity.java index 84e06b436..fa08e8e47 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/AbstractAuditingEntity.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/AbstractAuditingEntity.java @@ -2,24 +2,25 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.github.bbortt.event.planner.audit.EntityAuditEventListener; -import java.io.Serializable; -import java.time.Instant; -import javax.persistence.Column; -import javax.persistence.EntityListeners; -import javax.persistence.MappedSuperclass; +import jakarta.persistence.Column; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.MappedSuperclass; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import java.io.Serializable; +import java.time.Instant; + /** * Base abstract class for entities which will hold definitions for created, last modified, created by, * last modified by attributes. */ @MappedSuperclass -@EntityListeners({ AuditingEntityListener.class, EntityAuditEventListener.class }) -@JsonIgnoreProperties(value = { "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" }, allowGetters = true) +@EntityListeners({AuditingEntityListener.class, EntityAuditEventListener.class}) +@JsonIgnoreProperties(value = {"createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate"}, allowGetters = true) public abstract class AbstractAuditingEntity implements Serializable { private static final long serialVersionUID = 1L; diff --git a/src/main/java/io/github/bbortt/event/planner/domain/Authority.java b/src/main/java/io/github/bbortt/event/planner/domain/Authority.java index 4b5a825b7..ebea29b92 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/Authority.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/Authority.java @@ -1,13 +1,14 @@ package io.github.bbortt.event.planner.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; /** * An authority (a security role) used by Spring Security. diff --git a/src/main/java/io/github/bbortt/event/planner/domain/EntityAuditEvent.java b/src/main/java/io/github/bbortt/event/planner/domain/EntityAuditEvent.java index 7e18809bf..6eb2daa61 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/EntityAuditEvent.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/EntityAuditEvent.java @@ -1,13 +1,20 @@ package io.github.bbortt.event.planner.domain; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; + import java.io.Serializable; import java.time.Instant; import java.util.Objects; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "jhi_entity_audit_event") diff --git a/src/main/java/io/github/bbortt/event/planner/domain/Event.java b/src/main/java/io/github/bbortt/event/planner/domain/Event.java index ebfb5d9a8..73b0fa48d 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/Event.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/Event.java @@ -1,17 +1,18 @@ package io.github.bbortt.event.planner.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; /** * A Event. diff --git a/src/main/java/io/github/bbortt/event/planner/domain/Location.java b/src/main/java/io/github/bbortt/event/planner/domain/Location.java index 2533a5ae0..6c9e2d1db 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/Location.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/Location.java @@ -2,21 +2,22 @@ import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.util.HashSet; import java.util.Objects; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; /** * A Location. diff --git a/src/main/java/io/github/bbortt/event/planner/domain/Member.java b/src/main/java/io/github/bbortt/event/planner/domain/Member.java index 1c92e4678..706046894 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/Member.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/Member.java @@ -2,28 +2,29 @@ import io.github.bbortt.event.planner.audit.EntityAuditEventListener; import io.github.bbortt.event.planner.security.SecurityUtils; -import java.io.Serializable; -import java.time.Instant; -import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.PreUpdate; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.persistence.UniqueConstraint; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.persistence.UniqueConstraint; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import java.io.Serializable; +import java.time.Instant; +import java.util.Objects; + /** * A Member. */ @@ -31,8 +32,8 @@ @Table( name = "member", uniqueConstraints = { - @UniqueConstraint(name = "ux_invitation_per_project", columnNames = { "invited_email", "project_id" }), - @UniqueConstraint(name = "ux_accepted_per_project", columnNames = { "accepted_by", "project_id" }), + @UniqueConstraint(name = "ux_invitation_per_project", columnNames = {"invited_email", "project_id"}), + @UniqueConstraint(name = "ux_accepted_per_project", columnNames = {"accepted_by", "project_id"}), } ) @EntityListeners({ AuditingEntityListener.class, EntityAuditEventListener.class }) diff --git a/src/main/java/io/github/bbortt/event/planner/domain/Project.java b/src/main/java/io/github/bbortt/event/planner/domain/Project.java index 1a2878c91..d798ab173 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/Project.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/Project.java @@ -1,14 +1,22 @@ package io.github.bbortt.event.planner.domain; import com.fasterxml.jackson.annotation.JsonBackReference; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Set; import java.util.UUID; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; /** * A Project. diff --git a/src/main/java/io/github/bbortt/event/planner/domain/User.java b/src/main/java/io/github/bbortt/event/planner/domain/User.java index 496b69d71..b6ec37f45 100644 --- a/src/main/java/io/github/bbortt/event/planner/domain/User.java +++ b/src/main/java/io/github/bbortt/event/planner/domain/User.java @@ -2,17 +2,24 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import io.github.bbortt.event.planner.config.Constants; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.annotations.BatchSize; + import java.io.Serializable; import java.util.HashSet; import java.util.Locale; import java.util.Set; -import javax.persistence.*; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.annotations.BatchSize; /** * A user. diff --git a/src/main/java/io/github/bbortt/event/planner/mail/MailService.java b/src/main/java/io/github/bbortt/event/planner/mail/MailService.java index 7d4dd4cfe..67811563f 100644 --- a/src/main/java/io/github/bbortt/event/planner/mail/MailService.java +++ b/src/main/java/io/github/bbortt/event/planner/mail/MailService.java @@ -2,11 +2,9 @@ import io.github.bbortt.event.planner.service.dto.MemberDTO; import io.github.bbortt.event.planner.service.dto.ProjectDTO; -import java.nio.charset.StandardCharsets; -import java.util.Optional; -import javax.annotation.Nullable; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; +import jakarta.annotation.Nullable; +import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -15,11 +13,14 @@ import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; +import java.nio.charset.StandardCharsets; +import java.util.Optional; + @Lazy @Service public class MailService { - private final Logger log = LoggerFactory.getLogger(MailService.class); + private static final Logger logger = LoggerFactory.getLogger(MailService.class); private final ProjectInvitationMailFactory projectInvitationMailFactory; private final Optional javaMailSender; @@ -33,7 +34,7 @@ public MailService( } public void sendProjectInvitationEmail(MemberDTO memberDTO) { - log.info("Request to send project invitation email to new member: {}", memberDTO); + logger.info("Request to send project invitation email to new member: {}", memberDTO); ProjectDTO projectDTO = memberDTO.getProject(); @@ -48,8 +49,8 @@ public void sendProjectInvitationEmail(MemberDTO memberDTO) { } private void logEmailConfigurationForDisabledMailing(EmailConfiguration emailConfiguration) { - if (javaMailSender.isEmpty() && !log.isDebugEnabled()) { - log.info( + if (javaMailSender.isEmpty() && !logger.isDebugEnabled()) { + logger.info( "Mailing is disabled, invitation link sent to '{}' would be:\n{}", emailConfiguration.toEmail(), emailConfiguration.htmlContent() @@ -58,21 +59,21 @@ private void logEmailConfigurationForDisabledMailing(EmailConfiguration emailCon } private void sendProjectInvitationEmail(EmailConfiguration emailConfiguration, JavaMailSender mailSender) { - if (log.isDebugEnabled()) { - log.debug("Send project invitation email to '{}':\n{}", emailConfiguration.toEmail(), emailConfiguration.htmlContent()); + if (logger.isDebugEnabled()) { + logger.debug("Send project invitation email to '{}':\n{}", emailConfiguration.toEmail(), emailConfiguration.htmlContent()); } try { mailSender.send(getMimeMessage(emailConfiguration, mailSender)); } catch (MessagingException e) { - log.error("Failed to create email '{}' to '{}'!", emailConfiguration.subject(), emailConfiguration.toEmail(), e); + logger.error("Failed to create email '{}' to '{}'!", emailConfiguration.subject(), emailConfiguration.toEmail(), e); throw new IllegalArgumentException("Failed to create email!", e); } } private MimeMessage getMimeMessage(EmailConfiguration emailConfiguration, JavaMailSender mailSender) throws MessagingException { - if (log.isDebugEnabled()) { - log.debug( + if (logger.isDebugEnabled()) { + logger.debug( "Construct MIME message for message with subject '{}' to '{}'", emailConfiguration.subject(), emailConfiguration.toEmail() diff --git a/src/main/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactory.java b/src/main/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactory.java index 2769b2ecf..205530593 100644 --- a/src/main/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactory.java +++ b/src/main/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactory.java @@ -12,7 +12,7 @@ @Component public class ProjectInvitationMailFactory { - private final Logger log = LoggerFactory.getLogger(ProjectInvitationMailFactory.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectInvitationMailFactory.class); private static final String TEMPLATE_LOCATION = "mail/project-invitation.html"; @@ -36,7 +36,7 @@ public ProjectInvitationMailFactory( } public EmailConfiguration getEmailConfiguration(String invitedEmail, String projectName, String projectToken) { - log.info("Configure project invitation email"); + logger.info("Configure project invitation email"); return new EmailConfiguration( mailProperties.getFrom(), invitedEmail, @@ -46,7 +46,7 @@ public EmailConfiguration getEmailConfiguration(String invitedEmail, String proj } private String loadHtmlContent(String invitedEmail, String projectName, String projectToken) { - log.debug("Load html content"); + logger.debug("Load html content"); Context context = new Context( localeResolver.resolveLocale( diff --git a/src/main/java/io/github/bbortt/event/planner/mail/ServletRequestUtil.java b/src/main/java/io/github/bbortt/event/planner/mail/ServletRequestUtil.java index e8e5d140e..0a5866cce 100644 --- a/src/main/java/io/github/bbortt/event/planner/mail/ServletRequestUtil.java +++ b/src/main/java/io/github/bbortt/event/planner/mail/ServletRequestUtil.java @@ -1,10 +1,11 @@ package io.github.bbortt.event.planner.mail; -import java.util.Optional; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import java.util.Optional; + class ServletRequestUtil { Optional getCurrentHttpRequest() { diff --git a/src/main/java/io/github/bbortt/event/planner/repository/EventRepository.java b/src/main/java/io/github/bbortt/event/planner/repository/EventRepository.java index c9ae26e6b..2c047b539 100644 --- a/src/main/java/io/github/bbortt/event/planner/repository/EventRepository.java +++ b/src/main/java/io/github/bbortt/event/planner/repository/EventRepository.java @@ -1,14 +1,16 @@ package io.github.bbortt.event.planner.repository; import io.github.bbortt.event.planner.domain.Event; -import java.util.List; -import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.*; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.List; +import java.util.Optional; + /** * Spring Data JPA repository for the Event entity. */ diff --git a/src/main/java/io/github/bbortt/event/planner/repository/LocationRepository.java b/src/main/java/io/github/bbortt/event/planner/repository/LocationRepository.java index 09bad1fd1..be46f34c2 100644 --- a/src/main/java/io/github/bbortt/event/planner/repository/LocationRepository.java +++ b/src/main/java/io/github/bbortt/event/planner/repository/LocationRepository.java @@ -1,14 +1,17 @@ package io.github.bbortt.event.planner.repository; import io.github.bbortt.event.planner.domain.Location; -import java.util.List; -import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.*; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.List; +import java.util.Optional; + /** * Spring Data JPA repository for the Location entity. */ diff --git a/src/main/java/io/github/bbortt/event/planner/repository/MemberRepository.java b/src/main/java/io/github/bbortt/event/planner/repository/MemberRepository.java index 958189099..7dde86b8d 100644 --- a/src/main/java/io/github/bbortt/event/planner/repository/MemberRepository.java +++ b/src/main/java/io/github/bbortt/event/planner/repository/MemberRepository.java @@ -1,13 +1,16 @@ package io.github.bbortt.event.planner.repository; import io.github.bbortt.event.planner.domain.Member; -import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.*; +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import java.util.Optional; + /** * Spring Data JPA repository for the Member entity. */ diff --git a/src/main/java/io/github/bbortt/event/planner/security/oauth2/AudienceValidator.java b/src/main/java/io/github/bbortt/event/planner/security/oauth2/AudienceValidator.java index 9a22cfa08..42a1ee10d 100644 --- a/src/main/java/io/github/bbortt/event/planner/security/oauth2/AudienceValidator.java +++ b/src/main/java/io/github/bbortt/event/planner/security/oauth2/AudienceValidator.java @@ -11,7 +11,7 @@ public class AudienceValidator implements OAuth2TokenValidator { - private final Logger log = LoggerFactory.getLogger(AudienceValidator.class); + private static final Logger logger = LoggerFactory.getLogger(AudienceValidator.class); private final OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null); private final List allowedAudience; @@ -26,7 +26,7 @@ public OAuth2TokenValidatorResult validate(Jwt jwt) { if (audience.stream().anyMatch(allowedAudience::contains)) { return OAuth2TokenValidatorResult.success(); } else { - log.warn("Invalid audience: {}", audience); + logger.warn("Invalid audience: {}", audience); return OAuth2TokenValidatorResult.failure(error); } } diff --git a/src/main/java/io/github/bbortt/event/planner/service/EventService.java b/src/main/java/io/github/bbortt/event/planner/service/EventService.java index 531c83fec..2471c9a3c 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/EventService.java +++ b/src/main/java/io/github/bbortt/event/planner/service/EventService.java @@ -20,7 +20,7 @@ @Transactional public class EventService { - private final Logger log = LoggerFactory.getLogger(EventService.class); + private static final Logger logger = LoggerFactory.getLogger(EventService.class); private final EventRepository eventRepository; @@ -38,7 +38,7 @@ public EventService(EventRepository eventRepository, EventMapper eventMapper) { * @return the persisted entity. */ public EventDTO save(EventDTO eventDTO) { - log.debug("Request to save Event : {}", eventDTO); + logger.debug("Request to save Event : {}", eventDTO); Event event = eventMapper.toEntity(eventDTO); event = eventRepository.save(event); return eventMapper.toDto(event); @@ -51,7 +51,7 @@ public EventDTO save(EventDTO eventDTO) { * @return the persisted entity. */ public EventDTO update(EventDTO eventDTO) { - log.debug("Request to update Event : {}", eventDTO); + logger.debug("Request to update Event : {}", eventDTO); Event event = eventMapper.toEntity(eventDTO); event = eventRepository.save(event); return eventMapper.toDto(event); @@ -64,7 +64,7 @@ public EventDTO update(EventDTO eventDTO) { * @return the persisted entity. */ public Optional partialUpdate(EventDTO eventDTO) { - log.debug("Request to partially update Event : {}", eventDTO); + logger.debug("Request to partially update Event : {}", eventDTO); return eventRepository .findById(eventDTO.getId()) @@ -85,7 +85,7 @@ public Optional partialUpdate(EventDTO eventDTO) { */ @Transactional(readOnly = true) public Page findAll(Pageable pageable) { - log.debug("Request to get all Events"); + logger.debug("Request to get all Events"); return eventRepository.findAll(pageable).map(eventMapper::toDto); } @@ -106,7 +106,7 @@ public Page findAllWithEagerRelationships(Pageable pageable) { */ @Transactional(readOnly = true) public Optional findOne(Long id) { - log.debug("Request to get Event : {}", id); + logger.debug("Request to get Event : {}", id); return eventRepository.findOneWithEagerRelationships(id).map(eventMapper::toDto); } @@ -116,7 +116,7 @@ public Optional findOne(Long id) { * @param id the id of the entity. */ public void delete(Long id) { - log.debug("Request to delete Event : {}", id); + logger.debug("Request to delete Event : {}", id); eventRepository.deleteById(id); } @@ -129,7 +129,7 @@ public void delete(Long id) { @Transactional(readOnly = true) @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public Page findAllInProject(Long projectId, Pageable pageable) { - log.debug("Request to get a page of Locations in Project '{}'", projectId); + logger.debug("Request to get a page of Locations in Project '{}'", projectId); return eventRepository.findAllByLocation_Project_IdEquals(projectId, pageable).map(eventMapper::toDto); } } diff --git a/src/main/java/io/github/bbortt/event/planner/service/LocationService.java b/src/main/java/io/github/bbortt/event/planner/service/LocationService.java index ec5c3ad90..b8f96a806 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/LocationService.java +++ b/src/main/java/io/github/bbortt/event/planner/service/LocationService.java @@ -23,7 +23,7 @@ @Transactional public class LocationService { - private final Logger log = LoggerFactory.getLogger(LocationService.class); + private static final Logger logger = LoggerFactory.getLogger(LocationService.class); private final LocationRepository locationRepository; @@ -41,7 +41,7 @@ public LocationService(LocationRepository locationRepository, LocationMapper loc * @return the persisted entity. */ public LocationDTO save(LocationDTO locationDTO) { - log.debug("Request to save Location : {}", locationDTO); + logger.debug("Request to save Location : {}", locationDTO); Location location = locationMapper.toEntity(locationDTO); location = locationRepository.save(location); return locationMapper.toDto(location); @@ -54,7 +54,7 @@ public LocationDTO save(LocationDTO locationDTO) { * @return the persisted entity. */ public LocationDTO update(LocationDTO locationDTO) { - log.debug("Request to update Location : {}", locationDTO); + logger.debug("Request to update Location : {}", locationDTO); Location location = locationMapper.toEntity(locationDTO); location = locationRepository.save(location); return locationMapper.toDto(location); @@ -67,7 +67,7 @@ public LocationDTO update(LocationDTO locationDTO) { * @return the persisted entity. */ public Optional partialUpdate(LocationDTO locationDTO) { - log.debug("Request to partially update Location : {}", locationDTO); + logger.debug("Request to partially update Location : {}", locationDTO); return locationRepository .findById(locationDTO.getId()) @@ -88,7 +88,7 @@ public Optional partialUpdate(LocationDTO locationDTO) { */ @Transactional(readOnly = true) public Page findAll(Pageable pageable) { - log.debug("Request to get all Locations"); + logger.debug("Request to get all Locations"); return locationRepository.findAll(pageable).map(locationMapper::toDto); } @@ -109,7 +109,7 @@ public Page findAllWithEagerRelationships(Pageable pageable) { */ @Transactional(readOnly = true) public Optional findOne(Long id) { - log.debug("Request to get Location : {}", id); + logger.debug("Request to get Location : {}", id); return locationRepository.findOneWithEagerRelationships(id).map(locationMapper::toDto); } @@ -119,7 +119,7 @@ public Optional findOne(Long id) { * @param id the id of the entity. */ public void delete(Long id) { - log.debug("Request to delete Location : {}", id); + logger.debug("Request to delete Location : {}", id); locationRepository.deleteById(id); } @@ -133,7 +133,7 @@ public void delete(Long id) { @Transactional(readOnly = true) @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public List findAllInProject(Long projectId) { - log.debug("Request to get all Locations in Project '{}'", projectId); + logger.debug("Request to get all Locations in Project '{}'", projectId); return locationRepository.findAllByParentIsNullAndProject_IdEquals(projectId).stream().map(locationMapper::toDto).toList(); } @@ -148,7 +148,7 @@ public List findAllInProject(Long projectId) { @Transactional(readOnly = true) @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public List findAllInProjectExceptThis(Long projectId, Long locationId) { - log.debug("Request to get all Locations except '{}' in Project '{}'", locationId, projectId); + logger.debug("Request to get all Locations except '{}' in Project '{}'", locationId, projectId); return locationRepository .findAllByParentIsNullAndProject_IdEquals(projectId) .stream() @@ -162,8 +162,8 @@ public List findAllInProjectExceptThis(Long projectId, Long locatio } private Set dropLocationsMatchingId(Set locations, Long locationId) { - if (log.isTraceEnabled()) { - log.trace("Filter Locations by id '{}': {}", locationId, locations); + if (logger.isTraceEnabled()) { + logger.trace("Filter Locations by id '{}': {}", locationId, locations); } return locations diff --git a/src/main/java/io/github/bbortt/event/planner/service/MemberService.java b/src/main/java/io/github/bbortt/event/planner/service/MemberService.java index 76cb3f6d5..6df4ea7fc 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/MemberService.java +++ b/src/main/java/io/github/bbortt/event/planner/service/MemberService.java @@ -7,8 +7,7 @@ import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.service.mapper.MemberMapper; import io.github.bbortt.event.planner.service.mapper.ProjectMapper; -import java.util.Optional; -import javax.annotation.Nonnull; +import jakarta.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -18,13 +17,15 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.util.Optional; + /** * Service Implementation for managing {@link Member}. */ @Service public class MemberService { - private final Logger log = LoggerFactory.getLogger(MemberService.class); + private static final Logger logger = LoggerFactory.getLogger(MemberService.class); private final MemberRepository memberRepository; @@ -53,7 +54,7 @@ public MemberService( @Modifying @Transactional public MemberDTO save(MemberDTO memberDTO) { - log.debug("Request to save Member : {}", memberDTO); + logger.debug("Request to save Member : {}", memberDTO); Member member = memberMapper.toEntity(memberDTO); // Sanitize new membership @@ -71,7 +72,7 @@ public MemberDTO save(MemberDTO memberDTO) { @Modifying @Transactional public MemberDTO update(MemberDTO memberDTO) { - log.debug("Request to update Member : {}", memberDTO); + logger.debug("Request to update Member : {}", memberDTO); Member member = memberMapper.toEntity(memberDTO); member = memberRepository.save(member); return memberMapper.toDto(member); @@ -86,7 +87,7 @@ public MemberDTO update(MemberDTO memberDTO) { @Modifying @Transactional public Optional partialUpdate(MemberDTO memberDTO) { - log.debug("Request to partially update Member : {}", memberDTO); + logger.debug("Request to partially update Member : {}", memberDTO); return memberRepository .findById(memberDTO.getId()) @@ -107,7 +108,7 @@ public Optional partialUpdate(MemberDTO memberDTO) { */ @Transactional(readOnly = true) public Page findAll(Pageable pageable) { - log.debug("Request to get all Members"); + logger.debug("Request to get all Members"); return memberRepository.findAll(pageable).map(memberMapper::toDto); } @@ -129,7 +130,7 @@ public Page findAllWithEagerRelationships(Pageable pageable) { */ @Transactional(readOnly = true) public Optional findOne(Long id) { - log.debug("Request to get Member : {}", id); + logger.debug("Request to get Member : {}", id); return memberRepository.findOneWithEagerRelationships(id).map(memberMapper::toDto); } @@ -141,7 +142,7 @@ public Optional findOne(Long id) { @Modifying @Transactional public void delete(Long id) { - log.debug("Request to delete Member : {}", id); + logger.debug("Request to delete Member : {}", id); memberRepository.deleteById(id); } @@ -156,7 +157,7 @@ public void delete(Long id) { @Transactional(readOnly = true) @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public Page findAllInProject(Long projectId, Pageable pageable) { - log.debug("Request to get a page of Members in Project '{}'", projectId); + logger.debug("Request to get a page of Members in Project '{}'", projectId); return memberRepository.findAllByProjectIdEquals(projectId, pageable).map(memberMapper::toDto); } @@ -169,7 +170,7 @@ public Page findAllInProject(Long projectId, Pageable pageable) { * @return the entity. */ public Optional findOneInProjectByInvitationEmail(Long projectId, String invitedEmail) { - log.debug("Request to get Member with email '{}' in Project '{}'", invitedEmail, projectId); + logger.debug("Request to get Member with email '{}' in Project '{}'", invitedEmail, projectId); return memberRepository.findMemberInProject(invitedEmail, projectId).map(memberMapper::toDto); } @@ -185,7 +186,7 @@ public Optional findOneInProjectByInvitationEmail(Long projectId, Str @Transactional @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public MemberDTO inviteToProject(String email, @Nonnull ProjectDTO project) { - log.debug("Request to invite Member '{}' to Project '{}'", email, project); + logger.debug("Request to invite Member '{}' to Project '{}'", email, project); MemberDTO memberDTO = memberMapper.toDto( memberRepository.save(new Member().accepted(Boolean.FALSE).invitedEmail(email).project(projectMapper.toEntity(project))) diff --git a/src/main/java/io/github/bbortt/event/planner/service/ProjectService.java b/src/main/java/io/github/bbortt/event/planner/service/ProjectService.java index c299d1a1d..e28c8849a 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/ProjectService.java +++ b/src/main/java/io/github/bbortt/event/planner/service/ProjectService.java @@ -25,7 +25,7 @@ @Service public class ProjectService { - private final Logger log = LoggerFactory.getLogger(ProjectService.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectService.class); private final ProjectRepository projectRepository; @@ -45,7 +45,7 @@ public ProjectService(ProjectRepository projectRepository, ProjectMapper project @Modifying @Transactional public ProjectDTO save(ProjectDTO projectDTO) { - log.debug("Request to save Project : {}", projectDTO); + logger.debug("Request to save Project : {}", projectDTO); Project project = projectMapper.toEntity(projectDTO); // Sanitize new project @@ -63,7 +63,7 @@ public ProjectDTO save(ProjectDTO projectDTO) { @Modifying @Transactional public ProjectDTO update(ProjectDTO projectDTO) { - log.debug("Request to update Project : {}", projectDTO); + logger.debug("Request to update Project : {}", projectDTO); Project project = projectMapper.toEntity(projectDTO); project = projectRepository.save(project); return projectMapper.toDto(project); @@ -78,7 +78,7 @@ public ProjectDTO update(ProjectDTO projectDTO) { @Modifying @Transactional public Optional partialUpdate(ProjectDTO projectDTO) { - log.debug("Request to partially update Project : {}", projectDTO); + logger.debug("Request to partially update Project : {}", projectDTO); return projectRepository .findById(projectDTO.getId()) @@ -99,7 +99,7 @@ public Optional partialUpdate(ProjectDTO projectDTO) { */ @Transactional(readOnly = true) public boolean exists(Long projectId) { - log.debug("Request to check if Project with id '{}' exists", projectId); + logger.debug("Request to check if Project with id '{}' exists", projectId); return projectRepository.existsById(projectId); } @@ -111,7 +111,7 @@ public boolean exists(Long projectId) { */ @Transactional(readOnly = true) public Page findAll(Pageable pageable) { - log.debug("Request to get all Projects"); + logger.debug("Request to get all Projects"); return projectRepository.findAll(pageable).map(projectMapper::toDto); } @@ -123,7 +123,7 @@ public Page findAll(Pageable pageable) { */ @Transactional(readOnly = true) public Optional findOne(Long id) { - log.debug("Request to get Project : {}", id); + logger.debug("Request to get Project : {}", id); return projectRepository.findById(id).map(projectMapper::toDto); } @@ -135,16 +135,16 @@ public Optional findOne(Long id) { */ @Transactional(readOnly = true) public ProjectDTO findOneOrThrowEntityNotFoundAlertException(Long id) { - log.debug("Request to get Project : {}", id); + logger.debug("Request to get Project : {}", id); Optional project = findOne(id); if (project.isEmpty()) { - log.warn("Project {} does not exist!", id); + logger.warn("Project {} does not exist!", id); throw new EntityNotFoundAlertException("Entity not found", ProjectApiDelegateImpl.ENTITY_NAME, "idnotfound"); } - return project.get(); + return project.orElseThrow(IllegalArgumentException::new); } /** @@ -155,7 +155,7 @@ public ProjectDTO findOneOrThrowEntityNotFoundAlertException(Long id) { */ @Transactional(readOnly = true) public Optional findOneByToken(String token) { - log.debug("Request to get Project by token: {}", token); + logger.debug("Request to get Project by token: {}", token); return projectRepository.findByToken(UUID.fromString(token)).map(projectMapper::toDto); } @@ -168,11 +168,11 @@ public Optional findOneByToken(String token) { @Transactional(readOnly = true) @PreAuthorize("T(io.github.bbortt.event.planner.security.SecurityUtils).isAuthenticated()") public Slice findAllNotArchivedForCurrentUser(Pageable pageable) { - log.debug("Request to get all Projects for current user"); + logger.debug("Request to get all Projects for current user"); String login = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new IllegalArgumentException("Cannot find current user!")); - if (log.isTraceEnabled()) { - log.trace("Current login is '{}'", login); + if (logger.isTraceEnabled()) { + logger.trace("Current login is '{}'", login); } return projectRepository.findByUsernameParticipatingIn(login, pageable).map(projectMapper::toDto); @@ -186,7 +186,7 @@ public Slice findAllNotArchivedForCurrentUser(Pageable pageable) { @Modifying @Transactional public void delete(Long id) { - log.debug("Request to delete Project : {}", id); + logger.debug("Request to delete Project : {}", id); projectRepository.deleteById(id); } } diff --git a/src/main/java/io/github/bbortt/event/planner/service/UserService.java b/src/main/java/io/github/bbortt/event/planner/service/UserService.java index 13f12d281..def2ec18f 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/UserService.java +++ b/src/main/java/io/github/bbortt/event/planner/service/UserService.java @@ -8,10 +8,7 @@ import io.github.bbortt.event.planner.security.SecurityUtils; import io.github.bbortt.event.planner.service.dto.AdminUserDTO; import io.github.bbortt.event.planner.service.dto.UserDTO; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; -import javax.annotation.Nullable; +import jakarta.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -25,6 +22,14 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + /** * Service class for managing users. */ @@ -32,7 +37,7 @@ @Transactional public class UserService { - private final Logger log = LoggerFactory.getLogger(UserService.class); + private static final Logger logger = LoggerFactory.getLogger(UserService.class); private final UserRepository userRepository; @@ -73,7 +78,7 @@ public void updateUser(String firstName, String lastName, String email, String l user.setLangKey(langKey); user.setImageUrl(imageUrl); this.clearUserCaches(user); - log.debug("Changed Information for User: {}", user); + logger.debug("Changed Information for User: {}", user); }); } @@ -107,7 +112,7 @@ private User syncUserWithIdP(Map details, User user) { Collection userAuthorities = user.getAuthorities().stream().map(Authority::getName).toList(); for (String authority : userAuthorities) { if (!dbAuthorities.contains(authority)) { - log.debug("Saving authority '{}' in local database", authority); + logger.debug("Saving authority '{}' in local database", authority); Authority authorityToSave = new Authority(); authorityToSave.setName(authority); authorityRepository.save(authorityToSave); @@ -118,7 +123,7 @@ private User syncUserWithIdP(Map details, User user) { if (existingUser.isPresent()) { // if IdP sends last updated information, use it to determine if an update should happen if (details.get("updated_at") != null) { - Instant dbModifiedDate = existingUser.get().getLastModifiedDate(); + Instant dbModifiedDate = existingUser.orElseThrow(IllegalArgumentException::new).getLastModifiedDate(); Instant idpModifiedDate; if (details.get("updated_at") instanceof Instant) { idpModifiedDate = (Instant) details.get("updated_at"); @@ -126,16 +131,16 @@ private User syncUserWithIdP(Map details, User user) { idpModifiedDate = Instant.ofEpochSecond((Integer) details.get("updated_at")); } if (idpModifiedDate.isAfter(dbModifiedDate)) { - log.debug("Updating user '{}' in local database", user.getLogin()); + logger.debug("Updating user '{}' in local database", user.getLogin()); updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), user.getLangKey(), user.getImageUrl()); } // no last updated info, blindly update } else { - log.debug("Updating user '{}' in local database", user.getLogin()); + logger.debug("Updating user '{}' in local database", user.getLogin()); updateUser(user.getFirstName(), user.getLastName(), user.getEmail(), user.getLangKey(), user.getImageUrl()); } } else { - log.debug("Saving user '{}' in local database", user.getLogin()); + logger.debug("Saving user '{}' in local database", user.getLogin()); userRepository.save(user); this.clearUserCaches(user); } diff --git a/src/main/java/io/github/bbortt/event/planner/service/dto/AdminUserDTO.java b/src/main/java/io/github/bbortt/event/planner/service/dto/AdminUserDTO.java index 00de95344..dcb8ba10e 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/dto/AdminUserDTO.java +++ b/src/main/java/io/github/bbortt/event/planner/service/dto/AdminUserDTO.java @@ -3,11 +3,15 @@ import io.github.bbortt.event.planner.config.Constants; import io.github.bbortt.event.planner.domain.Authority; import io.github.bbortt.event.planner.domain.User; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.Set; import java.util.stream.Collectors; -import javax.validation.constraints.*; /** * A DTO representing a user, with his authorities. diff --git a/src/main/java/io/github/bbortt/event/planner/service/dto/EventDTO.java b/src/main/java/io/github/bbortt/event/planner/service/dto/EventDTO.java index 22ec4327f..092698576 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/dto/EventDTO.java +++ b/src/main/java/io/github/bbortt/event/planner/service/dto/EventDTO.java @@ -1,9 +1,11 @@ package io.github.bbortt.event.planner.service.dto; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.Objects; -import javax.validation.constraints.*; /** * A DTO for the {@link io.github.bbortt.event.planner.domain.Event} entity. diff --git a/src/main/java/io/github/bbortt/event/planner/service/dto/LocationDTO.java b/src/main/java/io/github/bbortt/event/planner/service/dto/LocationDTO.java index 2930d2aac..742848340 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/dto/LocationDTO.java +++ b/src/main/java/io/github/bbortt/event/planner/service/dto/LocationDTO.java @@ -1,10 +1,12 @@ package io.github.bbortt.event.planner.service.dto; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.List; import java.util.Objects; -import javax.validation.constraints.*; /** * A DTO for the {@link io.github.bbortt.event.planner.domain.Location} entity. diff --git a/src/main/java/io/github/bbortt/event/planner/service/dto/MemberDTO.java b/src/main/java/io/github/bbortt/event/planner/service/dto/MemberDTO.java index ad0271bd7..77370926a 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/dto/MemberDTO.java +++ b/src/main/java/io/github/bbortt/event/planner/service/dto/MemberDTO.java @@ -1,12 +1,13 @@ package io.github.bbortt.event.planner.service.dto; import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.Objects; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; /** * A DTO for the {@link io.github.bbortt.event.planner.domain.Member} entity. diff --git a/src/main/java/io/github/bbortt/event/planner/service/dto/ProjectDTO.java b/src/main/java/io/github/bbortt/event/planner/service/dto/ProjectDTO.java index ddd5affdb..990f76f9a 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/dto/ProjectDTO.java +++ b/src/main/java/io/github/bbortt/event/planner/service/dto/ProjectDTO.java @@ -1,10 +1,12 @@ package io.github.bbortt.event.planner.service.dto; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; + import java.io.Serializable; import java.time.Instant; import java.util.Objects; import java.util.UUID; -import javax.validation.constraints.*; /** * A DTO for the {@link io.github.bbortt.event.planner.domain.Project} entity. diff --git a/src/main/java/io/github/bbortt/event/planner/service/mapper/EventMapper.java b/src/main/java/io/github/bbortt/event/planner/service/mapper/EventMapper.java index 2938475fc..9d164aa6d 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/mapper/EventMapper.java +++ b/src/main/java/io/github/bbortt/event/planner/service/mapper/EventMapper.java @@ -4,7 +4,10 @@ import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.service.dto.EventDTO; import io.github.bbortt.event.planner.service.dto.LocationDTO; -import org.mapstruct.*; +import org.mapstruct.BeanMapping; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Named; /** * Mapper for the entity {@link Event} and its DTO {@link EventDTO}. diff --git a/src/main/java/io/github/bbortt/event/planner/service/mapper/ProjectMapper.java b/src/main/java/io/github/bbortt/event/planner/service/mapper/ProjectMapper.java index 10f385da0..f14c28ce0 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/mapper/ProjectMapper.java +++ b/src/main/java/io/github/bbortt/event/planner/service/mapper/ProjectMapper.java @@ -2,7 +2,12 @@ import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.service.dto.ProjectDTO; -import org.mapstruct.*; +import org.mapstruct.BeanMapping; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; +import org.mapstruct.Named; +import org.mapstruct.NullValuePropertyMappingStrategy; /** * Mapper for the entity {@link Project} and its DTO {@link ProjectDTO}. diff --git a/src/main/java/io/github/bbortt/event/planner/service/mapper/UserMapper.java b/src/main/java/io/github/bbortt/event/planner/service/mapper/UserMapper.java index 49ac32984..ae5fc2dff 100644 --- a/src/main/java/io/github/bbortt/event/planner/service/mapper/UserMapper.java +++ b/src/main/java/io/github/bbortt/event/planner/service/mapper/UserMapper.java @@ -4,13 +4,18 @@ import io.github.bbortt.event.planner.domain.User; import io.github.bbortt.event.planner.service.dto.AdminUserDTO; import io.github.bbortt.event.planner.service.dto.UserDTO; -import java.util.*; -import java.util.stream.Collectors; import org.mapstruct.BeanMapping; import org.mapstruct.Mapping; import org.mapstruct.Named; import org.springframework.stereotype.Service; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + /** * Mapper for the entity {@link User} and its DTO called {@link UserDTO}. * diff --git a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectApiDelegateImpl.java b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectApiDelegateImpl.java index 720b878a2..b3ec3b5ac 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectApiDelegateImpl.java +++ b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectApiDelegateImpl.java @@ -19,7 +19,7 @@ @RestController public class ProjectApiDelegateImpl implements ProjectApiDelegate { - private final Logger log = LoggerFactory.getLogger(ProjectApiDelegateImpl.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectApiDelegateImpl.class); public static final String ENTITY_NAME = "project"; private static final String PROJECT_ID_ATTRIBUTE_NAME = "id"; @@ -36,7 +36,7 @@ public ProjectApiDelegateImpl(ProjectService projectService, ApiProjectMapper ap @Override public ResponseEntity findProjectByToken(String projectToken) { - log.debug("REST request to get Project by token '{}'", projectToken); + logger.debug("REST request to get Project by token '{}'", projectToken); return ResponseUtil.wrapOrNotFound(projectService.findOneByToken(projectToken).map(apiProjectMapper::toApiDTO)); } @@ -47,7 +47,7 @@ public ResponseEntity getUserProjects( Optional pageNumber, Optional> sort ) { - log.debug("REST request to get a page of Projects"); + logger.debug("REST request to get a page of Projects"); Slice slice = projectService.findAllNotArchivedForCurrentUser( paginationUtil.createPagingInformation(pageSize, pageNumber, sort, PROJECT_ID_ATTRIBUTE_NAME) diff --git a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiDelegateImpl.java b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiDelegateImpl.java index 67f1396ea..787d9587d 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiDelegateImpl.java +++ b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiDelegateImpl.java @@ -20,7 +20,7 @@ @RestController public class ProjectEventsApiDelegateImpl implements ProjectEventsApiDelegate { - private final Logger log = LoggerFactory.getLogger(ProjectEventsApiDelegateImpl.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectEventsApiDelegateImpl.class); private static final String EVENT_ID_ATTRIBUTE_NAME = "id"; @@ -48,7 +48,7 @@ public ResponseEntity getProjectEvents( Optional pageNumber, Optional> sort ) { - log.debug("REST request to get all Events in Project '{}'", projectId); + logger.debug("REST request to get all Events in Project '{}'", projectId); projectService.findOneOrThrowEntityNotFoundAlertException(projectId); diff --git a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiDelegateImpl.java b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiDelegateImpl.java index 02222309e..fcf44d132 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiDelegateImpl.java +++ b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiDelegateImpl.java @@ -15,7 +15,7 @@ @RestController public class ProjectLocationApiDelegateImpl implements ProjectLocationApiDelegate { - private final Logger log = LoggerFactory.getLogger(ProjectLocationApiDelegateImpl.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectLocationApiDelegateImpl.class); private final LocationService locationService; private final ProjectService projectService; @@ -33,7 +33,7 @@ public ProjectLocationApiDelegateImpl( @Override public ResponseEntity getProjectLocations(Long projectId) { - log.debug("REST request to get all Locations in Project '{}'", projectId); + logger.debug("REST request to get all Locations in Project '{}'", projectId); projectService.findOneOrThrowEntityNotFoundAlertException(projectId); @@ -46,7 +46,7 @@ public ResponseEntity getProjectLocations(Long p @Override public ResponseEntity getProjectLocationsWithoutSelf(Long projectId, Long locationId) { - log.debug("REST request to get all Locations except '{}' in Project '{}'", locationId, projectId); + logger.debug("REST request to get all Locations except '{}' in Project '{}'", locationId, projectId); projectService.findOneOrThrowEntityNotFoundAlertException(projectId); diff --git a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiDelegateImpl.java b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiDelegateImpl.java index e463ea3bc..5fcaeaba7 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiDelegateImpl.java +++ b/src/main/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiDelegateImpl.java @@ -27,7 +27,7 @@ @RestController public class ProjectMemberApiDelegateImpl implements ProjectMemberApiDelegate { - private final Logger log = LoggerFactory.getLogger(ProjectMemberApiDelegateImpl.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectMemberApiDelegateImpl.class); private static final String MEMBER_ID_ATTRIBUTE_NAME = "id"; @@ -53,7 +53,7 @@ public ProjectMemberApiDelegateImpl( @Override public ResponseEntity findProjectMemberByTokenAndEmail(Long projectId, String invitationEmail) { - log.debug("REST request to get Member with email '{}' in Project '{}'", invitationEmail, projectId); + logger.debug("REST request to get Member with email '{}' in Project '{}'", invitationEmail, projectId); projectService.findOneOrThrowEntityNotFoundAlertException(projectId); @@ -69,7 +69,7 @@ public ResponseEntity getProjectMembers( Optional pageNumber, Optional> sort ) { - log.debug("REST request to get a page of Members in Project '{}'", projectId); + logger.debug("REST request to get a page of Members in Project '{}'", projectId); projectService.findOneOrThrowEntityNotFoundAlertException(projectId); @@ -90,7 +90,7 @@ public ResponseEntity inviteMemberToProject( Long projectId, List inviteMemberToProjectRequestInner ) { - log.debug("REST request to invite new Members '{}' to Project '{}'", inviteMemberToProjectRequestInner, projectId); + logger.debug("REST request to invite new Members '{}' to Project '{}'", inviteMemberToProjectRequestInner, projectId); ProjectDTO project = projectService.findOneOrThrowEntityNotFoundAlertException(projectId); diff --git a/src/main/java/io/github/bbortt/event/planner/web/api/mapper/TimeUtils.java b/src/main/java/io/github/bbortt/event/planner/web/api/mapper/TimeUtils.java index 9d8b85d7c..92b3c46c0 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/api/mapper/TimeUtils.java +++ b/src/main/java/io/github/bbortt/event/planner/web/api/mapper/TimeUtils.java @@ -1,10 +1,11 @@ package io.github.bbortt.event.planner.web.api.mapper; +import jakarta.annotation.Nullable; + import java.time.Instant; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.ZoneId; -import javax.annotation.Nullable; class TimeUtils { diff --git a/src/main/java/io/github/bbortt/event/planner/web/filter/OAuth2RefreshTokensWebFilter.java b/src/main/java/io/github/bbortt/event/planner/web/filter/OAuth2RefreshTokensWebFilter.java index 9ce5aa16c..09dc67673 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/filter/OAuth2RefreshTokensWebFilter.java +++ b/src/main/java/io/github/bbortt/event/planner/web/filter/OAuth2RefreshTokensWebFilter.java @@ -1,10 +1,9 @@ package io.github.bbortt.event.planner.web.filter; -import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest; @@ -22,6 +21,8 @@ import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; +import java.io.IOException; + /** * Refresh oauth2 tokens. */ diff --git a/src/main/java/io/github/bbortt/event/planner/web/filter/SpaWebFilter.java b/src/main/java/io/github/bbortt/event/planner/web/filter/SpaWebFilter.java new file mode 100644 index 000000000..6d5054977 --- /dev/null +++ b/src/main/java/io/github/bbortt/event/planner/web/filter/SpaWebFilter.java @@ -0,0 +1,36 @@ +package io.github.bbortt.event.planner.web.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +public class SpaWebFilter extends OncePerRequestFilter { + + /** + * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. + */ + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + String path = request.getRequestURI(); + if ( + !path.startsWith("/api") && + !path.startsWith("/management") && + !path.startsWith("/v3/api-docs") && + !path.startsWith("/login") && + !path.startsWith("/oauth2") && + !path.startsWith("/websocket") && + !path.contains(".") && + path.matches("/(.*)") + ) { + request.getRequestDispatcher("/index.html").forward(request, response); + return; + } + + filterChain.doFilter(request, response); + } +} diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/AccountResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/AccountResource.java index b72543177..1cbd6ab1a 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/AccountResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/AccountResource.java @@ -2,8 +2,7 @@ import io.github.bbortt.event.planner.service.UserService; import io.github.bbortt.event.planner.service.dto.AdminUserDTO; -import java.security.Principal; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AbstractAuthenticationToken; @@ -11,6 +10,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.security.Principal; + /** * REST controller for managing the current user's account. */ @@ -27,7 +28,7 @@ private AccountResourceException(String message) { } } - private final Logger log = LoggerFactory.getLogger(AccountResource.class); + private static final Logger logger = LoggerFactory.getLogger(AccountResource.class); private final UserService userService; @@ -60,7 +61,7 @@ public AdminUserDTO getAccount(Principal principal) { */ @GetMapping("/authenticate") public String isAuthenticated(HttpServletRequest request) { - log.debug("REST request to check if the current user is authenticated"); + logger.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } } diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/EntityAuditResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/EntityAuditResource.java index c1f3de2c8..51da3383a 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/EntityAuditResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/EntityAuditResource.java @@ -29,7 +29,7 @@ @Transactional public class EntityAuditResource { - private final Logger log = LoggerFactory.getLogger(EntityAuditResource.class); + private static final Logger logger = LoggerFactory.getLogger(EntityAuditResource.class); private final EntityAuditEventRepository entityAuditEventRepository; @@ -59,7 +59,7 @@ public ResponseEntity> getChanges( @RequestParam(value = "entityType") String entityType, @RequestParam(value = "limit") int limit ) { - log.debug("REST request to get a page of EntityAuditEvents"); + logger.debug("REST request to get a page of EntityAuditEvents"); Page page = entityAuditEventRepository.findAllByEntityType(entityType, PageRequest.of(0, limit)); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/EventResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/EventResource.java index d1b0c3320..a306e2f25 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/EventResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/EventResource.java @@ -4,26 +4,37 @@ import io.github.bbortt.event.planner.service.EventService; import io.github.bbortt.event.planner.service.dto.EventDTO; import io.github.bbortt.event.planner.web.rest.errors.BadRequestAlertException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + /** * REST controller for managing {@link io.github.bbortt.event.planner.domain.Event}. */ @@ -31,7 +42,7 @@ @RequestMapping("/api") public class EventResource { - private final Logger log = LoggerFactory.getLogger(EventResource.class); + private static final Logger logger = LoggerFactory.getLogger(EventResource.class); private static final String ENTITY_NAME = "event"; @@ -56,7 +67,7 @@ public EventResource(EventService eventService, EventRepository eventRepository) */ @PostMapping("/events") public ResponseEntity createEvent(@Valid @RequestBody EventDTO eventDTO) throws URISyntaxException { - log.debug("REST request to save Event : {}", eventDTO); + logger.debug("REST request to save Event : {}", eventDTO); if (eventDTO.getId() != null) { throw new BadRequestAlertException("A new event cannot already have an ID", ENTITY_NAME, "idexists"); } @@ -82,7 +93,7 @@ public ResponseEntity updateEvent( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody EventDTO eventDTO ) throws URISyntaxException { - log.debug("REST request to update Event : {}, {}", id, eventDTO); + logger.debug("REST request to update Event : {}, {}", id, eventDTO); if (eventDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -117,7 +128,7 @@ public ResponseEntity partialUpdateEvent( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody EventDTO eventDTO ) throws URISyntaxException { - log.debug("REST request to partial update Event partially : {}, {}", id, eventDTO); + logger.debug("REST request to partial update Event partially : {}, {}", id, eventDTO); if (eventDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -146,10 +157,10 @@ public ResponseEntity partialUpdateEvent( */ @GetMapping("/events") public ResponseEntity> getAllEvents( - @org.springdoc.api.annotations.ParameterObject Pageable pageable, + @ParameterObject Pageable pageable, @RequestParam(required = false, defaultValue = "false") boolean eagerload ) { - log.debug("REST request to get a page of Events"); + logger.debug("REST request to get a page of Events"); Page page; if (eagerload) { page = eventService.findAllWithEagerRelationships(pageable); @@ -168,7 +179,7 @@ public ResponseEntity> getAllEvents( */ @GetMapping("/events/{id}") public ResponseEntity getEvent(@PathVariable Long id) { - log.debug("REST request to get Event : {}", id); + logger.debug("REST request to get Event : {}", id); Optional eventDTO = eventService.findOne(id); return ResponseUtil.wrapOrNotFound(eventDTO); } @@ -181,7 +192,7 @@ public ResponseEntity getEvent(@PathVariable Long id) { */ @DeleteMapping("/events/{id}") public ResponseEntity deleteEvent(@PathVariable Long id) { - log.debug("REST request to delete Event : {}", id); + logger.debug("REST request to delete Event : {}", id); eventService.delete(id); return ResponseEntity .noContent() diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/LocationResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/LocationResource.java index c06beb853..4124c6783 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/LocationResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/LocationResource.java @@ -4,26 +4,37 @@ import io.github.bbortt.event.planner.service.LocationService; import io.github.bbortt.event.planner.service.dto.LocationDTO; import io.github.bbortt.event.planner.web.rest.errors.BadRequestAlertException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + /** * REST controller for managing {@link io.github.bbortt.event.planner.domain.Location}. */ @@ -31,7 +42,7 @@ @RequestMapping("/api") public class LocationResource { - private final Logger log = LoggerFactory.getLogger(LocationResource.class); + private static final Logger logger = LoggerFactory.getLogger(LocationResource.class); private static final String ENTITY_NAME = "location"; @@ -56,7 +67,7 @@ public LocationResource(LocationService locationService, LocationRepository loca */ @PostMapping("/locations") public ResponseEntity createLocation(@Valid @RequestBody LocationDTO locationDTO) throws URISyntaxException { - log.debug("REST request to save Location : {}", locationDTO); + logger.debug("REST request to save Location : {}", locationDTO); if (locationDTO.getId() != null) { throw new BadRequestAlertException("A new location cannot already have an ID", ENTITY_NAME, "idexists"); } @@ -82,7 +93,7 @@ public ResponseEntity updateLocation( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody LocationDTO locationDTO ) throws URISyntaxException { - log.debug("REST request to update Location : {}, {}", id, locationDTO); + logger.debug("REST request to update Location : {}, {}", id, locationDTO); if (locationDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -117,7 +128,7 @@ public ResponseEntity partialUpdateLocation( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody LocationDTO locationDTO ) throws URISyntaxException { - log.debug("REST request to partial update Location partially : {}, {}", id, locationDTO); + logger.debug("REST request to partial update Location partially : {}, {}", id, locationDTO); if (locationDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -146,10 +157,10 @@ public ResponseEntity partialUpdateLocation( */ @GetMapping("/locations") public ResponseEntity> getAllLocations( - @org.springdoc.api.annotations.ParameterObject Pageable pageable, + @ParameterObject Pageable pageable, @RequestParam(required = false, defaultValue = "false") boolean eagerload ) { - log.debug("REST request to get a page of Locations"); + logger.debug("REST request to get a page of Locations"); Page page; if (eagerload) { page = locationService.findAllWithEagerRelationships(pageable); @@ -168,7 +179,7 @@ public ResponseEntity> getAllLocations( */ @GetMapping("/locations/{id}") public ResponseEntity getLocation(@PathVariable Long id) { - log.debug("REST request to get Location : {}", id); + logger.debug("REST request to get Location : {}", id); Optional locationDTO = locationService.findOne(id); return ResponseUtil.wrapOrNotFound(locationDTO); } @@ -181,7 +192,7 @@ public ResponseEntity getLocation(@PathVariable Long id) { */ @DeleteMapping("/locations/{id}") public ResponseEntity deleteLocation(@PathVariable Long id) { - log.debug("REST request to delete Location : {}", id); + logger.debug("REST request to delete Location : {}", id); locationService.delete(id); return ResponseEntity .noContent() diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/LogoutResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/LogoutResource.java index 539b58bf0..3f3065f5c 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/LogoutResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/LogoutResource.java @@ -1,7 +1,6 @@ package io.github.bbortt.event.planner.web.rest; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; @@ -11,6 +10,8 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.Map; + /** * REST controller for managing global OIDC logout. */ diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/MemberResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/MemberResource.java index 91b02f951..9b27b95a2 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/MemberResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/MemberResource.java @@ -4,26 +4,37 @@ import io.github.bbortt.event.planner.service.MemberService; import io.github.bbortt.event.planner.service.dto.MemberDTO; import io.github.bbortt.event.planner.web.rest.errors.BadRequestAlertException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + /** * REST controller for managing {@link io.github.bbortt.event.planner.domain.Member}. */ @@ -31,7 +42,7 @@ @RequestMapping("/api") public class MemberResource { - private final Logger log = LoggerFactory.getLogger(MemberResource.class); + private static final Logger logger = LoggerFactory.getLogger(MemberResource.class); private static final String ENTITY_NAME = "member"; @@ -56,7 +67,7 @@ public MemberResource(MemberService memberService, MemberRepository memberReposi */ @PostMapping("/members") public ResponseEntity createMember(@Valid @RequestBody MemberDTO memberDTO) throws URISyntaxException { - log.debug("REST request to save Member : {}", memberDTO); + logger.debug("REST request to save Member : {}", memberDTO); if (memberDTO.getId() != null) { throw new BadRequestAlertException("A new member cannot already have an ID", ENTITY_NAME, "idexists"); } @@ -82,7 +93,7 @@ public ResponseEntity updateMember( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody MemberDTO memberDTO ) throws URISyntaxException { - log.debug("REST request to update Member : {}, {}", id, memberDTO); + logger.debug("REST request to update Member : {}, {}", id, memberDTO); if (memberDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -117,7 +128,7 @@ public ResponseEntity partialUpdateMember( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody MemberDTO memberDTO ) throws URISyntaxException { - log.debug("REST request to partial update Member partially : {}, {}", id, memberDTO); + logger.debug("REST request to partial update Member partially : {}, {}", id, memberDTO); if (memberDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -146,10 +157,10 @@ public ResponseEntity partialUpdateMember( */ @GetMapping("/members") public ResponseEntity> getAllMembers( - @org.springdoc.api.annotations.ParameterObject Pageable pageable, + @ParameterObject Pageable pageable, @RequestParam(required = false, defaultValue = "false") boolean eagerload ) { - log.debug("REST request to get a page of Members"); + logger.debug("REST request to get a page of Members"); Page page; if (eagerload) { page = memberService.findAllWithEagerRelationships(pageable); @@ -168,7 +179,7 @@ public ResponseEntity> getAllMembers( */ @GetMapping("/members/{id}") public ResponseEntity getMember(@PathVariable Long id) { - log.debug("REST request to get Member : {}", id); + logger.debug("REST request to get Member : {}", id); Optional memberDTO = memberService.findOne(id); return ResponseUtil.wrapOrNotFound(memberDTO); } @@ -181,7 +192,7 @@ public ResponseEntity getMember(@PathVariable Long id) { */ @DeleteMapping("/members/{id}") public ResponseEntity deleteMember(@PathVariable Long id) { - log.debug("REST request to delete Member : {}", id); + logger.debug("REST request to delete Member : {}", id); memberService.delete(id); return ResponseEntity .noContent() diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/ProjectResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/ProjectResource.java index f72a4a097..66a5c71d4 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/ProjectResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/ProjectResource.java @@ -4,15 +4,11 @@ import io.github.bbortt.event.planner.service.ProjectService; import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.web.rest.errors.BadRequestAlertException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -32,6 +28,12 @@ import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + /** * REST controller for managing {@link io.github.bbortt.event.planner.domain.Project}. */ @@ -39,7 +41,7 @@ @RequestMapping("/api") public class ProjectResource { - private final Logger log = LoggerFactory.getLogger(ProjectResource.class); + private static final Logger logger = LoggerFactory.getLogger(ProjectResource.class); private static final String ENTITY_NAME = "project"; @@ -64,7 +66,7 @@ public ProjectResource(ProjectService projectService, ProjectRepository projectR */ @PostMapping("/projects") public ResponseEntity createProject(@Valid @RequestBody ProjectDTO projectDTO) throws URISyntaxException { - log.debug("REST request to save Project : {}", projectDTO); + logger.debug("REST request to save Project : {}", projectDTO); if (projectDTO.getId() != null) { throw new BadRequestAlertException("A new project cannot already have an ID", ENTITY_NAME, "idexists"); } @@ -89,7 +91,7 @@ public ResponseEntity updateProject( @PathVariable(value = "id", required = false) final Long id, @Valid @RequestBody ProjectDTO projectDTO ) { - log.debug("REST request to update Project : {}, {}", id, projectDTO); + logger.debug("REST request to update Project : {}, {}", id, projectDTO); if (projectDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -123,7 +125,7 @@ public ResponseEntity partialUpdateProject( @PathVariable(value = "id", required = false) final Long id, @NotNull @RequestBody ProjectDTO projectDTO ) { - log.debug("REST request to partial update Project partially : {}, {}", id, projectDTO); + logger.debug("REST request to partial update Project partially : {}, {}", id, projectDTO); if (projectDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } @@ -150,8 +152,8 @@ public ResponseEntity partialUpdateProject( * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of projects in body. */ @GetMapping("/projects") - public ResponseEntity> getAllProjects(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { - log.debug("REST request to get a page of Projects"); + public ResponseEntity> getAllProjects(@ParameterObject Pageable pageable) { + logger.debug("REST request to get a page of Projects"); Page page = projectService.findAll(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return ResponseEntity.ok().headers(headers).body(page.getContent()); @@ -165,7 +167,7 @@ public ResponseEntity> getAllProjects(@org.springdoc.api.annota */ @GetMapping("/projects/{id}") public ResponseEntity getProject(@PathVariable Long id) { - log.debug("REST request to get Project : {}", id); + logger.debug("REST request to get Project : {}", id); Optional projectDTO = projectService.findOne(id); return ResponseUtil.wrapOrNotFound(projectDTO); } @@ -178,7 +180,7 @@ public ResponseEntity getProject(@PathVariable Long id) { */ @DeleteMapping("/projects/{id}") public ResponseEntity deleteProject(@PathVariable Long id) { - log.debug("REST request to delete Project : {}", id); + logger.debug("REST request to delete Project : {}", id); projectService.delete(id); return ResponseEntity .noContent() diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/PublicUserResource.java b/src/main/java/io/github/bbortt/event/planner/web/rest/PublicUserResource.java index 118c0abb7..db21e4016 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/PublicUserResource.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/PublicUserResource.java @@ -2,23 +2,27 @@ import io.github.bbortt.event.planner.service.UserService; import io.github.bbortt.event.planner.service.dto.UserDTO; -import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springdoc.core.annotations.ParameterObject; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.PaginationUtil; +import java.util.List; + @RestController @RequestMapping("/api") public class PublicUserResource { - private final Logger log = LoggerFactory.getLogger(PublicUserResource.class); + private static final Logger logger = LoggerFactory.getLogger(PublicUserResource.class); private final UserService userService; @@ -33,8 +37,8 @@ public PublicUserResource(UserService userService) { * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. */ @GetMapping("/users") - public ResponseEntity> getAllPublicUsers(@org.springdoc.api.annotations.ParameterObject Pageable pageable) { - log.debug("REST request to get all public User names"); + public ResponseEntity> getAllPublicUsers(@ParameterObject Pageable pageable) { + logger.debug("REST request to get all public User names"); final Page page = userService.getAllPublicUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/BadRequestAlertException.java b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/BadRequestAlertException.java index ecfac1f55..674b1f508 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/BadRequestAlertException.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/BadRequestAlertException.java @@ -1,13 +1,14 @@ package io.github.bbortt.event.planner.web.rest.errors; +import org.springframework.http.HttpStatus; +import org.springframework.web.ErrorResponseException; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; + import java.net.URI; -import java.util.HashMap; -import java.util.Map; -import org.zalando.problem.AbstractThrowableProblem; -import org.zalando.problem.Status; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep -public class BadRequestAlertException extends AbstractThrowableProblem { +public class BadRequestAlertException extends ErrorResponseException { private static final long serialVersionUID = 1L; @@ -20,7 +21,18 @@ public BadRequestAlertException(String defaultMessage, String entityName, String } public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { - super(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey)); + super( + HttpStatus.BAD_REQUEST, + ProblemDetailWithCauseBuilder + .instance() + .withStatus(HttpStatus.BAD_REQUEST.value()) + .withType(type) + .withTitle(defaultMessage) + .withProperty("message", "error." + errorKey) + .withProperty("params", entityName) + .build(), + null + ); this.entityName = entityName; this.errorKey = errorKey; } @@ -33,10 +45,7 @@ public String getErrorKey() { return errorKey; } - private static Map getAlertParameters(String entityName, String errorKey) { - Map parameters = new HashMap<>(); - parameters.put("message", "error." + errorKey); - parameters.put("params", entityName); - return parameters; + public ProblemDetailWithCause getProblemDetailWithCause() { + return (ProblemDetailWithCause) this.getBody(); } } diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/EntityNotFoundAlertException.java b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/EntityNotFoundAlertException.java index 7e960a406..0f47e5f89 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/EntityNotFoundAlertException.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/EntityNotFoundAlertException.java @@ -1,13 +1,15 @@ package io.github.bbortt.event.planner.web.rest.errors; +import org.springframework.http.HttpStatus; +import org.springframework.web.ErrorResponseException; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause; + import java.net.URI; import java.util.HashMap; import java.util.Map; -import org.zalando.problem.AbstractThrowableProblem; -import org.zalando.problem.Status; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep -public class EntityNotFoundAlertException extends AbstractThrowableProblem { +public class EntityNotFoundAlertException extends ErrorResponseException { private static final long serialVersionUID = 1L; @@ -20,7 +22,18 @@ public EntityNotFoundAlertException(String defaultMessage, String entityName, St } public EntityNotFoundAlertException(URI type, String defaultMessage, String entityName, String errorKey) { - super(type, defaultMessage, Status.NOT_FOUND, null, null, null, getAlertParameters(entityName, errorKey)); + super( + HttpStatus.NOT_FOUND, + ProblemDetailWithCause.ProblemDetailWithCauseBuilder + .instance() + .withStatus(HttpStatus.NOT_FOUND.value()) + .withType(type) + .withTitle(defaultMessage) + .withProperty("message", "error." + errorKey) + .withProperty("params", entityName) + .build(), + null + ); this.entityName = entityName; this.errorKey = errorKey; } diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslator.java b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslator.java index 74bb83e9e..374f2c64c 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslator.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslator.java @@ -1,47 +1,53 @@ package io.github.bbortt.event.planner.web.rest.errors; -import java.net.URI; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.dao.DataAccessException; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConversionException; -import org.springframework.validation.BindingResult; +import org.springframework.lang.Nullable; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.web.ErrorResponse; +import org.springframework.web.ErrorResponseException; 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.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; -import org.zalando.problem.DefaultProblem; -import org.zalando.problem.Problem; -import org.zalando.problem.ProblemBuilder; -import org.zalando.problem.Status; -import org.zalando.problem.StatusType; -import org.zalando.problem.spring.web.advice.ProblemHandling; -import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; -import org.zalando.problem.violations.ConstraintViolationProblem; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import tech.jhipster.config.JHipsterConstants; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause; +import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; import tech.jhipster.web.util.HeaderUtil; +import java.net.URI; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; + /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807). */ @ControllerAdvice -public class ExceptionTranslator implements ProblemHandling, SecurityAdviceTrait { +public class ExceptionTranslator extends ResponseEntityExceptionHandler { private static final String FIELD_ERRORS_KEY = "fieldErrors"; private static final String MESSAGE_KEY = "message"; private static final String PATH_KEY = "path"; - private static final String VIOLATIONS_KEY = "violations"; + private static final boolean CASUAL_CHAIN_ENABLED = false; @Value("${jhipster.clientApp.name}") private String applicationName; @@ -52,46 +58,84 @@ public ExceptionTranslator(Environment env) { this.env = env; } - /** - * Post-process the Problem payload to add the message key for the front-end if needed. - */ + @ExceptionHandler + public ResponseEntity handleAnyException(Throwable ex, NativeWebRequest request) { + ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request); + return handleExceptionInternal( + (Exception) ex, + pdCause, + buildHeaders(ex, request), + HttpStatusCode.valueOf(pdCause.getStatus()), + request + ); + } + + @Nullable @Override - public ResponseEntity process(@Nullable ResponseEntity entity, NativeWebRequest request) { - if (entity == null) { - return null; - } - Problem problem = entity.getBody(); - if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { - return entity; + protected ResponseEntity handleExceptionInternal( + Exception ex, + @Nullable Object body, + HttpHeaders headers, + HttpStatusCode statusCode, + WebRequest request + ) { + body = body == null ? wrapAndCustomizeProblem((Throwable) ex, (NativeWebRequest) request) : body; + return super.handleExceptionInternal(ex, body, headers, statusCode, request); + } + + protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, NativeWebRequest request) { + return customizeProblem(getProblemDetailWithCause(ex), ex, request); + } + + private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) { + if ( + ex instanceof ErrorResponseException exp && exp.getBody() instanceof ProblemDetailWithCause + ) return (ProblemDetailWithCause) exp.getBody(); + return ProblemDetailWithCauseBuilder.instance().withStatus(toStatus(ex).value()).build(); + } + + protected ProblemDetailWithCause customizeProblem(ProblemDetailWithCause problem, Throwable err, NativeWebRequest request) { + if (problem.getStatus() <= 0) problem.setStatus(toStatus(err)); + + if (problem.getType() == null || problem.getType().equals(URI.create("about:blank"))) problem.setType(getMappedType(err)); + + // higher precedence to Custom/ResponseStatus types + String title = extractTitle(err, problem.getStatus()); + String problemTitle = problem.getTitle(); + if (problemTitle == null || !problemTitle.equals(title)) { + problem.setTitle(title); } - HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class); - String requestUri = nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY; - ProblemBuilder builder = Problem - .builder() - .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) - .withStatus(problem.getStatus()) - .withTitle(problem.getTitle()) - .with(PATH_KEY, requestUri); - - if (problem instanceof ConstraintViolationProblem) { - builder - .with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()) - .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION); - } else { - builder.withCause(((DefaultProblem) problem).getCause()).withDetail(problem.getDetail()).withInstance(problem.getInstance()); - problem.getParameters().forEach(builder::with); - if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) { - builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode()); - } + if (problem.getDetail() == null) { + // higher precedence to cause + problem.setDetail(getCustomizedErrorDetails(err)); } - return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode()); + + Map problemProperties = problem.getProperties(); + if (problemProperties == null || !problemProperties.containsKey(MESSAGE_KEY)) problem.setProperty( + MESSAGE_KEY, + getMappedMessageKey(err) != null ? getMappedMessageKey(err) : "error.http." + problem.getStatus() + ); + + if (problemProperties == null || !problemProperties.containsKey(PATH_KEY)) problem.setProperty(PATH_KEY, getPathValue(request)); + + if ( + (err instanceof MethodArgumentNotValidException) && + (problemProperties == null || !problemProperties.containsKey(FIELD_ERRORS_KEY)) + ) problem.setProperty(FIELD_ERRORS_KEY, getFieldErrors((MethodArgumentNotValidException) err)); + + problem.setCause(buildCause(err.getCause(), request).orElse(null)); + + return problem; } - @Override - public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { - BindingResult result = ex.getBindingResult(); - List fieldErrors = result + private String extractTitle(Throwable err, int statusCode) { + return getCustomizedTitle(err) != null ? getCustomizedTitle(err) : extractTitleForResponseStatus(err, statusCode); + } + + private List getFieldErrors(MethodArgumentNotValidException ex) { + return ex + .getBindingResult() .getFieldErrors() .stream() .map(f -> @@ -102,86 +146,104 @@ public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotVal ) ) .toList(); + } - Problem problem = Problem - .builder() - .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) - .withTitle("Method argument not valid") - .withStatus(defaultConstraintViolationStatus()) - .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION) - .with(FIELD_ERRORS_KEY, fieldErrors) - .build(); - return create(ex, problem, request); + private String extractTitleForResponseStatus(Throwable err, int statusCode) { + ResponseStatus specialStatus = extractResponseStatus(err); + return specialStatus == null ? HttpStatus.valueOf(statusCode).getReasonPhrase() : specialStatus.reason(); } - @ExceptionHandler - public ResponseEntity handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { - return create( - ex, - request, - HeaderUtil.createFailureAlert(applicationName, true, ex.getEntityName(), ex.getErrorKey(), ex.getMessage()) - ); + private String extractURI(NativeWebRequest request) { + HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class); + return nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY; } - @ExceptionHandler - public ResponseEntity handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { - Problem problem = Problem.builder().withStatus(Status.CONFLICT).with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE).build(); - return create(ex, problem, request); + private HttpStatus toStatus(final Throwable throwable) { + // Let the ErrorResponse take this responsibility + if (throwable instanceof ErrorResponse err) return HttpStatus.valueOf(err.getBody().getStatus()); + + return Optional + .ofNullable(getMappedStatus(throwable)) + .orElse( + Optional.ofNullable(resolveResponseStatus(throwable)).map(ResponseStatus::value).orElse(HttpStatus.INTERNAL_SERVER_ERROR) + ); } - @Override - public ProblemBuilder prepare(final Throwable throwable, final StatusType status, final URI type) { - Collection activeProfiles = Arrays.asList(env.getActiveProfiles()); + private ResponseStatus extractResponseStatus(final Throwable throwable) { + return Optional.ofNullable(resolveResponseStatus(throwable)).orElse(null); + } + + private ResponseStatus resolveResponseStatus(final Throwable type) { + final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class); + return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate; + } + + private URI getMappedType(Throwable err) { + if (err instanceof MethodArgumentNotValidException exp) return ErrorConstants.CONSTRAINT_VIOLATION_TYPE; + return ErrorConstants.DEFAULT_TYPE; + } + private String getMappedMessageKey(Throwable err) { + if (err instanceof MethodArgumentNotValidException) return ErrorConstants.ERR_VALIDATION; else if ( + err instanceof ConcurrencyFailureException || err.getCause() != null && err.getCause() instanceof ConcurrencyFailureException + ) return ErrorConstants.ERR_CONCURRENCY_FAILURE; + return null; + } + + private String getCustomizedTitle(Throwable err) { + if (err instanceof MethodArgumentNotValidException exp) return "Method argument not valid"; + return null; + } + + private String getCustomizedErrorDetails(Throwable err) { + Collection activeProfiles = Arrays.asList(env.getActiveProfiles()); if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { - if (throwable instanceof HttpMessageConversionException) { - return Problem - .builder() - .withType(type) - .withTitle(status.getReasonPhrase()) - .withStatus(status) - .withDetail("Unable to convert http message") - .withCause( - Optional.ofNullable(throwable.getCause()).filter(cause -> isCausalChainsEnabled()).map(this::toProblem).orElse(null) - ); - } - if (throwable instanceof DataAccessException) { - return Problem - .builder() - .withType(type) - .withTitle(status.getReasonPhrase()) - .withStatus(status) - .withDetail("Failure during data access") - .withCause( - Optional.ofNullable(throwable.getCause()).filter(cause -> isCausalChainsEnabled()).map(this::toProblem).orElse(null) - ); - } - if (containsPackageName(throwable.getMessage())) { - return Problem - .builder() - .withType(type) - .withTitle(status.getReasonPhrase()) - .withStatus(status) - .withDetail("Unexpected runtime exception") - .withCause( - Optional.ofNullable(throwable.getCause()).filter(cause -> isCausalChainsEnabled()).map(this::toProblem).orElse(null) - ); - } + if (err instanceof HttpMessageConversionException) return "Unable to convert http message"; + if (err instanceof DataAccessException) return "Failure during data access"; + if (containsPackageName(err.getMessage())) return "Unexpected runtime exception"; } + return err.getCause() != null ? err.getCause().getMessage() : err.getMessage(); + } - return Problem - .builder() - .withType(type) - .withTitle(status.getReasonPhrase()) - .withStatus(status) - .withDetail(throwable.getMessage()) - .withCause( - Optional.ofNullable(throwable.getCause()).filter(cause -> isCausalChainsEnabled()).map(this::toProblem).orElse(null) - ); + private HttpStatus getMappedStatus(Throwable err) { + // Where we disagree with Spring defaults + if (err instanceof AccessDeniedException) return HttpStatus.FORBIDDEN; + if (err instanceof ConcurrencyFailureException) return HttpStatus.CONFLICT; + if (err instanceof BadCredentialsException) return HttpStatus.UNAUTHORIZED; + return null; + } + + private URI getPathValue(NativeWebRequest request) { + if (request == null) return URI.create("about:blank"); + return URI.create(extractURI(request)); + } + + private HttpHeaders buildHeaders(Throwable err, NativeWebRequest request) { + return err instanceof BadRequestAlertException + ? HeaderUtil.createFailureAlert( + applicationName, + true, + ((BadRequestAlertException) err).getEntityName(), + ((BadRequestAlertException) err).getErrorKey(), + ((BadRequestAlertException) err).getMessage() + ) + : null; + } + + public Optional buildCause(final Throwable throwable, NativeWebRequest request) { + if (throwable != null && isCasualChainEnabled()) { + return Optional.of(customizeProblem(getProblemDetailWithCause(throwable), throwable, request)); + } + return Optional.ofNullable(null); + } + + private boolean isCasualChainEnabled() { + // Customize as per the needs + return CASUAL_CHAIN_ENABLED; } private boolean containsPackageName(String message) { // This list is for sure not complete - return StringUtils.containsAny(message, "org.", "java.", "net.", "javax.", "com.", "io.", "de.", "io.github.bbortt.event.planner"); + return StringUtils.containsAny(message, "org.", "java.", "net.", "jakarta.", "javax.", "com.", "io.", "de.", "io.github.bbortt.event.planner"); } } diff --git a/src/main/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtil.java b/src/main/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtil.java index 219494684..3b4d9e4ba 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtil.java +++ b/src/main/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtil.java @@ -53,10 +53,10 @@ public Pageable createPagingInformation( PageRequest pageRequest = PageRequest.ofSize(pageSizeOrDefault(pageSize)); if (pageNumber.isPresent()) { - if (pageNumber.get() < 1) { + if (pageNumber.orElseThrow(IllegalArgumentException::new) < 1) { throw new IllegalArgumentException("Page number is 1-based!"); } else { - pageRequest = pageRequest.withPage(pageNumber.get() - 1); + pageRequest = pageRequest.withPage(pageNumber.orElseThrow(IllegalArgumentException::new) - 1); } } diff --git a/src/main/java/io/github/bbortt/event/planner/web/websocket/ActivityService.java b/src/main/java/io/github/bbortt/event/planner/web/websocket/ActivityService.java index 2ef462fb1..88d0d64df 100644 --- a/src/main/java/io/github/bbortt/event/planner/web/websocket/ActivityService.java +++ b/src/main/java/io/github/bbortt/event/planner/web/websocket/ActivityService.java @@ -1,23 +1,26 @@ package io.github.bbortt.event.planner.web.websocket; -import static io.github.bbortt.event.planner.config.WebsocketConfiguration.IP_ADDRESS; - import io.github.bbortt.event.planner.web.websocket.dto.ActivityDTO; -import java.security.Principal; -import java.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; -import org.springframework.messaging.handler.annotation.*; +import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.Payload; +import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessageSendingOperations; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; import org.springframework.stereotype.Controller; import org.springframework.web.socket.messaging.SessionDisconnectEvent; +import java.security.Principal; +import java.time.Instant; + +import static io.github.bbortt.event.planner.config.WebsocketConfiguration.IP_ADDRESS; + @Controller public class ActivityService implements ApplicationListener { - private static final Logger log = LoggerFactory.getLogger(ActivityService.class); + private static final Logger logger = LoggerFactory.getLogger(ActivityService.class); private final SimpMessageSendingOperations messagingTemplate; @@ -32,7 +35,7 @@ public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAcc activityDTO.setSessionId(stompHeaderAccessor.getSessionId()); activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString()); activityDTO.setTime(Instant.now()); - log.debug("Sending user tracking data {}", activityDTO); + logger.debug("Sending user tracking data {}", activityDTO); return activityDTO; } diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index a66a29fc4..1c9943e1f 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -40,8 +40,6 @@ spring: hikari: poolName: Hikari auto-commit: false - jpa: - database-platform: tech.jhipster.domain.util.FixedPostgreSQL10Dialect liquibase: # Remove "faker" if you do not want the sample data to be loaded automatically contexts: dev, faker @@ -77,7 +75,7 @@ jhipster: enabled: false host: localhost port: 5000 - queue-size: 512 + ring-buffer-size: 512 mail: base-url: http://localhost:9000 enabled: false diff --git a/src/main/resources/config/application-prod.yml b/src/main/resources/config/application-prod.yml index cd1bb4bdb..451d889aa 100644 --- a/src/main/resources/config/application-prod.yml +++ b/src/main/resources/config/application-prod.yml @@ -20,9 +20,9 @@ logging: io.github.bbortt.event.planner: INFO management: - metrics: - export: - prometheus: + prometheus: + metrics: + export: enabled: false spring: @@ -41,8 +41,6 @@ spring: hikari: poolName: Hikari auto-commit: false - jpa: - database-platform: tech.jhipster.domain.util.FixedPostgreSQL10Dialect # Replace by "prod, faker" to add the faker context and have sample data loaded in production liquibase: contexts: prod @@ -99,7 +97,7 @@ jhipster: enabled: false host: localhost port: 5000 - queue-size: 512 + ring-buffer-size: 512 # =================================================================== # Application specific properties # Add your own application properties here, see the ApplicationProperties class diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index e86bf83eb..955cd38df 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -30,20 +30,18 @@ management: base-path: /management exposure: include: - [ - 'configprops', - 'env', - 'health', - 'info', - 'jhimetrics', - 'jhiopenapigroups', - 'logfile', - 'loggers', - 'prometheus', - 'threaddump', - 'caches', - 'liquibase', - ] + - configprops + - env + - health + - info + - jhimetrics + - jhiopenapigroups + - logfile + - loggers + - prometheus + - threaddump + - caches + - liquibase endpoint: health: show-details: when_authorized @@ -65,10 +63,9 @@ management: health: mail: enabled: false # When using the MailService, configure an SMTP server and set this to true - metrics: - export: - # Prometheus is the default metrics backend - prometheus: + prometheus: + metrics: + export: enabled: true step: 60 enable: @@ -114,9 +111,10 @@ spring: open-in-view: false properties: hibernate.jdbc.time_zone: UTC + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP hibernate.id.new_generator_mappings: true hibernate.connection.provider_disables_autocommit: true - hibernate.cache.use_second_level_cache: false + hibernate.cache.use_second_level_cache: true hibernate.cache.use_query_cache: false hibernate.generate_statistics: false # modify batch size as necessary @@ -128,8 +126,8 @@ spring: hibernate: ddl-auto: none naming: - physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy + physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy messages: basename: i18n/messages main: diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 92a33639b..9139a204d 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -32,11 +32,12 @@ --> - - - - - + + + + + + @@ -54,22 +55,25 @@ + - - + + - - + + + + true diff --git a/src/main/resources/swagger/api.yml b/src/main/resources/swagger/api.yml index 8d196be34..a0372d6f9 100644 --- a/src/main/resources/swagger/api.yml +++ b/src/main/resources/swagger/api.yml @@ -366,12 +366,49 @@ components: type: string responses: Problem: - description: | - An error occurred - see status code and problem object for more information. + description: error occurred - see status code and problem object for more information. content: - 'application/problem+json': + application/problem+json: schema: - $ref: 'https://opensource.zalando.com/problem/schema.yaml#/Problem' + type: object + properties: + type: + type: string + format: uri + description: | + An absolute URI that identifies the problem type. When dereferenced, + it SHOULD provide human-readable documentation for the problem type + (e.g., using HTML). + default: 'about:blank' + example: 'https://www.jhipster.tech/problem/constraint-violation' + title: + type: string + description: | + A short, summary of the problem type. Written in english and readable + for engineers (usually not suited for non technical stakeholders and + not localized); example: Service Unavailable + status: + type: integer + format: int32 + description: | + The HTTP status code generated by the origin server for this occurrence + of the problem. + minimum: 100 + maximum: 600 + exclusiveMaximum: true + example: 503 + detail: + type: string + description: | + A human readable explanation specific to this occurrence of the + problem. + example: Connection to database timed out + instance: + type: string + format: uri + description: | + An absolute URI that identifies the specific occurrence of the problem. + It may or may not yield further information if dereferenced. headers: hasNextPage: schema: diff --git a/src/main/resources/templates/error.html b/src/main/resources/templates/error.html index 690e85607..b557650ac 100644 --- a/src/main/resources/templates/error.html +++ b/src/main/resources/templates/error.html @@ -43,7 +43,9 @@ border: 1px solid #b3b3b3; border-radius: 4px; margin: 0 auto; - box-shadow: 0 1px 10px #a7a7a7, inset 0 1px 0 #fff; + box-shadow: + 0 1px 10px #a7a7a7, + inset 0 1px 0 #fff; background: #fcfcfc; } diff --git a/src/test/java/io/github/bbortt/event/planner/TechnicalStructureTest.java b/src/test/java/io/github/bbortt/event/planner/TechnicalStructureTest.java index 03e1a7c7e..73d96dc5b 100644 --- a/src/test/java/io/github/bbortt/event/planner/TechnicalStructureTest.java +++ b/src/test/java/io/github/bbortt/event/planner/TechnicalStructureTest.java @@ -1,11 +1,5 @@ package io.github.bbortt.event.planner; -import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue; -import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf; -import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage; -import static com.tngtech.archunit.core.domain.JavaClass.Predicates.type; -import static com.tngtech.archunit.library.Architectures.layeredArchitecture; - import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; @@ -16,12 +10,19 @@ import io.github.bbortt.event.planner.security.SecurityUtils; import io.github.bbortt.event.planner.web.rest.errors.EntityNotFoundAlertException; +import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage; +import static com.tngtech.archunit.core.domain.JavaClass.Predicates.type; +import static com.tngtech.archunit.library.Architectures.layeredArchitecture; + @AnalyzeClasses(packagesOf = EventPlannerApp.class, importOptions = DoNotIncludeTests.class) class TechnicalStructureTest { // prettier-ignore @ArchTest static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture() + .consideringAllDependencies() .layer("Config").definedBy("..config..") .layer("Web").definedBy("..web..") .optionalLayer("Service").definedBy("..service..") diff --git a/src/test/java/io/github/bbortt/event/planner/config/PostgreSqlTestContainer.java b/src/test/java/io/github/bbortt/event/planner/config/PostgreSqlTestContainer.java index ac28a6d3e..0824ee290 100644 --- a/src/test/java/io/github/bbortt/event/planner/config/PostgreSqlTestContainer.java +++ b/src/test/java/io/github/bbortt/event/planner/config/PostgreSqlTestContainer.java @@ -9,7 +9,7 @@ public class PostgreSqlTestContainer implements SqlTestContainer { - private static final Logger log = LoggerFactory.getLogger(PostgreSqlTestContainer.class); + private static final Logger logger = LoggerFactory.getLogger(PostgreSqlTestContainer.class); private PostgreSQLContainer postgreSQLContainer; @@ -23,11 +23,11 @@ public void destroy() { @Override public void afterPropertiesSet() { if (null == postgreSQLContainer) { - try (PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer<>("postgres:15.2-alpine")) { + try (PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer<>("postgres:15.3-alpine")) { postgreSQLContainer .withDatabaseName("eventplanner") .withTmpFs(Collections.singletonMap("/testtmpfs", "rw")) - .withLogConsumer(new Slf4jLogConsumer(log)) + .withLogConsumer(new Slf4jLogConsumer(logger)) .withReuse(true); this.postgreSQLContainer = postgreSQLContainer; } diff --git a/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainer.java b/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainer.java index dbfc9ae7b..3f7d1b7df 100644 --- a/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainer.java +++ b/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainer.java @@ -6,12 +6,12 @@ import org.springframework.beans.factory.InitializingBean; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; -import org.testcontainers.utility.DockerImageName; public class RedisTestContainer implements InitializingBean, DisposableBean { + private static final Logger logger = LoggerFactory.getLogger(RedisTestContainer.class); + private GenericContainer redisContainer; - private static final Logger log = LoggerFactory.getLogger(RedisTestContainer.class); @Override public void destroy() { @@ -24,9 +24,9 @@ public void destroy() { public void afterPropertiesSet() { if (null == redisContainer) { redisContainer = - new GenericContainer("redis:7.0.10-alpine") + new GenericContainer("redis:7.0.12-alpine") .withExposedPorts(6379) - .withLogConsumer(new Slf4jLogConsumer(log)) + .withLogConsumer(new Slf4jLogConsumer(logger)) .withReuse(true); } if (!redisContainer.isRunning()) { diff --git a/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainersSpringContextCustomizerFactory.java b/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainersSpringContextCustomizerFactory.java new file mode 100644 index 000000000..386cc5777 --- /dev/null +++ b/src/test/java/io/github/bbortt/event/planner/config/RedisTestContainersSpringContextCustomizerFactory.java @@ -0,0 +1,45 @@ +package io.github.bbortt.event.planner.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.test.context.ContextConfigurationAttributes; +import org.springframework.test.context.ContextCustomizer; +import org.springframework.test.context.ContextCustomizerFactory; + +import java.util.List; + +public class RedisTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory { + + private static final Logger logger = LoggerFactory.getLogger(RedisTestContainersSpringContextCustomizerFactory.class); + + private static RedisTestContainer redisBean; + + @Override + public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { + return (context, mergedConfig) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + TestPropertyValues testValues = TestPropertyValues.empty(); + EmbeddedRedis redisAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedRedis.class); + if (null != redisAnnotation) { + logger.debug("detected the EmbeddedRedis annotation on class {}", testClass.getName()); + logger.info("Warming up the redis database"); + if (null == redisBean) { + redisBean = beanFactory.createBean(RedisTestContainer.class); + beanFactory.registerSingleton(RedisTestContainer.class.getName(), redisBean); + // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(RedisTestContainer.class.getName(), redisBean); + } + testValues = + testValues.and( + "jhipster.cache.redis.server=redis://" + + redisBean.getRedisContainer().getContainerIpAddress() + + ":" + + redisBean.getRedisContainer().getMappedPort(6379) + ); + } + testValues.applyTo(context); + }; + } +} diff --git a/src/test/java/io/github/bbortt/event/planner/config/SqlTestContainersSpringContextCustomizerFactory.java b/src/test/java/io/github/bbortt/event/planner/config/SqlTestContainersSpringContextCustomizerFactory.java new file mode 100644 index 000000000..93f040f2c --- /dev/null +++ b/src/test/java/io/github/bbortt/event/planner/config/SqlTestContainersSpringContextCustomizerFactory.java @@ -0,0 +1,48 @@ +package io.github.bbortt.event.planner.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.core.annotation.AnnotatedElementUtils; +import org.springframework.test.context.ContextConfigurationAttributes; +import org.springframework.test.context.ContextCustomizer; +import org.springframework.test.context.ContextCustomizerFactory; + +import java.util.List; + +public class SqlTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory { + + private static final Logger logger = LoggerFactory.getLogger(SqlTestContainersSpringContextCustomizerFactory.class); + + private static SqlTestContainer prodTestContainer; + + @Override + public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { + return (context, mergedConfig) -> { + ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); + TestPropertyValues testValues = TestPropertyValues.empty(); + EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class); + if (null != sqlAnnotation) { + logger.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName()); + logger.info("Warming up the sql database"); + if (null == prodTestContainer) { + try { + Class containerClass = (Class) Class.forName( + this.getClass().getPackageName() + ".PostgreSqlTestContainer" + ); + prodTestContainer = beanFactory.createBean(containerClass); + beanFactory.registerSingleton(containerClass.getName(), prodTestContainer); + // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), prodTestContainer); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + testValues = testValues.and("spring.datasource.url=" + prodTestContainer.getTestContainer().getJdbcUrl() + ""); + testValues = testValues.and("spring.datasource.username=" + prodTestContainer.getTestContainer().getUsername()); + testValues = testValues.and("spring.datasource.password=" + prodTestContainer.getTestContainer().getPassword()); + } + testValues.applyTo(context); + }; + } +} diff --git a/src/test/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfigurerTest.java b/src/test/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfigurerTest.java index acacc9a3b..62bc1bb28 100644 --- a/src/test/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfigurerTest.java +++ b/src/test/java/io/github/bbortt/event/planner/config/StaticResourcesWebConfigurerTest.java @@ -1,10 +1,5 @@ package io.github.bbortt.event.planner.config; -import static io.github.bbortt.event.planner.config.StaticResourcesWebConfiguration.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; - -import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.CacheControl; @@ -15,6 +10,18 @@ import tech.jhipster.config.JHipsterDefaults; import tech.jhipster.config.JHipsterProperties; +import java.util.concurrent.TimeUnit; + +import static io.github.bbortt.event.planner.config.StaticResourcesWebConfiguration.RESOURCE_LOCATIONS; +import static io.github.bbortt.event.planner.config.StaticResourcesWebConfiguration.RESOURCE_PATHS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + class StaticResourcesWebConfigurerTest { public static final int MAX_AGE_TEST = 5; diff --git a/src/test/java/io/github/bbortt/event/planner/config/TestContainersSpringContextCustomizerFactory.java b/src/test/java/io/github/bbortt/event/planner/config/TestContainersSpringContextCustomizerFactory.java deleted file mode 100644 index 78e4300ca..000000000 --- a/src/test/java/io/github/bbortt/event/planner/config/TestContainersSpringContextCustomizerFactory.java +++ /dev/null @@ -1,97 +0,0 @@ -package io.github.bbortt.event.planner.config; - -import java.util.Arrays; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.core.annotation.AnnotatedElementUtils; -import org.springframework.test.context.ContextConfigurationAttributes; -import org.springframework.test.context.ContextCustomizer; -import org.springframework.test.context.ContextCustomizerFactory; -import tech.jhipster.config.JHipsterConstants; - -public class TestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory { - - private Logger log = LoggerFactory.getLogger(TestContainersSpringContextCustomizerFactory.class); - - private static RedisTestContainer redisBean; - private static SqlTestContainer devTestContainer; - private static SqlTestContainer prodTestContainer; - - @Override - public ContextCustomizer createContextCustomizer(Class testClass, List configAttributes) { - return (context, mergedConfig) -> { - ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); - TestPropertyValues testValues = TestPropertyValues.empty(); - EmbeddedRedis redisAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedRedis.class); - if (null != redisAnnotation) { - log.debug("detected the EmbeddedRedis annotation on class {}", testClass.getName()); - log.info("Warming up the redis database"); - if (null == redisBean) { - redisBean = beanFactory.createBean(RedisTestContainer.class); - beanFactory.registerSingleton(RedisTestContainer.class.getName(), redisBean); - // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(RedisTestContainer.class.getName(), redisBean); - } - testValues = - testValues.and( - "jhipster.cache.redis.server=redis://" + - redisBean.getRedisContainer().getContainerIpAddress() + - ":" + - redisBean.getRedisContainer().getMappedPort(6379) - ); - } - EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class); - if (null != sqlAnnotation) { - log.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName()); - log.info("Warming up the sql database"); - if ( - Arrays - .asList(context.getEnvironment().getActiveProfiles()) - .contains("test" + JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) - ) { - if (null == devTestContainer) { - try { - Class containerClass = (Class) Class.forName( - this.getClass().getPackageName() + ".PostgreSqlTestContainer" - ); - devTestContainer = beanFactory.createBean(containerClass); - beanFactory.registerSingleton(containerClass.getName(), devTestContainer); - // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), devTestContainer); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - testValues = testValues.and("spring.datasource.url=" + devTestContainer.getTestContainer().getJdbcUrl() + ""); - testValues = testValues.and("spring.datasource.username=" + devTestContainer.getTestContainer().getUsername()); - testValues = testValues.and("spring.datasource.password=" + devTestContainer.getTestContainer().getPassword()); - } - if ( - Arrays - .asList(context.getEnvironment().getActiveProfiles()) - .contains("test" + JHipsterConstants.SPRING_PROFILE_PRODUCTION) - ) { - if (null == prodTestContainer) { - try { - Class containerClass = (Class) Class.forName( - this.getClass().getPackageName() + ".PostgreSqlTestContainer" - ); - prodTestContainer = beanFactory.createBean(containerClass); - beanFactory.registerSingleton(containerClass.getName(), prodTestContainer); - // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), prodTestContainer); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - testValues = testValues.and("spring.datasource.url=" + prodTestContainer.getTestContainer().getJdbcUrl() + ""); - testValues = testValues.and("spring.datasource.username=" + prodTestContainer.getTestContainer().getUsername()); - testValues = testValues.and("spring.datasource.password=" + prodTestContainer.getTestContainer().getPassword()); - } - } - testValues.applyTo(context); - }; - } -} diff --git a/src/test/java/io/github/bbortt/event/planner/config/WebConfigurerTest.java b/src/test/java/io/github/bbortt/event/planner/config/WebConfigurerTest.java index d53c2a1c9..2c52aadc4 100644 --- a/src/test/java/io/github/bbortt/event/planner/config/WebConfigurerTest.java +++ b/src/test/java/io/github/bbortt/event/planner/config/WebConfigurerTest.java @@ -1,18 +1,9 @@ package io.github.bbortt.event.planner.config; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.File; -import java.util.*; -import javax.servlet.*; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterRegistration; +import jakarta.servlet.Servlet; +import jakarta.servlet.ServletRegistration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; @@ -24,6 +15,22 @@ import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Unit tests for the {@link WebConfigurer} class. */ diff --git a/src/test/java/io/github/bbortt/event/planner/config/timezone/HibernateTimeZoneIT.java b/src/test/java/io/github/bbortt/event/planner/config/timezone/HibernateTimeZoneIT.java index 9ad29f60d..440577c1e 100644 --- a/src/test/java/io/github/bbortt/event/planner/config/timezone/HibernateTimeZoneIT.java +++ b/src/test/java/io/github/bbortt/event/planner/config/timezone/HibernateTimeZoneIT.java @@ -1,13 +1,8 @@ package io.github.bbortt.event.planner.config.timezone; -import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.repository.timezone.DateTimeWrapper; import io.github.bbortt.event.planner.repository.timezone.DateTimeWrapperRepository; -import java.time.*; -import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -16,6 +11,20 @@ import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.Month; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; + /** * Integration tests for the ZoneId Hibernate configuration. */ diff --git a/src/test/java/io/github/bbortt/event/planner/mail/MailServiceTest.java b/src/test/java/io/github/bbortt/event/planner/mail/MailServiceTest.java index 729cc65c8..9b52957dc 100644 --- a/src/test/java/io/github/bbortt/event/planner/mail/MailServiceTest.java +++ b/src/test/java/io/github/bbortt/event/planner/mail/MailServiceTest.java @@ -1,21 +1,12 @@ package io.github.bbortt.event.planner.mail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - import io.github.bbortt.event.planner.service.dto.MemberDTO; import io.github.bbortt.event.planner.service.dto.ProjectDTO; -import java.nio.charset.StandardCharsets; -import java.util.Optional; -import java.util.UUID; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; +import jakarta.mail.Message; +import jakarta.mail.MessagingException; +import jakarta.mail.Multipart; +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,6 +15,16 @@ import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.util.ReflectionTestUtils; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @ExtendWith(MockitoExtension.class) class MailServiceTest { diff --git a/src/test/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactoryTest.java b/src/test/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactoryTest.java index e3c3018b2..50ebbcfc8 100644 --- a/src/test/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactoryTest.java +++ b/src/test/java/io/github/bbortt/event/planner/mail/ProjectInvitationMailFactoryTest.java @@ -1,12 +1,6 @@ package io.github.bbortt.event.planner.mail; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -19,6 +13,12 @@ import org.thymeleaf.context.Context; import tech.jhipster.config.JHipsterProperties; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + @ExtendWith(MockitoExtension.class) class ProjectInvitationMailFactoryTest { diff --git a/src/test/java/io/github/bbortt/event/planner/repository/EventRepositoryIT.java b/src/test/java/io/github/bbortt/event/planner/repository/EventRepositoryIT.java index ef5c7ffdd..7fcdb24db 100644 --- a/src/test/java/io/github/bbortt/event/planner/repository/EventRepositoryIT.java +++ b/src/test/java/io/github/bbortt/event/planner/repository/EventRepositoryIT.java @@ -1,25 +1,24 @@ package io.github.bbortt.event.planner.repository; -import static org.junit.jupiter.api.Assertions.assertEquals; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Event; import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.domain.Project; -import io.github.bbortt.event.planner.service.dto.EventDTO; -import io.github.bbortt.event.planner.web.rest.EventResource; import io.github.bbortt.event.planner.web.rest.EventResourceIT; import io.github.bbortt.event.planner.web.rest.LocationResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.UUID; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + @IntegrationTest class EventRepositoryIT { diff --git a/src/test/java/io/github/bbortt/event/planner/repository/LocationRepositoryIT.java b/src/test/java/io/github/bbortt/event/planner/repository/LocationRepositoryIT.java index 9912264ae..7616cfa45 100644 --- a/src/test/java/io/github/bbortt/event/planner/repository/LocationRepositoryIT.java +++ b/src/test/java/io/github/bbortt/event/planner/repository/LocationRepositoryIT.java @@ -1,17 +1,18 @@ package io.github.bbortt.event.planner.repository; -import static org.junit.jupiter.api.Assertions.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.web.rest.LocationResourceIT; -import java.util.List; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + @IntegrationTest class LocationRepositoryIT { diff --git a/src/test/java/io/github/bbortt/event/planner/repository/MemberRepositoryIT.java b/src/test/java/io/github/bbortt/event/planner/repository/MemberRepositoryIT.java index 5313e30b4..75948e355 100644 --- a/src/test/java/io/github/bbortt/event/planner/repository/MemberRepositoryIT.java +++ b/src/test/java/io/github/bbortt/event/planner/repository/MemberRepositoryIT.java @@ -1,22 +1,22 @@ package io.github.bbortt.event.planner.repository; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.web.rest.MemberResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.Objects; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.transaction.annotation.Transactional; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + @IntegrationTest class MemberRepositoryIT { diff --git a/src/test/java/io/github/bbortt/event/planner/repository/ProjectRepositoryIT.java b/src/test/java/io/github/bbortt/event/planner/repository/ProjectRepositoryIT.java index de8df237c..4f6ca8f82 100644 --- a/src/test/java/io/github/bbortt/event/planner/repository/ProjectRepositoryIT.java +++ b/src/test/java/io/github/bbortt/event/planner/repository/ProjectRepositoryIT.java @@ -1,17 +1,11 @@ package io.github.bbortt.event.planner.repository; -import static io.github.bbortt.event.planner.test.util.SecurityContextUtil.setCurrentUsernameInAuthenticationContext; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.web.rest.MemberResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.Optional; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; @@ -19,6 +13,13 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.transaction.annotation.Transactional; +import java.util.Optional; +import java.util.UUID; + +import static io.github.bbortt.event.planner.test.util.SecurityContextUtil.setCurrentUsernameInAuthenticationContext; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + @IntegrationTest @WithMockUser("project-repository-it") class ProjectRepositoryIT { @@ -121,6 +122,6 @@ void findByTokenReturnsMatchingOnly() { Optional result = projectRepository.findByToken(token); assertTrue(result.isPresent()); - assertEquals(project, result.get()); + assertEquals(project, result.orElseThrow(IllegalArgumentException::new)); } } diff --git a/src/test/java/io/github/bbortt/event/planner/repository/timezone/DateTimeWrapper.java b/src/test/java/io/github/bbortt/event/planner/repository/timezone/DateTimeWrapper.java index 53a406dad..52d319fc7 100644 --- a/src/test/java/io/github/bbortt/event/planner/repository/timezone/DateTimeWrapper.java +++ b/src/test/java/io/github/bbortt/event/planner/repository/timezone/DateTimeWrapper.java @@ -1,9 +1,22 @@ package io.github.bbortt.event.planner.repository.timezone; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; + import java.io.Serializable; -import java.time.*; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.OffsetTime; +import java.time.ZonedDateTime; import java.util.Objects; -import javax.persistence.*; @Entity @Table(name = "jhi_date_time_wrapper") diff --git a/src/test/java/io/github/bbortt/event/planner/security/SecurityUtilsUnitTest.java b/src/test/java/io/github/bbortt/event/planner/security/SecurityUtilsUnitTest.java index c0197e2f7..823e9d5d9 100644 --- a/src/test/java/io/github/bbortt/event/planner/security/SecurityUtilsUnitTest.java +++ b/src/test/java/io/github/bbortt/event/planner/security/SecurityUtilsUnitTest.java @@ -1,10 +1,5 @@ package io.github.bbortt.event.planner.security; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames.ID_TOKEN; - -import java.time.Instant; -import java.util.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -18,6 +13,18 @@ import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames.ID_TOKEN; + /** * Test class for the {@link SecurityUtils} utility class. */ diff --git a/src/test/java/io/github/bbortt/event/planner/service/LocationServiceIT.java b/src/test/java/io/github/bbortt/event/planner/service/LocationServiceIT.java index 77551c7ca..cda30e10d 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/LocationServiceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/service/LocationServiceIT.java @@ -1,23 +1,23 @@ package io.github.bbortt.event.planner.service; -import static org.junit.jupiter.api.Assertions.assertEquals; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.service.dto.LocationDTO; import io.github.bbortt.event.planner.web.rest.LocationResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.transaction.annotation.Transactional; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; + @IntegrationTest @WithMockUser("location-service-it") class LocationServiceIT { diff --git a/src/test/java/io/github/bbortt/event/planner/service/MemberServiceIT.java b/src/test/java/io/github/bbortt/event/planner/service/MemberServiceIT.java index 93c3dfe22..d8c42d667 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/MemberServiceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/service/MemberServiceIT.java @@ -1,11 +1,5 @@ package io.github.bbortt.event.planner.service; -import static io.github.bbortt.event.planner.test.util.SecurityContextUtil.setCurrentUsernameInAuthenticationContext; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; @@ -14,8 +8,7 @@ import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.web.rest.MemberResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -25,6 +18,14 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.transaction.annotation.Transactional; +import java.util.UUID; + +import static io.github.bbortt.event.planner.test.util.SecurityContextUtil.setCurrentUsernameInAuthenticationContext; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + @IntegrationTest @WithMockUser("member-service-it") class MemberServiceIT { diff --git a/src/test/java/io/github/bbortt/event/planner/service/MemberServiceTest.java b/src/test/java/io/github/bbortt/event/planner/service/MemberServiceTest.java index dd00b0a1b..415b16cc0 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/MemberServiceTest.java +++ b/src/test/java/io/github/bbortt/event/planner/service/MemberServiceTest.java @@ -85,7 +85,7 @@ void findOneInProjectByInvitationEmailCallsRepository() { Optional result = fixture.findOneInProjectByInvitationEmail(projectId, invitedEmail); assertTrue(result.isPresent()); - assertEquals(memberDTO, result.get()); + assertEquals(memberDTO, result.orElseThrow(IllegalArgumentException::new)); } @Test diff --git a/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceIT.java b/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceIT.java index a5c8fb91d..48dd947d5 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceIT.java @@ -1,16 +1,12 @@ package io.github.bbortt.event.planner.service; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.repository.ProjectRepository; import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.service.mapper.ProjectMapper; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; @@ -18,6 +14,11 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.transaction.annotation.Transactional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + @IntegrationTest @WithMockUser("project-service-it") class ProjectServiceIT { diff --git a/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceTest.java b/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceTest.java index 09da5607d..d26705c9d 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceTest.java +++ b/src/test/java/io/github/bbortt/event/planner/service/ProjectServiceTest.java @@ -1,22 +1,10 @@ package io.github.bbortt.event.planner.service; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.repository.ProjectRepository; import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.service.mapper.ProjectMapper; import io.github.bbortt.event.planner.web.rest.errors.EntityNotFoundAlertException; -import java.util.List; -import java.util.Optional; -import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,11 +14,24 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.SliceImpl; +import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.util.ReflectionTestUtils; -import org.zalando.problem.Status; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; @ExtendWith(MockitoExtension.class) class ProjectServiceTest { @@ -80,7 +81,7 @@ void findOneCallsRepository() { Optional result = fixture.findOne(projectId); assertTrue(result.isPresent()); - assertEquals(projectDTO, result.get()); + assertEquals(projectDTO, result.orElseThrow(IllegalArgumentException::new)); } @Test @@ -107,7 +108,7 @@ void findOneOrThrowsEntityNotFoundAlertExceptionWhenProjectByIdDoesNotExist() { () -> fixture.findOneOrThrowEntityNotFoundAlertException(projectId) ); - assertEquals(Status.NOT_FOUND, exception.getStatus()); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatusCode()); assertEquals("idnotfound", exception.getErrorKey()); assertEquals("project", exception.getEntityName()); @@ -127,7 +128,7 @@ void findOneByTokenCallsRepository() { Optional result = fixture.findOneByToken(token.toString()); assertTrue(result.isPresent()); - assertEquals(projectDTO, result.get()); + assertEquals(projectDTO, result.orElseThrow(IllegalArgumentException::new)); } @Test diff --git a/src/test/java/io/github/bbortt/event/planner/service/mapper/MemberMapperTest.java b/src/test/java/io/github/bbortt/event/planner/service/mapper/MemberMapperTest.java index 575679245..1ee227dc7 100644 --- a/src/test/java/io/github/bbortt/event/planner/service/mapper/MemberMapperTest.java +++ b/src/test/java/io/github/bbortt/event/planner/service/mapper/MemberMapperTest.java @@ -1,22 +1,11 @@ package io.github.bbortt.event.planner.service.mapper; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - import io.github.bbortt.event.planner.domain.Member; -import io.github.bbortt.event.planner.domain.Project; -import io.github.bbortt.event.planner.domain.User; import io.github.bbortt.event.planner.service.dto.AdminUserDTO; import io.github.bbortt.event.planner.service.dto.MemberDTO; -import io.github.bbortt.event.planner.web.rest.ProjectResource; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import io.github.bbortt.event.planner.web.rest.PublicUserResource; import io.github.bbortt.event.planner.web.rest.UserResourceIT; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,6 +13,13 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; + @ExtendWith(MockitoExtension.class) class MemberMapperTest { diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiIT.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiIT.java index 0369a3652..54343cb0d 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiIT.java @@ -1,17 +1,8 @@ package io.github.bbortt.event.planner.web.api; -import static io.github.bbortt.event.planner.config.Constants.SLICE_HAS_NEXT_PAGE_HEADER; -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -20,6 +11,16 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.util.UUID; + +import static io.github.bbortt.event.planner.config.Constants.SLICE_HAS_NEXT_PAGE_HEADER; +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @IntegrationTest @AutoConfigureMockMvc @WithMockUser("project-api-it") diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiTest.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiTest.java index 3899b64b4..e17c3a72f 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiTest.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectApiTest.java @@ -1,20 +1,11 @@ package io.github.bbortt.event.planner.web.api; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verifyNoInteractions; - import io.github.bbortt.event.planner.service.ProjectService; import io.github.bbortt.event.planner.service.api.dto.GetUserProjects200Response; import io.github.bbortt.event.planner.service.api.dto.Project; import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.web.api.mapper.ApiProjectMapper; import io.github.bbortt.event.planner.web.rest.util.PaginationUtil; -import java.util.Collections; -import java.util.List; -import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -28,6 +19,15 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.server.ResponseStatusException; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doReturn; + @ExtendWith(MockitoExtension.class) class ProjectApiTest { @@ -73,7 +73,7 @@ void findProjectByTokenNotFound() { ResponseStatusException exception = assertThrows(ResponseStatusException.class, () -> fixture.findProjectByToken(projectToken)); - assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatusCode()); } @Test diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiIT.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiIT.java index 72d862cbc..deddcd77c 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiIT.java @@ -1,32 +1,13 @@ package io.github.bbortt.event.planner.web.api; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.fasterxml.jackson.databind.ObjectMapper; import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Event; import io.github.bbortt.event.planner.domain.Location; -import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; -import io.github.bbortt.event.planner.repository.MemberRepository; -import io.github.bbortt.event.planner.service.mapper.MemberMapper; -import io.github.bbortt.event.planner.web.api.mapper.ApiProjectMemberMapper; import io.github.bbortt.event.planner.web.rest.EventResourceIT; import io.github.bbortt.event.planner.web.rest.LocationResourceIT; -import io.github.bbortt.event.planner.web.rest.MemberResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import io.github.bbortt.event.planner.web.rest.TestUtil; -import java.util.List; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,7 +16,15 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import org.yaml.snakeyaml.util.UriEncoder; + +import java.util.UUID; + +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @IntegrationTest @AutoConfigureMockMvc diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiTest.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiTest.java index 1ad2ff12e..d990e063b 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiTest.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectEventsApiTest.java @@ -74,7 +74,7 @@ void getProjectEventsCallsService() { Optional pageNumber = Optional.of(0); Optional> sort = Optional.of(Collections.singletonList("id,asc")); - PageRequest pageRequest = PageRequest.of(pageNumber.get(), pageSize.get()); + PageRequest pageRequest = PageRequest.of(pageNumber.orElseThrow(IllegalArgumentException::new), pageSize.orElseThrow(IllegalArgumentException::new)); doReturn(pageRequest).when(paginationUtilMock).createPagingInformation(pageSize, pageNumber, sort, "id"); // Project by ID exists diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiIT.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiIT.java index e56f27288..aa63f62f7 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectLocationApiIT.java @@ -1,20 +1,12 @@ package io.github.bbortt.event.planner.web.api; -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.repository.LocationRepository; import io.github.bbortt.event.planner.web.rest.LocationResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; -import java.util.List; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -24,6 +16,15 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.util.List; +import java.util.UUID; + +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @IntegrationTest @AutoConfigureMockMvc @WithMockUser("project-location-api-it") diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiIT.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiIT.java index 3e2b2cbc4..55d83595b 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiIT.java @@ -1,29 +1,16 @@ package io.github.bbortt.event.planner.web.api; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import com.fasterxml.jackson.databind.ObjectMapper; import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.repository.MemberRepository; -import io.github.bbortt.event.planner.service.dto.MemberDTO; import io.github.bbortt.event.planner.service.mapper.MemberMapper; import io.github.bbortt.event.planner.web.api.mapper.ApiProjectMemberMapper; import io.github.bbortt.event.planner.web.rest.MemberResourceIT; import io.github.bbortt.event.planner.web.rest.ProjectResourceIT; import io.github.bbortt.event.planner.web.rest.TestUtil; -import java.util.List; -import java.util.UUID; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -34,6 +21,19 @@ import org.springframework.transaction.annotation.Transactional; import org.yaml.snakeyaml.util.UriEncoder; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @IntegrationTest @AutoConfigureMockMvc @WithMockUser("project-member-api-it") diff --git a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiTest.java b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiTest.java index 81e1c5d8a..945778572 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiTest.java +++ b/src/test/java/io/github/bbortt/event/planner/web/api/ProjectMemberApiTest.java @@ -1,14 +1,5 @@ package io.github.bbortt.event.planner.web.api; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - import io.github.bbortt.event.planner.service.MemberService; import io.github.bbortt.event.planner.service.ProjectService; import io.github.bbortt.event.planner.service.api.dto.GetProjectMembers200Response; @@ -18,9 +9,6 @@ import io.github.bbortt.event.planner.web.api.mapper.ApiProjectMemberMapper; import io.github.bbortt.event.planner.web.rest.errors.EntityNotFoundAlertException; import io.github.bbortt.event.planner.web.rest.util.PaginationUtil; -import java.util.Collections; -import java.util.List; -import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -37,7 +25,19 @@ import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import org.zalando.problem.Status; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; @ExtendWith(MockitoExtension.class) class ProjectMemberApiTest { @@ -118,7 +118,7 @@ void findNonExistentProjectMemberByTokenAndEmailForExistingProject() { () -> fixture.findProjectMemberByTokenAndEmail(projectId, invitedEmail) ); - assertEquals(HttpStatus.NOT_FOUND, exception.getStatus()); + assertEquals(HttpStatus.NOT_FOUND, exception.getStatusCode()); } @Test @@ -132,7 +132,7 @@ void getProjectMembersForExistingProject() { // Project by ID exists doReturn(new ProjectDTO()).when(projectServiceMock).findOneOrThrowEntityNotFoundAlertException(projectId); - PageRequest pageRequest = PageRequest.of(pageNumber.get(), pageSize.get()); + PageRequest pageRequest = PageRequest.of(pageNumber.orElseThrow(IllegalArgumentException::new), pageSize.orElseThrow(IllegalArgumentException::new)); doReturn(pageRequest).when(paginationUtilMock).createPagingInformation(pageSize, pageNumber, sort, "id"); MemberDTO memberDTO = new MemberDTO(); diff --git a/src/test/java/io/github/bbortt/event/planner/web/filter/SpaWebFilterIT.java b/src/test/java/io/github/bbortt/event/planner/web/filter/SpaWebFilterIT.java new file mode 100644 index 000000000..642d5392f --- /dev/null +++ b/src/test/java/io/github/bbortt/event/planner/web/filter/SpaWebFilterIT.java @@ -0,0 +1,84 @@ +package io.github.bbortt.event.planner.web.filter; + +import io.github.bbortt.event.planner.IntegrationTest; +import io.github.bbortt.event.planner.security.AuthoritiesConstants; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WithMockUser +@IntegrationTest +@AutoConfigureMockMvc +class SpaWebFilterIT { + + @Autowired + private MockMvc mockMvc; + + @Test + void testFilterForwardsToIndex() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + @WithMockUser(authorities = AuthoritiesConstants.ADMIN) + void testFilterDoesNotForwardToIndexForV3ApiDocs() throws Exception { + mockMvc.perform(get("/v3/api-docs")).andExpect(status().isOk()).andExpect(forwardedUrl(null)); + } + + @Test + void testFilterDoesNotForwardToIndexForDotFile() throws Exception { + mockMvc.perform(get("/file.js")).andExpect(status().isNotFound()); + } + + @Test + void getBackendEndpoint() throws Exception { + mockMvc.perform(get("/test")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedFirstLevelMapping() throws Exception { + mockMvc.perform(get("/first-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedSecondLevelMapping() throws Exception { + mockMvc.perform(get("/first-level/second-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedThirdLevelMapping() throws Exception { + mockMvc.perform(get("/first-level/second-level/third-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); + } + + @Test + void forwardUnmappedDeepMapping() throws Exception { + mockMvc.perform(get("/1/2/3/4/5/6/7/8/9/10")).andExpect(forwardedUrl("/index.html")); + } + + @Test + void getUnmappedFirstLevelFile() throws Exception { + mockMvc.perform(get("/foo.js")).andExpect(status().isNotFound()); + } + + /** + * This test verifies that any files that aren't permitted by Spring Security will be forbidden. + * If you want to change this to return isNotFound(), you need to add a request mapping that + * allows this file in SecurityConfiguration. + */ + @Test + void getUnmappedSecondLevelFile() throws Exception { + mockMvc.perform(get("/foo/bar.js")).andExpect(status().isForbidden()); + } + + @Test + void getUnmappedThirdLevelFile() throws Exception { + mockMvc.perform(get("/foo/another/bar.js")).andExpect(status().isForbidden()); + } +} + diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/AccountResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/AccountResourceIT.java index 11058a68d..bc0694903 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/AccountResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/AccountResourceIT.java @@ -1,11 +1,5 @@ package io.github.bbortt.event.planner.web.rest; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.TEST_USER_LOGIN; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.registerAuthenticationToken; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.testAuthenticationToken; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.security.AuthoritiesConstants; import org.junit.jupiter.api.Test; @@ -19,6 +13,14 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.TEST_USER_LOGIN; +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.registerAuthenticationToken; +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.testAuthenticationToken; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link AccountResource} REST controller. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/ClientForwardControllerTest.java b/src/test/java/io/github/bbortt/event/planner/web/rest/ClientForwardControllerTest.java deleted file mode 100644 index c16099ebe..000000000 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/ClientForwardControllerTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package io.github.bbortt.event.planner.web.rest; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * Unit tests for the {@link ClientForwardController} REST controller. - */ -class ClientForwardControllerTest { - - private MockMvc restMockMvc; - - @BeforeEach - void setup() { - ClientForwardController clientForwardController = new ClientForwardController(); - this.restMockMvc = MockMvcBuilders.standaloneSetup(clientForwardController, new TestController()).build(); - } - - @Test - void getBackendEndpoint() throws Exception { - restMockMvc - .perform(get("/test")) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE)) - .andExpect(content().string("test")); - } - - @Test - void getClientEndpoint() throws Exception { - ResultActions perform = restMockMvc.perform(get("/non-existant-mapping")); - perform.andExpect(status().isOk()).andExpect(forwardedUrl("/")); - } - - @Test - void getNestedClientEndpoint() throws Exception { - restMockMvc.perform(get("/admin/user-management")).andExpect(status().isOk()).andExpect(forwardedUrl("/")); - } - - @Test - void getUnmappedDottedEndpoint() throws Exception { - restMockMvc.perform(get("/foo.js")).andExpect(status().isNotFound()); - } - - @Test - void getUnmappedNestedDottedEndpoint() throws Exception { - restMockMvc.perform(get("/foo/bar.js")).andExpect(status().isNotFound()); - } - - @Test - void getWebsocketInfoEndpoint() throws Exception { - restMockMvc.perform(get("/websocket/info")).andExpect(status().isNotFound()); - } - - @Test - void getWebsocketEndpoint() throws Exception { - restMockMvc.perform(get("/websocket/tracker/308/sessionId/websocket")).andExpect(status().isNotFound()); - } - - @Test - void getWebsocketFallbackEndpoint() throws Exception { - restMockMvc.perform(get("/websocket/tracker/308/sessionId/xhr_streaming")).andExpect(status().isNotFound()); - } - - @RestController - public static class TestController { - - @RequestMapping(value = "/test") - public String test() { - return "test"; - } - } -} diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/EventResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/EventResourceIT.java index c37d57542..1fa9c5a7a 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/EventResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/EventResourceIT.java @@ -1,21 +1,5 @@ package io.github.bbortt.event.planner.web.rest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Event; import io.github.bbortt.event.planner.domain.Location; @@ -23,11 +7,7 @@ import io.github.bbortt.event.planner.service.EventService; import io.github.bbortt.event.planner.service.dto.EventDTO; import io.github.bbortt.event.planner.service.mapper.EventMapper; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -42,6 +22,27 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link EventResource} REST controller. */ @@ -259,7 +260,7 @@ void putExistingEvent() throws Exception { int databaseSizeBeforeUpdate = eventRepository.findAll().size(); // Update the event - Event updatedEvent = eventRepository.findById(event.getId()).get(); + Event updatedEvent = eventRepository.findById(event.getId()).orElseThrow(IllegalArgumentException::new);; // Disconnect from session so that the updates on updatedEvent are not directly saved in db em.detach(updatedEvent); updatedEvent.name(UPDATED_NAME); diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/LocationResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/LocationResourceIT.java index 5c2e17176..caf8f2e68 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/LocationResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/LocationResourceIT.java @@ -1,12 +1,5 @@ package io.github.bbortt.event.planner.web.rest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.Mockito.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Location; import io.github.bbortt.event.planner.domain.Project; @@ -14,13 +7,7 @@ import io.github.bbortt.event.planner.service.LocationService; import io.github.bbortt.event.planner.service.dto.LocationDTO; import io.github.bbortt.event.planner.service.mapper.LocationMapper; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -29,13 +16,33 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link LocationResource} REST controller. */ @@ -259,7 +266,7 @@ void putExistingLocation() throws Exception { int databaseSizeBeforeUpdate = locationRepository.findAll().size(); // Update the location - Location updatedLocation = locationRepository.findById(location.getId()).get(); + Location updatedLocation = locationRepository.findById(location.getId()).orElseThrow(IllegalArgumentException::new);; // Disconnect from session so that the updates on updatedLocation are not directly saved in db em.detach(updatedLocation); updatedLocation.name(UPDATED_NAME).description(UPDATED_DESCRIPTION); diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/LogoutResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/LogoutResourceIT.java index 474b958ef..d2917298e 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/LogoutResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/LogoutResourceIT.java @@ -1,16 +1,7 @@ package io.github.bbortt.event.planner.web.rest; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.ID_TOKEN; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.authenticationToken; -import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.registerAuthenticationToken; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.security.AuthoritiesConstants; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -25,6 +16,18 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.ID_TOKEN; +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.authenticationToken; +import static io.github.bbortt.event.planner.test.util.OAuth2TestUtil.registerAuthenticationToken; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link LogoutResource} REST controller. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/MemberResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/MemberResourceIT.java index fb70ca50d..c46d81730 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/MemberResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/MemberResourceIT.java @@ -1,12 +1,5 @@ package io.github.bbortt.event.planner.web.rest; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.mockito.Mockito.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Member; import io.github.bbortt.event.planner.domain.Project; @@ -15,13 +8,7 @@ import io.github.bbortt.event.planner.service.MemberService; import io.github.bbortt.event.planner.service.dto.MemberDTO; import io.github.bbortt.event.planner.service.mapper.MemberMapper; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -30,13 +17,35 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link MemberResource} REST controller. */ @@ -329,7 +338,7 @@ void putExistingMember() throws Exception { int databaseSizeBeforeUpdate = memberRepository.findAll().size(); // Update the member - Member updatedMember = memberRepository.findById(member.getId()).get(); + Member updatedMember = memberRepository.findById(member.getId()).orElseThrow(IllegalArgumentException::new);; // Disconnect from session so that the updates on updatedMember are not directly saved in db em.detach(updatedMember); updatedMember.invitedEmail("hope-pym@localhost").accepted(UPDATED_ACCEPTED); diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/ProjectResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/ProjectResourceIT.java index c5c576918..10ae699c7 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/ProjectResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/ProjectResourceIT.java @@ -1,27 +1,11 @@ package io.github.bbortt.event.planner.web.rest; -import static io.github.bbortt.event.planner.web.rest.TestUtil.sameInstant; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Project; import io.github.bbortt.event.planner.repository.ProjectRepository; import io.github.bbortt.event.planner.service.dto.ProjectDTO; import io.github.bbortt.event.planner.service.mapper.ProjectMapper; -import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Random; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -31,6 +15,26 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import static io.github.bbortt.event.planner.web.rest.TestUtil.sameInstant; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link ProjectResource} REST controller. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/PublicUserResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/PublicUserResourceIT.java index 5f1b68f5a..5d082bcf2 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/PublicUserResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/PublicUserResourceIT.java @@ -1,18 +1,10 @@ package io.github.bbortt.event.planner.web.rest; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.User; import io.github.bbortt.event.planner.repository.UserRepository; import io.github.bbortt.event.planner.security.AuthoritiesConstants; -import java.util.Objects; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -23,6 +15,15 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; +import java.util.Objects; + +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + /** * Integration tests for the {@link PublicUserResource} REST controller. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/TestUtil.java b/src/test/java/io/github/bbortt/event/planner/web/rest/TestUtil.java index 6bb6bbd90..f2d358ff5 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/TestUtil.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/TestUtil.java @@ -1,22 +1,14 @@ package io.github.bbortt.event.planner.web.rest; -import static org.assertj.core.api.Assertions.assertThat; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import java.io.IOException; -import java.math.BigDecimal; -import java.time.Instant; -import java.time.ZonedDateTime; -import java.time.format.DateTimeParseException; -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.TypeSafeMatcher; @@ -24,6 +16,15 @@ import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.Instant; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + /** * Utility class for testing REST controllers. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/UserResourceIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/UserResourceIT.java index ab79a54e9..8ce2bb847 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/UserResourceIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/UserResourceIT.java @@ -1,7 +1,5 @@ package io.github.bbortt.event.planner.web.rest; -import static org.assertj.core.api.Assertions.assertThat; - import io.github.bbortt.event.planner.IntegrationTest; import io.github.bbortt.event.planner.domain.Authority; import io.github.bbortt.event.planner.domain.User; @@ -9,10 +7,7 @@ import io.github.bbortt.event.planner.security.AuthoritiesConstants; import io.github.bbortt.event.planner.service.dto.AdminUserDTO; import io.github.bbortt.event.planner.service.mapper.UserMapper; -import java.time.Instant; -import java.util.*; -import java.util.function.Consumer; -import javax.persistence.EntityManager; +import jakarta.persistence.EntityManager; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +17,16 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; +import java.time.Instant; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; + /** * Integration tests for the {@link PublicUserResource} REST controller. */ diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorIT.java b/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorIT.java index 088eb492b..184fd8200 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorIT.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorIT.java @@ -96,7 +96,7 @@ void testMethodNotSupported() throws Exception { .andExpect(status().isMethodNotAllowed()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.405")) - .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + .andExpect(jsonPath("$.detail").value("Request method 'POST' is not supported")); } @Test diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorTestController.java b/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorTestController.java index 5b2933a14..21c1c7e26 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorTestController.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/errors/ExceptionTranslatorTestController.java @@ -1,12 +1,19 @@ package io.github.bbortt.event.planner.web.rest.errors; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/exception-translator-test") diff --git a/src/test/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtilTest.java b/src/test/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtilTest.java index cf0de6407..3204b02c2 100644 --- a/src/test/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtilTest.java +++ b/src/test/java/io/github/bbortt/event/planner/web/rest/util/PaginationUtilTest.java @@ -1,17 +1,17 @@ package io.github.bbortt.event.planner.web.rest.util; -import static io.github.bbortt.event.planner.config.Constants.DEFAULT_PAGE_SIZE; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.List; -import java.util.Optional; -import javax.swing.text.html.Option; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import java.util.List; +import java.util.Optional; + +import static io.github.bbortt.event.planner.config.Constants.DEFAULT_PAGE_SIZE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + class PaginationUtilTest { private final String defaultSorgingPropertyName = "test-default-sorting"; diff --git a/src/test/resources/META-INF/spring.factories b/src/test/resources/META-INF/spring.factories index f3f7cafd1..d56c2373d 100644 --- a/src/test/resources/META-INF/spring.factories +++ b/src/test/resources/META-INF/spring.factories @@ -1 +1,2 @@ -org.springframework.test.context.ContextCustomizerFactory = io.github.bbortt.event.planner.config.TestContainersSpringContextCustomizerFactory +org.springframework.test.context.ContextCustomizerFactory = io.github.bbortt.event.planner.config.SqlTestContainersSpringContextCustomizerFactory,\ + io.github.bbortt.event.planner.config.RedisTestContainersSpringContextCustomizerFactory diff --git a/src/test/resources/config/application-testdev.yml b/src/test/resources/config/application-testdev.yml index 4b59759dd..0258e9169 100644 --- a/src/test/resources/config/application-testdev.yml +++ b/src/test/resources/config/application-testdev.yml @@ -16,12 +16,11 @@ spring: maximum-pool-size: 1 poolName: Hikari jpa: - database-platform: tech.jhipster.domain.util.FixedPostgreSQL10Dialect hibernate: ddl-auto: none naming: implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy + physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy open-in-view: false properties: hibernate.id.new_generator_mappings: true @@ -30,5 +29,6 @@ spring: hibernate.cache.use_query_cache: false hibernate.generate_statistics: false hibernate.hbm2ddl.auto: validate + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP hibernate.jdbc.time_zone: UTC hibernate.query.fail_on_pagination_over_collection_fetch: true diff --git a/src/test/resources/config/application-testprod.yml b/src/test/resources/config/application-testprod.yml index 4b59759dd..0258e9169 100644 --- a/src/test/resources/config/application-testprod.yml +++ b/src/test/resources/config/application-testprod.yml @@ -16,12 +16,11 @@ spring: maximum-pool-size: 1 poolName: Hikari jpa: - database-platform: tech.jhipster.domain.util.FixedPostgreSQL10Dialect hibernate: ddl-auto: none naming: implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy - physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy + physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy open-in-view: false properties: hibernate.id.new_generator_mappings: true @@ -30,5 +29,6 @@ spring: hibernate.cache.use_query_cache: false hibernate.generate_statistics: false hibernate.hbm2ddl.auto: validate + hibernate.type.preferred_instant_jdbc_type: TIMESTAMP hibernate.jdbc.time_zone: UTC hibernate.query.fail_on_pagination_over_collection_fetch: true diff --git a/src/test/resources/config/application.yml b/src/test/resources/config/application.yml index be836e727..f6801b177 100644 --- a/src/test/resources/config/application.yml +++ b/src/test/resources/config/application.yml @@ -72,7 +72,7 @@ jhipster: enabled: false host: localhost port: 5000 - queue-size: 512 + ring-buffer-size: 512 # =================================================================== # Application specific properties diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml index 2fc5e5766..9cc430516 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback.xml @@ -12,9 +12,9 @@ - - - + + + @@ -37,14 +37,9 @@ - - - - - WARN - - - + + + diff --git a/webpack/webpack.custom.js b/webpack/webpack.custom.js index 0e2f4127b..eca9c2510 100644 --- a/webpack/webpack.custom.js +++ b/webpack/webpack.custom.js @@ -32,7 +32,7 @@ module.exports = async (config, options, targetOptions) => { new WebpackNotifierPlugin({ title: 'Event Planner', contentImage: path.join(__dirname, 'logo-jhipster.png'), - }) + }), ); } @@ -72,8 +72,8 @@ module.exports = async (config, options, targetOptions) => { }, { reload: targetOptions.target === 'build', // enabled for build --watch - } - ) + }, + ), ); } @@ -84,7 +84,7 @@ module.exports = async (config, options, targetOptions) => { openAnalyzer: false, // Webpack statistics in target folder reportFilename: '../stats.html', - }) + }), ); } @@ -128,11 +128,11 @@ module.exports = async (config, options, targetOptions) => { // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array ], }, - }) + }), ); config = merge( - config + config, // jhipster-needle-add-webpack-config - JHipster will add custom config );