From b5ca0067a148740862c6472f7dbdd04b7657d4d3 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 19 Dec 2024 18:03:53 +0100 Subject: [PATCH 01/47] feat: upgrade to spring boot 3.0.X --- .github/workflows/admin-api-documentation.yml | 2 +- .github/workflows/dockerImage.yml | 2 +- .github/workflows/feature-branch.yml | 2 +- api/appointmentservice.yaml | 15 + pom.xml | 128 ++-- pom2.xml | 643 ++++++++++++++++++ .../cob/userservice/api/AccountManager.java | 3 +- .../api/UserServiceApplication.java | 2 +- .../api/actions/registry/ActionContainer.java | 5 +- .../adapters/keycloak/KeycloakService.java | 19 +- .../keycloak/config/KeycloakConfig.java | 18 +- .../keycloak/config/KeycloakCustomConfig.java | 2 +- .../RocketChatCredentialsProvider.java | 2 +- .../rocketchat/RocketChatService.java | 49 +- .../rocketchat/config/RocketChatConfig.java | 12 +- .../dto/message/attachment/AttachmentDTO.java | 4 +- .../dto/message/attachment/FileDTO.java | 9 +- .../web/controller/AppointmentController.java | 8 +- .../controller/ConversationController.java | 6 +- .../web/controller/LiveProxyController.java | 4 +- .../web/controller/UserAdminController.java | 8 +- .../web/controller/UserController.java | 34 +- .../controller/UserStatisticsController.java | 4 +- .../ApiResponseEntityExceptionHandler.java | 13 +- .../interceptor/CorrelationIdFilter.java | 8 +- .../interceptor/HttpTenantFilter.java | 8 +- .../interceptor/StatelessCsrfFilter.java | 10 +- .../api/adapters/web/dto/ChatDTO.java | 29 +- .../web/dto/GroupSessionConsultantDTO.java | 11 +- .../adapters/web/dto/NewRegistrationDto.java | 35 +- .../web/dto/SessionConsultantForUserDTO.java | 11 +- .../api/adapters/web/dto/SessionUserDTO.java | 11 +- .../api/adapters/web/dto/UserChatDTO.java | 44 +- .../api/adapters/web/dto/UserDTO.java | 47 +- .../adapters/web/dto/UserDataResponseDTO.java | 35 +- .../validation/MandatoryFieldsProvider.java | 5 +- .../adapters/web/dto/validation/ValidAge.java | 4 +- .../web/dto/validation/ValidAgeValidator.java | 4 +- .../web/dto/validation/ValidState.java | 4 +- .../dto/validation/ValidStateValidator.java | 4 +- .../web/mapping/ConsultantDtoMapper.java | 3 +- .../adapters/web/mapping/UserDtoMapper.java | 5 +- .../admin/facade/AskerUserAdminFacade.java | 2 +- .../admin/facade/ConsultantAdminFacade.java | 2 +- .../registry/ViolationRuleRegistry.java | 4 +- .../service/ViolationReportGenerator.java | 7 +- .../api/admin/service/FilterQueryBuilder.java | 40 -- .../admin/service/SearchResultBuilder.java | 70 -- .../admin/AdminSearchResultBuilder.java | 60 -- .../CreateAdminAgencyRelationService.java | 4 +- .../admin/search/AdminFilterService.java | 118 ++-- .../admin/search/RetrieveAdminService.java | 5 +- .../querybuilder/AdminFilterQueryBuilder.java | 49 -- .../agency/ConsultantAgencyAdminService.java | 3 +- .../ConsultantAdminFilterService.java | 126 ++-- ...nsultantAdminFilterTenantAwareService.java | 63 -- .../consultant/ConsultantAdminService.java | 2 +- .../consultant/ConsultantReindexer.java | 21 - .../ConsultantSearchResultBuilder.java | 78 --- ...onsultantAgencyRelationCreatorService.java | 11 +- ...CreateConsultantAgencyDTOInputAdapter.java | 2 +- .../ConsultantFilterQueryBuilder.java | 70 -- .../update/ConsultantUpdateService.java | 2 +- .../validation/UserAccountInputValidator.java | 2 +- .../cob/userservice/api/config/AppConfig.java | 23 +- .../api/config/AppointmentConfig.java | 6 +- .../api/config/BeanAwareSpringLiquibase.java | 4 +- .../api/config/CacheManagerConfig.java | 9 +- .../config/GlobalMethodSecurityConfig.java | 6 +- .../api/config/LiquibaseConfig.java | 2 +- .../userservice/api/config/SwaggerConfig.java | 2 +- .../api/config/VideoChatConfig.java | 2 +- .../AgencyServiceApiClientConfig.java | 4 +- .../ApplicationSettingsApiClient.java | 5 +- .../config/apiclient/TenantServiceHelper.java | 5 +- .../apiclient/TopicServiceApiClient.java | 5 +- .../api/config/auth/IdentityConfig.java | 6 +- .../RoleAuthorizationAuthorityMapper.java | 5 +- .../api/config/auth/SecurityConfig.java | 447 ++++++------ .../api/config/auth/TechnicalUserConfig.java | 2 +- .../userservice/api/config/auth/UserRole.java | 6 +- .../service/ConversationListResolver.java | 2 +- .../api/exception/CreateEnquiryException.java | 3 +- .../api/exception/CustomCryptoException.java | 4 +- .../exception/EmailNotificationException.java | 4 +- .../api/exception/HelperException.java | 4 +- .../api/exception/ImportException.java | 4 +- .../MessageHasAlreadyBeenSavedException.java | 4 +- .../MissingConsultingTypeException.java | 4 +- .../NewMessageNotificationException.java | 4 +- .../api/exception/NoMasterKeyException.java | 4 +- .../api/exception/NoUserSessionException.java | 4 +- .../UpdateFeedbackGroupIdException.java | 4 +- .../api/exception/UpdateSessionException.java | 4 +- .../httpresponses/BadRequestException.java | 4 +- .../httpresponses/ConflictException.java | 3 +- .../CreateEnquiryMessageException.java | 4 +- .../httpresponses/ForbiddenException.java | 5 +- .../httpresponses/NoContentException.java | 3 +- .../httpresponses/NotFoundException.java | 11 +- .../RocketChatUnauthorizedException.java | 4 +- .../exception/keycloak/KeycloakException.java | 4 +- .../RocketChatAddConsultantsException.java | 3 +- .../RocketChatAddSystemUserException.java | 3 +- .../RocketChatAddUserToGroupException.java | 4 +- .../RocketChatCreateGroupException.java | 4 +- .../RocketChatGetGroupMembersException.java | 4 +- .../RocketChatGetGroupsListAllException.java | 4 +- .../RocketChatGetUserIdException.java | 4 +- .../RocketChatLeaveFromGroupException.java | 4 +- .../rocketchat/RocketChatLoginException.java | 4 +- ...tChatPostFurtherStepsMessageException.java | 3 +- .../RocketChatPostMessageException.java | 3 +- ...RocketChatPostWelcomeMessageException.java | 3 +- ...cketChatRemoveSystemMessagesException.java | 4 +- ...ocketChatRemoveUserFromGroupException.java | 4 +- ...RocketChatUserNotInitializedException.java | 4 +- .../facade/CreateEnquiryMessageFacade.java | 10 +- .../api/facade/CreateUserFacade.java | 4 +- .../api/facade/JoinAndLeaveChatFacade.java | 2 +- .../api/facade/RocketChatFacade.java | 23 +- .../assignsession/AssignEnquiryFacade.java | 2 +- .../assignsession/AssignSessionFacade.java | 4 +- .../UnauthorizedMembersProvider.java | 2 +- .../facade/sessionlist/SessionListFacade.java | 20 +- .../userdata/ConsultantDataProvider.java | 6 +- .../api/helper/AgencyVerifier.java | 5 +- .../api/helper/EmptyObjectSerializer.java | 3 +- .../cob/userservice/api/helper/Helper.java | 2 +- .../api/helper/LatestMessageParseUtil.java | 37 + .../api/helper/SessionListAnalyser.java | 2 +- .../consultingtype/ConsultingTypeManager.java | 2 +- .../cob/userservice/api/model/Admin.java | 35 +- .../userservice/api/model/AdminAgency.java | 22 +- .../userservice/api/model/Appointment.java | 24 +- .../cob/userservice/api/model/Chat.java | 28 +- .../cob/userservice/api/model/ChatAgency.java | 18 +- .../cob/userservice/api/model/Consultant.java | 57 +- .../api/model/ConsultantAgency.java | 30 +- .../api/model/ConsultantMobileToken.java | 20 +- .../cob/userservice/api/model/Language.java | 22 +- .../cob/userservice/api/model/Session.java | 32 +- .../userservice/api/model/SessionData.java | 20 +- .../userservice/api/model/SessionTopic.java | 18 +- .../cob/userservice/api/model/User.java | 32 +- .../cob/userservice/api/model/UserAgency.java | 20 +- .../cob/userservice/api/model/UserChat.java | 20 +- .../api/model/UserMobileToken.java | 20 +- .../api/port/out/IdentityClientConfig.java | 2 +- .../api/scheduler/ScheduledLogger.java | 3 +- .../api/service/AskerImportService.java | 18 +- .../userservice/api/service/ChatService.java | 9 +- .../api/service/ConsultantImportService.java | 4 +- .../service/TenantHibernateInterceptor.java | 13 +- .../service/archive/SessionDeleteService.java | 2 +- .../AssignEnquiryEmailSupplier.java | 2 +- .../NewDirectEnquiryEmailSupplier.java | 2 +- .../NewEnquiryEmailSupplier.java | 2 +- .../NewMessageEmailSupplier.java | 2 +- ...ReassignmentConfirmationEmailSupplier.java | 2 +- .../ReassignmentRequestEmailSupplier.java | 2 +- .../httpheader/HttpHeadersResolver.java | 2 +- .../LiveEventNotificationService.java | 30 +- .../message/MessageServiceProvider.java | 10 +- .../security/AuthorisationService.java | 49 ++ .../service/security/JwtAuthConverter.java | 60 ++ .../security/JwtAuthConverterProperties.java | 16 + .../api/service/session/SessionService.java | 14 +- .../ConsultantSessionListService.java | 8 +- .../service/statistics/StatisticsService.java | 2 +- .../api/service/user/UserAccountService.java | 2 +- .../user/validation/UserAccountValidator.java | 2 +- .../api/tenant/AccessTokenTenantResolver.java | 2 +- .../tenant/CustomHeaderTenantResolver.java | 2 +- ...tenancyWithSingleDomainTenantResolver.java | 2 +- .../api/tenant/SubdomainTenantResolver.java | 2 +- ...chnicalOrSuperAdminUserTenantResolver.java | 2 +- .../userservice/api/tenant/TenantAspect.java | 4 +- .../api/tenant/TenantResolver.java | 2 +- .../api/tenant/TenantResolverService.java | 2 +- .../DeactivateAnonymousUserService.java | 2 +- .../service/DeactivateGroupChatService.java | 2 +- .../service/DeleteUserAnonymousService.java | 2 +- .../keycloak/KeycloakServiceTest.java | 4 +- .../web/controller/ActuatorControllerIT.java | 2 +- .../AppointmentControllerAuthorizationIT.java | 2 +- .../AppointmentControllerE2EIT.java | 2 +- ...ConversationControllerAuthorizationIT.java | 2 +- .../UserAdminControllerAuthorizationIT.java | 29 +- .../controller/UserAdminControllerE2EIT.java | 2 +- .../web/controller/UserAdminControllerIT.java | 14 +- .../controller/UserController2faE2EIT.java | 2 +- .../UserControllerAuthorizationIT.java | 2 +- .../controller/UserControllerChatE2EIT.java | 4 +- .../UserControllerConsultantE2EIT.java | 6 +- .../web/controller/UserControllerIT.java | 10 +- .../UserControllerSessionE2EIT.java | 4 +- .../interceptor/HttpTenantFilterTest.java | 8 +- .../interceptor/StatelessCsrfFilterTest.java | 10 +- .../admin/facade/ConsultantAdminFacadeIT.java | 2 +- ...tantAdminFilterTenantAwareServiceTest.java | 2 +- .../consultant/ConsultantAdminServiceIT.java | 4 +- .../ConsultantAdminServiceTest.java | 5 +- .../UserAccountInputValidatorTest.java | 4 +- .../AnonymousUsernameRegistryTest.java | 3 - .../api/config/auth/IdentityConfigTest.java | 6 +- .../api/facade/AssignChatFacadeTest.java | 5 +- .../CreateEnquiryMessageFacadeTest.java | 2 +- .../AssignEnquiryFacadeTest.java | 2 +- .../AssignSessionFacadeTest.java | 2 +- .../api/port/out/ConsultantRepositoryIT.java | 4 +- .../service/ConsultingTypeServiceTest.java | 2 +- .../api/service/session/SessionServiceIT.java | 2 +- .../tenant/AccessTokenTenantResolverTest.java | 2 +- .../CustomHeaderTenantResolverTest.java | 2 +- ...ncyWithSingleDomainTenantResolverTest.java | 2 +- .../tenant/SubdomainTenantResolverTest.java | 2 +- .../TechnicalUserTenantResolverTest.java | 2 +- .../api/tenant/TenantResolverServiceTest.java | 2 +- .../testConfig/ApiControllerTestConfig.java | 4 +- .../ConsultingTypeManagerTestConfig.java | 2 +- .../api/testConfig/KeycloakTestConfig.java | 2 +- .../api/testConfig/RabbitMqTestConfig.java | 2 +- .../api/testConfig/RocketChatTestConfig.java | 2 +- 224 files changed, 2031 insertions(+), 1659 deletions(-) create mode 100644 pom2.xml delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/FilterQueryBuilder.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/admin/AdminSearchResultBuilder.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/querybuilder/AdminFilterQueryBuilder.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareService.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantReindexer.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java delete mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/querybuilder/ConsultantFilterQueryBuilder.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/service/security/AuthorisationService.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverter.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverterProperties.java diff --git a/.github/workflows/admin-api-documentation.yml b/.github/workflows/admin-api-documentation.yml index ea0043639..3a7c4c511 100644 --- a/.github/workflows/admin-api-documentation.yml +++ b/.github/workflows/admin-api-documentation.yml @@ -20,7 +20,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17 java-package: jdk architecture: x64 diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index 48a8b7058..f7f4d3c25 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -28,7 +28,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17 java-package: jdk architecture: x64 diff --git a/.github/workflows/feature-branch.yml b/.github/workflows/feature-branch.yml index 59b01a4f6..b4082e7cf 100644 --- a/.github/workflows/feature-branch.yml +++ b/.github/workflows/feature-branch.yml @@ -19,7 +19,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17 java-package: jdk architecture: x64 diff --git a/api/appointmentservice.yaml b/api/appointmentservice.yaml index d13e45a77..08a65ed93 100644 --- a/api/appointmentservice.yaml +++ b/api/appointmentservice.yaml @@ -279,3 +279,18 @@ components: example: fR2Rz7dmWmHdXE8uz t: type: string + + LanguageCode: + type: string + description: ISO 639-1 code + enum: [ + aa, ab, ae, af, ak, am, an, ar, as, av, ay, az, ba, be, bg, bh, bi, bm, bn, bo, br, + bs, ca, ce, ch, co, cr, cs, cu, cv, cy, da, de, dv, dz, ee, el, en, eo, es, et, eu, + fa, ff, fi, fj, fo, fr, fy, ga, gd, gl, gn, gu, gv, ha, he, hi, ho, hr, ht, hu, hy, + hz, ia, id, ie, ig, ii, ik, io, is, it, iu, ja, jv, ka, kg, ki, kj, kk, kl, km, kn, + ko, kr, ks, ku, kv, kw, ky, la, lb, lg, li, ln, lo, lt, lu, lv, mg, mh, mi, mk, ml, + mn, mr, ms, mt, my, na, nb, nd, ne, ng, nl, nn, no, nr, nv, ny, oc, oj, om, or, os, + pa, pi, pl, ps, pt, qu, rm, rn, ro, ru, rw, sa, sc, sd, se, sg, si, sk, sl, sm, sn, + so, sq, sr, ss, st, su, sv, sw, ta, te, tg, th, ti, tk, tl, tn, to, tr, ts, tt, tw, + ty, ug, uk, ur, uz, ve, vi, vo, wa, wo, xh, yi, yo, za, zh, zu + ] diff --git a/pom.xml b/pom.xml index 337733ecf..f08f213f0 100644 --- a/pom.xml +++ b/pom.xml @@ -16,14 +16,14 @@ org.springframework.boot spring-boot-starter-parent - 2.7.18 + 3.0.13 UTF-8 UTF-8 - 11 + 17 false false 17.0.0 @@ -41,24 +41,31 @@ 1.7 4.8.0 2.1.1 - 2.7.18 - 5.7.12 - 5.3.35 - 5.3.35 - 5.3.35 + 3.0.13 + 5.7.14 + 6.0.23 + 6.0.23 + 6.0.23 2.4.7 2.10.0 - 5.3.35 + 6.0.23 2.10.9.2 1.17.6 + 7.10.0 + 17 + 17 + + javax.ws.rs + javax.ws.rs-api + 2.1.1 + org.springframework.boot spring-boot-starter-web - ${spring-boot-starter-web.version} org.springframework.boot @@ -67,7 +74,7 @@ org.springframework spring-web - 5.3.35 + 6.0.23 org.springframework.boot @@ -101,7 +108,10 @@ org.springframework.security spring-security-core - ${spring-security-core.version} + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server org.springframework @@ -133,23 +143,27 @@ net.minidev json-smart - ${json-smart.version} - org.hibernate - hibernate-search-orm - 5.11.12.Final + org.hibernate.search + hibernate-search-mapper-orm + 6.1.7.Final org.openapitools openapi-generator-maven-plugin - 5.3.0 + ${openapi-generator-maven-plugin.version} provided + + io.swagger.core.v3 + swagger-annotations + 2.2.15 + org.openapitools jackson-databind-nullable @@ -172,8 +186,8 @@ ${springfox.version} - javax.validation - validation-api + jakarta.validation + jakarta.validation-api @@ -193,9 +207,8 @@ ${keycloak.version} - javax.ws.rs - javax.ws.rs-api - ${javax.ws.rs-api.version} + jakarta.ws.rs + jakarta.ws.rs-api @@ -204,6 +217,11 @@ lombok true + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.1.0 + com.github.jknack @@ -257,17 +275,14 @@ org.apache.logging.log4j log4j-core - ${log4j.version} org.apache.logging.log4j log4j-api - ${log4j.version} org.apache.logging.log4j log4j-to-slf4j - ${log4j.version} net.logstash.logback @@ -327,7 +342,6 @@ com.h2database h2 test - 1.4.200 org.jeasy @@ -381,14 +395,6 @@ byte-buddy 1.14.15 - - - - powermock-api-mockito2 - org.powermock - test - ${powermock.version} - org.reflections reflections @@ -492,17 +498,17 @@ org.openrewrite.maven rewrite-maven-plugin - 5.30.0 + 5.46.2 - org.openrewrite.java.spring.boot2.UpgradeSpringBoot_2_7 + org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_0 org.openrewrite.recipe rewrite-spring - 5.9.0 + 5.24.1 @@ -531,7 +537,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.1 + ${openapi-generator-maven-plugin.version} @@ -539,13 +545,17 @@ ${project.basedir}/api/userservice.yaml + ${project.basedir}/api/.openapi-generator-ignore spring ${adapters.web.generated.path}.controller ${adapters.web.dto.path} true + true / + true + true target/generated-sources @@ -602,6 +612,7 @@ / true java8 + true target/generated-sources @@ -623,6 +634,7 @@ / resttemplate java8 + true ${project.basedir}/services/applicationsettingsservice.yaml java @@ -646,6 +658,7 @@ true / + true ${project.basedir}/api/useradminservice.yaml spring @@ -669,6 +682,7 @@ true / + true ${project.basedir}/api/userstatisticsservice.yaml spring @@ -689,6 +703,7 @@ true / + true ${project.basedir}/api/conversationservice.yaml spring @@ -718,6 +733,7 @@ + true ${project.basedir}/api/useradminservice.yaml markdown @@ -742,6 +758,7 @@ native true java8 + true ${project.basedir}/services/liveservice.yaml java @@ -763,6 +780,7 @@ / resttemplate java8 + true ${project.basedir}/services/consultingtypeservice.yaml java @@ -794,6 +812,7 @@ / resttemplate java8 + true ${project.basedir}/services/agencyadminservice.yaml java @@ -820,6 +839,7 @@ / resttemplate java8 + true ${project.basedir}/services/agencyservice.yaml java @@ -846,6 +866,7 @@ / resttemplate java8 + true ${project.basedir}/services/messageservice.yaml java @@ -871,6 +892,7 @@ / resttemplate java8 + true ${project.basedir}/services/mailservice.yaml java @@ -892,6 +914,7 @@ / resttemplate java8 + true ${project.basedir}/services/statisticsservice.yaml java @@ -914,6 +937,7 @@ / resttemplate java8 + true ${project.basedir}/services/tenantservice.yaml java @@ -939,6 +963,7 @@ / resttemplate java8 + true ${project.basedir}/services/tenantadminservice.yaml java @@ -964,6 +989,7 @@ / resttemplate java8 + true ${project.basedir}/services/topicservice.yaml java @@ -989,6 +1015,7 @@ / resttemplate java8 + true ${project.basedir}/services/appointmentService.yaml java @@ -1012,6 +1039,7 @@ true / + true ${project.basedir}/services/keycloakextension.yaml false @@ -1026,11 +1054,35 @@ + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + + + process-sources + + + + + + + + + + + + + + run + + + + org.liquibase liquibase-maven-plugin - ${liquibase-maven-plugin.version} src/main/resources/liquibase.properties diff --git a/pom2.xml b/pom2.xml new file mode 100644 index 000000000..3acb98f67 --- /dev/null +++ b/pom2.xml @@ -0,0 +1,643 @@ + + + 4.0.0 + + Caritas Online Beratung: AgencyService + + de.caritas.cob + agencyservice + 0.0.1-SNAPSHOT + jar + + AgencyService + + + org.springframework.boot + spring-boot-starter-parent + 3.3.6 + + + + + UTF-8 + UTF-8 + 17 + 17.0.0 + + 2.17.1 + 6.6.0 + 0.2.3 + 2.1.1 + 3.11 + 4.23.2 + 1.4.200 + 2.10.6 + 5.0.0 + 3.0.6 + 4.23.2 + 3.0.0 + 6.3.4 + 2.9.2 + 2.10.0 + 3.0.1 + 17 + 17 + 6.1.1.Final + 3.0.0 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-cache + + + org.springframework.boot + spring-boot-starter-hateoas + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter-freemarker + + + org.springframework.security + spring-security-web + + + org.springframework.security + spring-security-config + + + org.springframework.security + spring-security-core + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + org.openapitools + openapi-generator-maven-plugin + ${openapi.generator.maven.version} + provided + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable.version} + + + org.codehaus.plexus + plexus-utils + 3.3.0 + + + io.swagger.parser.v3 + swagger-parser + 2.1.15 + + + + org.sonatype.plexus + plexus-build-api + 0.0.7 + provided + + + org.codehaus.plexus + plexus-utils + + + + + + + org.keycloak + keycloak-spring-security-adapter + ${keycloak.version} + + + org.keycloak + keycloak-spring-boot-starter + ${keycloak.version} + + + org.keycloak + keycloak-admin-client + ${keycloak.version} + + + jakarta.ws.rs + jakarta.ws.rs-api + + + + + org.projectlombok + lombok + true + + + + + + org.apache.commons + commons-lang3 + + + + com.github.jknack + handlebars + 4.3.1 + + + + + org.liquibase + liquibase-maven-plugin + ${liquibase-maven-plugin.version} + + + org.liquibase + liquibase-core + + + + + + org.liquibase + liquibase-core + + + + + org.apache.httpcomponents.client5 + httpclient5 + + + + net.sf.ehcache + ehcache + 2.10.9.2 + + + com.fasterxml.jackson.core + jackson-databind + + + + + + + org.mariadb.jdbc + mariadb-java-client + + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-api + + + org.apache.logging.log4j + log4j-to-slf4j + + + + + + org.jeasy + easy-random-core + ${easy-random-core.version} + test + + + org.yaml + snakeyaml + + + + + + + + com.h2database + h2 + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + com.c4-soft.springaddons + spring-security-oauth2-test-webmvc-addons + ${spring-security-oauth2-test-webmvc-addons.version} + test + + + + + ${project.name} + + + src/main/resources + true + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + org.openapitools + openapi-generator-maven-plugin + ${openapi.generator.maven.version} + + + agency-service + + generate + + + + true + / + true + + ${project.basedir}/api/agencyservice.yaml + spring + ${project.groupId}.${project.artifactId}.generated.api.controller + + ${project.groupId}.${project.artifactId}.api.model + true + target/generated-sources + + + + agency-admin-service + + generate + + + + true + / + true + + ${project.basedir}/api/agencyadminservice.yaml + spring + ${project.groupId}.${project.artifactId}.generated.api.admin.controller + + ${project.groupId}.${project.artifactId}.api.model + true + target/generated-sources + + + + + agency-admin-service-markdown + + generate + + + + + ${project.basedir}/api/agencyadminservice.yaml + markdown + target/generated-sources/markdown/agencyservice + ./ + model + false + false + false + + + + + user-admin-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + true + + ${project.basedir}/services/useradminservice.yaml + java + true + false + false + ${project.groupId}.${project.artifactId}.useradminservice.generated.web + + + ${project.groupId}.${project.artifactId}.useradminservice.generated.web.model + + + + + consulting-type-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + true + + ${project.basedir}/services/consultingtypeservice.yaml + java + true + false + false + + ${project.groupId}.${project.artifactId}.consultingtypeservice.generated.web + + + ${project.groupId}.${project.artifactId}.consultingtypeservice.generated.web.model + + + + + application-settings-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + true + + ${project.basedir}/services/applicationsettingsservice.yml + java + true + false + false + + ${project.groupId}.${project.artifactId}.applicationsettingsservice.generated.web + + + ${project.groupId}.${project.artifactId}.applicationsettingsservice.generated.web.model + + + + + tenant-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + true + + ${project.basedir}/services/tenantservice.yaml + java + true + false + false + + ${project.groupId}.${project.artifactId}.tenantservice.generated.web + + + ${project.groupId}.${project.artifactId}.tenantservice.generated.web.model + + + OffsetDateTime=LocalDateTime + + + java.time.OffsetDateTime=java.time.LocalDateTime + + + + + topic-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + + ${project.basedir}/services/topicservice.yaml + java + true + false + false + + ${project.groupId}.${project.artifactId}.topicservice.generated.web + + + ${project.groupId}.${project.artifactId}.topicservice.generated.web.model + + + + + appointment-service-client-model + generate-sources + + generate + + + + / + resttemplate + java8 + + ${project.basedir}/services/appointmentService.yaml + java + true + false + false + + ${project.groupId}.${project.artifactId}.appointmentservice.generated.web + + + ${project.groupId}.${project.artifactId}.appointmentservice.generated.web.model + + + + + + + + org.liquibase + liquibase-maven-plugin + + src/main/resources/liquibase.properties + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.6.0 + + + validate + validate + + google_checks_light.xml + true + true + true + true + warning + true + + + check + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + --enable-preview + ${java.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + + + true + --enable-preview + + + + unit-tests + test + + test + + + false + + **/*Test.java + + + + + integration-tests + integration-test + + test + + + false + + **/*IT.* + + + + + + + org.openrewrite.maven + rewrite-maven-plugin + 5.46.1 + + true + + org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 + + + + + org.openrewrite.recipe + rewrite-spring + 5.24.1 + + + + + + + + local + + local + + + true + + + + dev + + dev + + + + prod + + prod + + + + + diff --git a/src/main/java/de/caritas/cob/userservice/api/AccountManager.java b/src/main/java/de/caritas/cob/userservice/api/AccountManager.java index cf945c646..22bac012e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/AccountManager.java +++ b/src/main/java/de/caritas/cob/userservice/api/AccountManager.java @@ -195,8 +195,7 @@ private Map findByDbConsultant(Consultant dbConsultant) { private Runnable throwPersistenceConflict(String dbUserId, String chatUserId) { var message = - String.format( - "User (%s) found in database but not in Rocket.Chat (%s)", dbUserId, chatUserId); + "User (%s) found in database but not in Rocket.Chat (%s)".formatted(dbUserId, chatUserId); return () -> { throw new InternalServerErrorException(message); diff --git a/src/main/java/de/caritas/cob/userservice/api/UserServiceApplication.java b/src/main/java/de/caritas/cob/userservice/api/UserServiceApplication.java index d8b519f59..f95cf4ec0 100644 --- a/src/main/java/de/caritas/cob/userservice/api/UserServiceApplication.java +++ b/src/main/java/de/caritas/cob/userservice/api/UserServiceApplication.java @@ -36,7 +36,7 @@ public static void main(String[] args) { } @Bean - public Executor taskExecutor() { + Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); /* * This will create 10 threads at the time of initialization. If all 10 threads are busy and new diff --git a/src/main/java/de/caritas/cob/userservice/api/actions/registry/ActionContainer.java b/src/main/java/de/caritas/cob/userservice/api/actions/registry/ActionContainer.java index 8078f3c43..a434707ef 100644 --- a/src/main/java/de/caritas/cob/userservice/api/actions/registry/ActionContainer.java +++ b/src/main/java/de/caritas/cob/userservice/api/actions/registry/ActionContainer.java @@ -32,9 +32,8 @@ public ActionContainer addActionToExecute(Class> a .orElseThrow( () -> new NoSuchElementException( - String.format( - "ActionCommand class %s does not exist or is not implemented yet", - actionToAdd.getSimpleName())))); + "ActionCommand class %s does not exist or is not implemented yet" + .formatted(actionToAdd.getSimpleName())))); return this; } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java index 7053319bc..565438271 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java @@ -25,6 +25,7 @@ import de.caritas.cob.userservice.api.port.out.IdentityClient; import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; +import jakarta.ws.rs.BadRequestException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; @@ -34,7 +35,6 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Stream; -import javax.ws.rs.BadRequestException; import javax.ws.rs.core.Response; import lombok.NonNull; import lombok.RequiredArgsConstructor; @@ -154,8 +154,7 @@ public KeycloakLoginResponseDTO loginUser(final String userName, final String pa } catch (RestClientResponseException exception) { throw new BadRequestException( - String.format( - "Could not log in user %s into Keycloak: %s", userName, exception.getMessage()), + "Could not log in user %s into Keycloak: %s".formatted(userName, exception.getMessage()), exception); } } @@ -360,8 +359,8 @@ public KeycloakCreateUserResponseDTO createKeycloakUser( handleCreateKeycloakUserError(response); } throw new InternalServerErrorException( - String.format( - "Could not create Keycloak account for: %s %nKeycloak error: %s", user, keycloakError)); + "Could not create Keycloak account for: %s %nKeycloak error: %s" + .formatted(user, keycloakError)); } private void handleCreateKeycloakUserError(Response response) { @@ -669,12 +668,11 @@ public boolean userHasAuthority(String userId, String authority) { try { return getUserRoles(userId).stream() .map(role -> UserRole.getRoleByValue(role.getName())) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(Optional::stream) .map(Authority::getAuthoritiesByUserRole) .anyMatch(currentAuthority -> currentAuthority.contains(authority)); } catch (Exception ex) { - var error = String.format("Could not get roles for user id %s", userId); + var error = "Could not get roles for user id %s".formatted(userId); log.error("Keycloak error: " + error, ex); throw new KeycloakException(error); } @@ -691,12 +689,11 @@ public boolean userHasRole(String userId, String userRole) { try { return getUserRoles(userId).stream() .map(this::toUserRole) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(Optional::stream) .map(UserRole::getValue) .anyMatch(userRole::equals); } catch (Exception ex) { - var error = String.format("Could not get roles for user id %s", userId); + var error = "Could not get roles for user id %s".formatted(userId); log.error("Keycloak error: " + error, ex); throw new KeycloakException(error); } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java index 18221778a..fd2176efa 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java @@ -4,10 +4,10 @@ import de.caritas.cob.userservice.api.exception.keycloak.KeycloakException; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; import lombok.Data; import org.hibernate.validator.constraints.URL; import org.keycloak.KeycloakSecurityContext; @@ -34,25 +34,25 @@ public class KeycloakConfig { @Bean("keycloakRestTemplate") - public RestTemplate keycloakRestTemplate(RestTemplateBuilder restTemplateBuilder) { + RestTemplate keycloakRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.build(); } @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public KeycloakAuthenticationToken keycloakAuthenticationToken(HttpServletRequest request) { + KeycloakAuthenticationToken keycloakAuthenticationToken(HttpServletRequest request) { return (KeycloakAuthenticationToken) request.getUserPrincipal(); } @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public KeycloakSecurityContext keycloakSecurityContext(KeycloakAuthenticationToken token) { + KeycloakSecurityContext keycloakSecurityContext(KeycloakAuthenticationToken token) { return token.getAccount().getKeycloakSecurityContext(); } @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public AuthenticatedUser authenticatedUser(HttpServletRequest request) { + AuthenticatedUser authenticatedUser(HttpServletRequest request) { var userPrincipal = request.getUserPrincipal(); var authenticatedUser = new AuthenticatedUser(); @@ -83,7 +83,7 @@ public AuthenticatedUser authenticatedUser(HttpServletRequest request) { } @Bean - public Keycloak keycloak() { + Keycloak keycloak() { return KeycloakBuilder.builder() .serverUrl(authServerUrl) .realm(realm) @@ -98,7 +98,7 @@ public Keycloak keycloak() { * application properties. */ @Bean - public KeycloakConfigResolver keyCloakConfigResolver() { + KeycloakConfigResolver keyCloakConfigResolver() { return new KeycloakSpringBootConfigResolver(); } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakCustomConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakCustomConfig.java index 298319b6e..5faf5607e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakCustomConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakCustomConfig.java @@ -1,6 +1,6 @@ package de.caritas.cob.userservice.api.adapters.keycloak.config; -import javax.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotBlank; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatCredentialsProvider.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatCredentialsProvider.java index 9d834c518..b22c4c27a 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatCredentialsProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatCredentialsProvider.java @@ -206,7 +206,7 @@ public ResponseEntity loginUser(String username, String passwo return restTemplate.postForEntity(url, request, LoginResponseDTO.class); } catch (Exception ex) { throw new RocketChatLoginException( - String.format("Could not login user (%s) in Rocket.Chat", username)); + "Could not login user (%s) in Rocket.Chat".formatted(username)); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java index 295c9f8c1..9679655ac 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/RocketChatService.java @@ -56,6 +56,7 @@ import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatUserNotInitializedException; import de.caritas.cob.userservice.api.port.out.MessageClient; import de.caritas.cob.userservice.api.service.LogService; +import jakarta.annotation.PostConstruct; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; @@ -64,7 +65,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import javax.annotation.PostConstruct; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; @@ -353,7 +353,7 @@ public Optional createPrivateGroup( if (!isCreateGroupResponseSuccess(response)) { throw new RocketChatCreateGroupException( - String.format("Rocket.Chat group with name %s could not be created", name)); + "Rocket.Chat group with name %s could not be created".formatted(name)); } return Optional.ofNullable(response); @@ -528,7 +528,7 @@ public ResponseEntity loginUserFirstTime(String username, Stri username, ex); throw new RocketChatLoginException( - String.format("Could not login user (%s) in Rocket.Chat for the first time", username)); + "Could not login user (%s) in Rocket.Chat for the first time".formatted(username)); } } @@ -586,13 +586,12 @@ public void addUserToGroup(String rcUserId, String rcGroupId) rcGroupId, ex); throw new RocketChatAddUserToGroupException( - String.format( - "Could not add user %s to Rocket.Chat group with id %s", rcUserId, rcGroupId)); + "Could not add user %s to Rocket.Chat group with id %s".formatted(rcUserId, rcGroupId)); } if (nonNull(response) && !response.isSuccess()) { var error = "Could not add user %s to Rocket.Chat group with id %s"; - throw new RocketChatAddUserToGroupException(String.format(error, rcUserId, rcGroupId)); + throw new RocketChatAddUserToGroupException(error.formatted(rcUserId, rcGroupId)); } } @@ -631,13 +630,13 @@ public void leaveFromGroupAsTechnicalUser(String rcGroupId) rcGroupId, ex); throw new RocketChatLeaveFromGroupException( - String.format( - "Could not leave as technical user from Rocket.Chat group with id %s", rcGroupId)); + "Could not leave as technical user from Rocket.Chat group with id %s" + .formatted(rcGroupId)); } if (response != null && !response.isSuccess()) { var error = "Could not leave as technical user from Rocket.Chat group with id %s"; - throw new RocketChatLeaveFromGroupException(String.format(error, rcGroupId)); + throw new RocketChatLeaveFromGroupException(error.formatted(rcGroupId)); } } @@ -668,13 +667,13 @@ public void removeUserFromGroup(String rcUserId, String rcGroupId) rcGroupId, ex); throw new RocketChatRemoveUserFromGroupException( - String.format( - "Could not remove user %s from Rocket.Chat group with id %s", rcUserId, rcGroupId)); + "Could not remove user %s from Rocket.Chat group with id %s" + .formatted(rcUserId, rcGroupId)); } if (response != null && !response.isSuccess()) { var error = "Could not remove user %s from Rocket.Chat group with id %s"; - throw new RocketChatRemoveUserFromGroupException(String.format(error, rcUserId, rcGroupId)); + throw new RocketChatRemoveUserFromGroupException(error.formatted(rcUserId, rcGroupId)); } } @@ -708,7 +707,7 @@ public List getStandardMembersOfGroup(String rcGroupId) } catch (Exception exception) { log.error("Could not get chat users. Reason: ", exception); throw new RocketChatGetGroupMembersException( - String.format("Group member list from group with id %s is empty", rcGroupId)); + "Group member list from group with id %s is empty".formatted(rcGroupId)); } Iterator groupMemberListIterator = groupMemberList.iterator(); @@ -739,7 +738,7 @@ public void removeAllStandardUsersFromGroup(String rcGroupId) if (groupMemberList.isEmpty()) { throw new RocketChatGetGroupMembersException( - String.format("Group member list from group with id %s is empty", rcGroupId)); + "Group member list from group with id %s is empty".formatted(rcGroupId)); } for (GroupMemberDTO member : groupMemberList) { @@ -814,15 +813,14 @@ public List getMembersOfGroup(String rcGroupId) } catch (Exception ex) { log.error("Could not get chat users. Reason: ", ex); throw new RocketChatGetGroupMembersException( - String.format("Could not get Rocket.Chat group" + " members for room id %s", rcGroupId), - ex); + ("Could not get Rocket.Chat group" + " members for room id %s").formatted(rcGroupId), ex); } if (response.getStatusCode() == HttpStatus.OK && nonNull(response.getBody())) { return asList(response.getBody().getMembers()); } else { var error = "Could not get Rocket.Chat group members for room id %s"; - throw new RocketChatGetGroupMembersException(String.format(error, rcGroupId)); + throw new RocketChatGetGroupMembersException(error.formatted(rcGroupId)); } } @@ -883,12 +881,12 @@ private void removeMessages( } catch (Exception ex) { log.error("Could not clean history of Rocket.Chat group id {}. Reason: ", rcGroupId, ex); throw new RocketChatRemoveSystemMessagesException( - String.format("Could not clean history of Rocket.Chat group id %s", rcGroupId)); + "Could not clean history of Rocket.Chat group id %s".formatted(rcGroupId)); } if (nonNull(response) && !response.isSuccess()) { throw new RocketChatRemoveSystemMessagesException( - String.format("Could not clean history of Rocket.Chat group id %s", rcGroupId)); + "Could not clean history of Rocket.Chat group id %s".formatted(rcGroupId)); } } @@ -1006,7 +1004,7 @@ public UserInfoResponseDTO getUserInfo(String rcUserId) { } catch (RestClientResponseException | RocketChatUserNotInitializedException ex) { throw new InternalServerErrorException( - String.format("Could not get Rocket.Chat user info of user id %s", rcUserId), + "Could not get Rocket.Chat user info of user id %s".formatted(rcUserId), ex, LogService::logRocketChatError); } @@ -1168,9 +1166,9 @@ public List fetchAllInactivePrivateGroupsSinceGivenDate( LocalDateTime dateTimeSinceInactive) throws RocketChatGetGroupsListAllException { String filter = - String.format( - "{\"lm\": {\"$lt\": {\"$date\": \"%s\"}}, \"$and\": [{\"t\": \"p\"}]}", - dateTimeSinceInactive.format(DateTimeFormatter.ofPattern(RC_DATE_TIME_PATTERN))); + "{\"lm\": {\"$lt\": {\"$date\": \"%s\"}}, \"$and\": [{\"t\": \"p\"}]}" + .formatted( + dateTimeSinceInactive.format(DateTimeFormatter.ofPattern(RC_DATE_TIME_PATTERN))); return getGroupsListAll(filter); } @@ -1302,8 +1300,7 @@ private String extractUserIdFromResponse(RocketChatUserDTO[] users) return users[0].getId(); } - throw new RocketChatGetUserIdException( - String.format("Found %s users by username", users.length)); + throw new RocketChatGetUserIdException("Found %s users by username".formatted(users.length)); } private String buildUsersListGetUrl() { @@ -1312,7 +1309,7 @@ private String buildUsersListGetUrl() { } private String buildUsernameQuery(String username) { - return String.format("{\"username\":{\"$eq\":\"%s\"}}", username.toLowerCase()); + return "{\"username\":{\"$eq\":\"%s\"}}".formatted(username.toLowerCase()); } public boolean saveRoomSettings(String chatId, boolean encrypted) { diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/config/RocketChatConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/config/RocketChatConfig.java index e01b04625..2941b08d4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/config/RocketChatConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/config/RocketChatConfig.java @@ -10,10 +10,10 @@ import com.mongodb.client.MongoClients; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatCredentials; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.NotBlank; import java.util.Arrays; -import javax.servlet.http.HttpServletRequest; -import javax.validation.constraints.AssertTrue; -import javax.validation.constraints.NotBlank; import lombok.Data; import org.apache.logging.log4j.core.util.CronExpression; import org.hibernate.validator.constraints.URL; @@ -49,7 +49,7 @@ public class RocketChatConfig { @NotBlank private String mongoUrl; @Bean("rocketChatRestTemplate") - public RestTemplate rocketChatRestTemplate(RestTemplateBuilder restTemplateBuilder) { + RestTemplate rocketChatRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder .defaultHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON.toString()) .build(); @@ -57,7 +57,7 @@ public RestTemplate rocketChatRestTemplate(RestTemplateBuilder restTemplateBuild @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - public RocketChatCredentials rocketChatCredentials() { + RocketChatCredentials rocketChatCredentials() { var rcUserId = httpServletRequest.getHeader("RCUserId"); return RocketChatCredentials.builder() @@ -67,7 +67,7 @@ public RocketChatCredentials rocketChatCredentials() { } @Bean - public MongoClient mongoClient() { + MongoClient mongoClient() { var connectionString = new ConnectionString(mongoUrl); var settings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/AttachmentDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/AttachmentDTO.java index 20fd2cbc8..b04e55f67 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/AttachmentDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/AttachmentDTO.java @@ -1,7 +1,7 @@ package de.caritas.cob.userservice.api.adapters.rocketchat.dto.message.attachment; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -14,7 +14,7 @@ @NoArgsConstructor public class AttachmentDTO { - @ApiModelProperty(required = true, example = "/9j/2wBDAAYEBQYFBAYGBQY", position = 2) + @Schema(required = true, example = "/9j/2wBDAAYEBQYFBAYGBQY") @JsonProperty("image_preview") private String imagePreview; } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/FileDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/FileDTO.java index 45cc50415..d063331db 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/FileDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/rocketchat/dto/message/attachment/FileDTO.java @@ -1,7 +1,7 @@ package de.caritas.cob.userservice.api.adapters.rocketchat.dto.message.attachment; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -14,13 +14,12 @@ @NoArgsConstructor public class FileDTO { - @ApiModelProperty(required = true, example = "filename.png", position = 0) + @Schema(required = true, example = "filename.png") private String name; - @ApiModelProperty( + @Schema( required = true, - example = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - position = 1) + example = "application/vnd.openxmlformats-officedocument.wordprocessingml.document") @JsonProperty("type") private String type; } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentController.java index a48409797..0074c9b78 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentController.java @@ -24,12 +24,12 @@ import de.caritas.cob.userservice.api.service.statistics.StatisticsService; import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.generated.api.adapters.web.controller.AppointmentsApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.constraints.NotNull; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; -import javax.validation.constraints.NotNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; @@ -40,9 +40,9 @@ import org.springframework.web.bind.annotation.RestController; @Slf4j +@Tag(name = "appointment-controller") @RestController @RequiredArgsConstructor -@Api(tags = "appointment-controller") public class AppointmentController implements AppointmentsApi { private static final String APPOINTMENT_NOT_FOUND = "Appointment (%s) not found."; @@ -161,7 +161,7 @@ private String resolveConsultantId(Appointment appointment) { && appointment.getConsultantEmail() != null) { Optional consultant = consultantRepository.findByEmailAndDeleteDateIsNull(appointment.getConsultantEmail()); - if (!consultant.isPresent()) { + if (consultant.isEmpty()) { throw new BadRequestException( "Consultant doesn't exist for given email " + appointment.getConsultantEmail()); } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationController.java index 0f6b55793..b8c38d9d1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationController.java @@ -19,8 +19,8 @@ import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.port.in.Messaging; import de.caritas.cob.userservice.generated.api.conversation.controller.ConversationsApi; -import io.swagger.annotations.Api; -import javax.validation.Valid; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; @@ -31,8 +31,8 @@ /** Controller for conversation API requests. */ @RestController +@Tag(name = "conversation-controller") @RequiredArgsConstructor -@Api(tags = "conversation-controller") public class ConversationController implements ConversationsApi { private final @NonNull ConversationListResolver conversationListResolver; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyController.java index d837e62d4..80c4feb23 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyController.java @@ -2,7 +2,7 @@ import de.caritas.cob.userservice.api.service.liveevents.LiveEventNotificationService; import de.caritas.cob.userservice.generated.api.adapters.web.controller.LiveproxyApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; @@ -12,8 +12,8 @@ /** Controller to consume live events and send them to the live service. */ @RestController +@Tag(name = "live-controller") @RequiredArgsConstructor -@Api(tags = "live-controller") public class LiveProxyController implements LiveproxyApi { private final @NonNull LiveEventNotificationService liveEventNotificationService; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java index deac46cfa..21f608775 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminController.java @@ -34,13 +34,13 @@ import de.caritas.cob.userservice.api.service.appointment.AppointmentService; import de.caritas.cob.userservice.api.service.helper.EmailUrlDecoder; import de.caritas.cob.userservice.generated.api.adapters.web.controller.UseradminApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.commons.validator.routines.EmailValidator; @@ -52,8 +52,8 @@ /** Controller to handle all session admin requests. */ @RestController +@Tag(name = "admin-user-controller") @RequiredArgsConstructor -@Api(tags = "admin-user-controller") public class UserAdminController implements UseradminApi { private final @NonNull SessionAdminService sessionAdminService; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java index 4daed2a46..8c3d5950e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java @@ -100,7 +100,10 @@ import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.api.tenant.TenantContext; import de.caritas.cob.userservice.generated.api.adapters.web.controller.UsersApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; +import jakarta.ws.rs.InternalServerErrorException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Collection; @@ -109,15 +112,12 @@ import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.InternalServerErrorException; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import lombok.val; import org.apache.commons.validator.routines.EmailValidator; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -127,9 +127,9 @@ /** Controller for user api requests */ @Slf4j +@Tag(name = "user-controller") @RestController @RequiredArgsConstructor -@Api(tags = "user-controller") public class UserController implements UsersApi { private final @NotNull UserAccountService userAccountProvider; @@ -179,8 +179,8 @@ public class UserController implements UsersApi { @Override public ResponseEntity userExists(String username) { - val usernameAvailable = identityClient.isUsernameAvailable(username); - val userExists = !usernameAvailable; + final var usernameAvailable = identityClient.isUsernameAvailable(username); + final var userExists = !usernameAvailable; if (userExists) { return ResponseEntity.ok().build(); } @@ -230,7 +230,8 @@ public ResponseEntity registerNewConsultingType( createNewConsultingTypeFacade.initializeNewConsultingType( newRegistrationDto, user, rocketChatCredentials); - return new ResponseEntity<>(registrationResponse, registrationResponse.getStatus()); + return new ResponseEntity<>( + registrationResponse, (HttpStatusCode) registrationResponse.getStatus()); } /** @@ -470,9 +471,9 @@ private EmailNotificationsDTO getEmailNotifications(User user) { * * @return {@link ResponseEntity} containing {@link UserDataResponseDTO} */ - @Override - public ResponseEntity getUserData() { - UserDataResponseDTO partialUserData; + public ResponseEntity + getUserData() { + de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO partialUserData; if (authenticatedUser.isConsultant()) { var consultant = userAccountProvider.retrieveValidatedConsultant(); partialUserData = consultantDataProvider.retrieveData(consultant); @@ -878,8 +879,7 @@ public ResponseEntity removeFromSession(Long sessionId, UUID consultantId) var chatUserId = userDtoMapper.chatUserIdOf(consultantMap); if (!messenger.removeUserFromSession(chatUserId, chatId)) { var message = - String.format( - "Could not remove consultant (%s) from session (%s)", consultantId, sessionId); + "Could not remove consultant (%s) from session (%s)".formatted(consultantId, sessionId); throw new InternalServerErrorException(message); } @@ -1009,7 +1009,7 @@ public ResponseEntity startChat(@PathVariable Long chatId) { .orElseThrow( () -> new BadRequestException( - String.format("Chat with id %s not found for starting chat.", chatId))); + "Chat with id %s not found for starting chat.".formatted(chatId))); var callingConsultant = this.userAccountProvider.retrieveValidatedConsultant(); startChatFacade.startChat(chat, callingConsultant); @@ -1085,8 +1085,8 @@ public ResponseEntity stopChat(Long chatId) { .orElseThrow( () -> new BadRequestException( - String.format( - "Chat with id %s not found while trying to stop the chat.", chatId))); + "Chat with id %s not found while trying to stop the chat." + .formatted(chatId))); var callingConsultant = this.userAccountProvider.retrieveValidatedConsultant(); messenger.unbanUsersInChat(chatId, callingConsultant.getId()); diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserStatisticsController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserStatisticsController.java index e02cbdadb..92109567b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserStatisticsController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserStatisticsController.java @@ -3,7 +3,7 @@ import de.caritas.cob.userservice.api.service.statistics.SessionStatisticsService; import de.caritas.cob.userservice.api.statistics.model.SessionStatisticsResultDTO; import de.caritas.cob.userservice.generated.api.statistics.controller.UserstatisticsApi; -import io.swagger.annotations.Api; +import io.swagger.v3.oas.annotations.tags.Tag; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; @@ -12,8 +12,8 @@ /** Controller to handle all statistics requests. */ @RestController +@Tag(name = "user-statistics-controller") @RequiredArgsConstructor -@Api(tags = "user-statistics-controller") public class UserStatisticsController implements UserstatisticsApi { private final @NonNull SessionStatisticsService sessionStatisticsService; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/ApiResponseEntityExceptionHandler.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/ApiResponseEntityExceptionHandler.java index 40ead6482..a7214a0ea 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/ApiResponseEntityExceptionHandler.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/ApiResponseEntityExceptionHandler.java @@ -14,8 +14,8 @@ import de.caritas.cob.userservice.api.exception.httpresponses.RocketChatUnauthorizedException; import de.caritas.cob.userservice.api.exception.keycloak.KeycloakException; import de.caritas.cob.userservice.api.service.LogService; +import jakarta.validation.ConstraintViolationException; import java.net.UnknownHostException; -import javax.validation.ConstraintViolationException; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -26,6 +26,7 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; 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.HttpMessageNotReadableException; import org.springframework.lang.Nullable; @@ -125,9 +126,9 @@ public ResponseEntity handleBadRequest( protected ResponseEntity handleHttpMessageNotReadable( final HttpMessageNotReadableException ex, final HttpHeaders headers, - final HttpStatus status, + final HttpStatusCode status, final WebRequest request) { - log.warn(USER_SERVICE_API_LOG_PLACEHOLDER, status.getReasonPhrase(), ex.getStackTrace()); + log.warn(USER_SERVICE_API_LOG_PLACEHOLDER, status, ex.getStackTrace()); return handleExceptionInternal(null, null, headers, status, request); } @@ -142,9 +143,9 @@ protected ResponseEntity handleHttpMessageNotReadable( protected ResponseEntity handleMethodArgumentNotValid( final MethodArgumentNotValidException ex, final HttpHeaders headers, - final HttpStatus status, + final HttpStatusCode status, final WebRequest request) { - log.warn(USER_SERVICE_API_LOG_PLACEHOLDER, status.getReasonPhrase(), ex); + log.warn(USER_SERVICE_API_LOG_PLACEHOLDER, status, ex); return handleExceptionInternal(null, null, headers, status, request); } @@ -276,7 +277,7 @@ protected ResponseEntity handleExceptionInternal( @Nullable Exception ex, @Nullable Object body, HttpHeaders headers, - HttpStatus status, + HttpStatusCode status, WebRequest request) { if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { request.setAttribute("javax.servlet.error.exception", ex, 0); diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/CorrelationIdFilter.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/CorrelationIdFilter.java index 6312d2714..67fd26fd7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/CorrelationIdFilter.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/CorrelationIdFilter.java @@ -2,12 +2,12 @@ import static org.apache.commons.lang3.StringUtils.isEmpty; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.UUID; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java index 70e7a2f03..fe3e92ac2 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java @@ -3,14 +3,14 @@ import de.caritas.cob.userservice.api.admin.service.tenant.TenantService; import de.caritas.cob.userservice.api.tenant.TenantContext; import de.caritas.cob.userservice.api.tenant.TenantResolverService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilter.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilter.java index 459211023..b04f39ccc 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilter.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilter.java @@ -4,17 +4,17 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank; import de.caritas.cob.userservice.api.config.CsrfSecurityProperties; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Stream; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.security.access.AccessDeniedException; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java index e7abc41de..0d181aec4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/ChatDTO.java @@ -7,15 +7,14 @@ import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import java.time.LocalDate; import java.time.LocalTime; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -31,46 +30,46 @@ @Getter @Setter @Builder -@ApiModel(value = "Chat") +@Schema(name = "Chat") public class ChatDTO { @Size(min = CHAT_TOPIC_MIN_LENGTH, max = CHAT_TOPIC_MAX_LENGTH) @NotBlank(message = "{chat.name.notBlank}") - @ApiModelProperty(required = true, example = "Wöchentliche Drogenberatung", position = 0) + @Schema(required = true, example = "Wöchentliche Drogenberatung") @JsonProperty("topic") private String topic; @DateTimeFormat(iso = ISO.DATE) @NotNull(message = "{chat.startDate.invalid}") - @ApiModelProperty(required = true, example = "2019-10-23", position = 1) + @Schema(required = true, example = "2019-10-23") @JsonProperty("startDate") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private LocalDate startDate; @DateTimeFormat(pattern = "HH:mm") @NotNull(message = "{chat.startTime.invalid}") - @ApiModelProperty(required = true, example = "12:05", position = 2) + @Schema(required = true, example = "12:05") @JsonProperty("startTime") private LocalTime startTime; @NotNull(message = "{chat.duration.notNull}") @Min(value = CHAT_MIN_DURATION, message = "{chat.duration.invalid}") @Max(value = CHAT_MAX_DURATION, message = "{chat.duration.invalid}") - @ApiModelProperty(required = true, example = "120", position = 3) + @Schema(required = true, example = "120") @JsonProperty("duration") private int duration; @NotNull(message = "{chat.repetitive.notNull}") - @ApiModelProperty(required = true, example = "true", position = 4) + @Schema(required = true, example = "true") @JsonProperty("repetitive") private boolean repetitive; - @ApiModelProperty(required = true, example = "5", position = 5) + @Schema(required = true, example = "5") @Min(value = 0, message = "{chat.agencyId.invalid}") @JsonProperty("agencyId") private Long agencyId; - @ApiModelProperty(required = true, example = "5", position = 6) + @Schema(required = true, example = "5") @Length(max = 300, message = "{chat.hintMessage.invalid}") @JsonProperty("hintMessage") private String hintMessage; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/GroupSessionConsultantDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/GroupSessionConsultantDTO.java index 201eead55..2db9ab4a4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/GroupSessionConsultantDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/GroupSessionConsultantDTO.java @@ -4,15 +4,14 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.caritas.cob.userservice.api.adapters.web.dto.serialization.DecodeUsernameJsonSerializer; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -@ApiModel(value = "GroupSessionConsultant") +@Schema(name = "GroupSessionConsultant") @JsonInclude(Include.NON_NULL) @Builder @NoArgsConstructor @@ -21,14 +20,14 @@ @Getter public class GroupSessionConsultantDTO { - @ApiModelProperty(example = "\"Username\"") + @Schema(example = "\"Username\"") @JsonSerialize(using = DecodeUsernameJsonSerializer.class) private String username; - @ApiModelProperty(example = "\"true\"") + @Schema(example = "\"true\"") private boolean isAbsent; - @ApiModelProperty(example = "\"Bin nicht da\"") + @Schema(example = "\"Bin nicht da\"") private String absenceMessage; private String displayName; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/NewRegistrationDto.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/NewRegistrationDto.java index ebb6eb3b6..d3b752a96 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/NewRegistrationDto.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/NewRegistrationDto.java @@ -8,14 +8,13 @@ import static de.caritas.cob.userservice.api.helper.UserHelper.VALID_POSTCODE_REGEX; import com.fasterxml.jackson.annotation.JsonProperty; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.util.Collection; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -27,46 +26,46 @@ @NoArgsConstructor @Getter @Setter -@ApiModel(value = "NewRegistration") +@Schema(name = "NewRegistration") @ToString public class NewRegistrationDto implements UserRegistrationDTO { @NotBlank(message = "{user.custom.postcode.notNull}") @NotNull(message = "{user.custom.postcode.notNull}") @Pattern(regexp = VALID_POSTCODE_REGEX, message = "{user.custom.postcode.invalid}") - @ApiModelProperty(required = true, example = "\"79098\"", position = 0) + @Schema(required = true, example = "\"79098\"") @JsonProperty("postcode") private String postcode; @NotNull(message = "{user.custom.agency.notNull}") @Min(value = AGENCY_ID_MIN, message = "{user.custom.agency.invalid}") @Max(value = AGENCY_ID_MAX, message = "{user.custom.agency.invalid}") - @ApiModelProperty(required = true, example = "\"15\"", position = 1) + @Schema(required = true, example = "\"15\"") @JsonProperty("agencyId") private Long agencyId; @NotBlank(message = "{user.consultingType.invalid}") @NotNull(message = "{user.consultingType.invalid}") @Pattern(regexp = CONSULTING_TYPE_REGEXP, message = "{user.consultingType.invalid}") - @ApiModelProperty(required = true, example = "\"0\"", position = 2) + @Schema(required = true, example = "\"0\"") @JsonProperty("consultingType") private String consultingType; - @ApiModelProperty(hidden = true) + @Schema(hidden = true) private boolean newUserAccount; private String consultantId; - @ApiModelProperty(required = false, example = "\"2\"") + @Schema(required = false, example = "\"2\"") @JsonProperty("mainTopicId") private Long mainTopicId; - @ApiModelProperty(required = false, example = "\"MALE\"") + @Schema(required = false, example = "\"MALE\"") @JsonProperty("gender") private String userGender; @Pattern(regexp = AGE_REGEXP, message = "{user.custom.age.invalid}") - @ApiModelProperty(example = "1") + @Schema(example = "1") @JsonProperty("age") private String age; @@ -74,15 +73,15 @@ public Integer getUserAge() { return age == null ? null : Integer.valueOf(age); } - @ApiModelProperty(required = false, example = "\"[1,5]\"") + @Schema(required = false, example = "\"[1,5]\"") @JsonProperty("topicIds") private Collection topicIds; - @ApiModelProperty(required = false, example = "\"RELATIVE_COUNSELLING\"") + @Schema(required = false, example = "\"RELATIVE_COUNSELLING\"") @JsonProperty("counsellingRelation") private String counsellingRelation; - @ApiModelProperty(required = false, example = "\"referer\"") + @Schema(required = false, example = "\"referer\"") @Pattern(regexp = REFERER_REGEXP, message = "{user.custom.referer.invalid}") @JsonProperty("referer") private String referer; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionConsultantForUserDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionConsultantForUserDTO.java index 8aed6afb9..e8aca54c0 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionConsultantForUserDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionConsultantForUserDTO.java @@ -2,8 +2,7 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.caritas.cob.userservice.api.adapters.web.dto.serialization.DecodeUsernameJsonSerializer; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -17,19 +16,19 @@ @NoArgsConstructor @Getter @Setter -@ApiModel(value = "SessionConsultantForUser") +@Schema(name = "SessionConsultantForUser") public class SessionConsultantForUserDTO { private String consultantId; - @ApiModelProperty(example = "\"Username\"") + @Schema(example = "\"Username\"") @JsonSerialize(using = DecodeUsernameJsonSerializer.class) private String username; - @ApiModelProperty(example = "\"true\"") + @Schema(example = "\"true\"") private boolean isAbsent; - @ApiModelProperty(example = "\"Bin nicht da\"") + @Schema(example = "\"Bin nicht da\"") private String absenceMessage; private String displayName; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionUserDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionUserDTO.java index dab76a5d5..33603d1c8 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionUserDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/SessionUserDTO.java @@ -1,7 +1,6 @@ package de.caritas.cob.userservice.api.adapters.web.dto; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; @@ -12,16 +11,16 @@ @NoArgsConstructor @Getter @Setter -@ApiModel(value = "SessionUser") +@Schema(name = "SessionUser") public class SessionUserDTO { - @ApiModelProperty(example = "id", position = 0) + @Schema(example = "id") private String id; - @ApiModelProperty(example = "Username", position = 1) + @Schema(example = "Username") private String username; - @ApiModelProperty(example = "isDeleted", position = 2) + @Schema(example = "isDeleted") private boolean isDeleted; private Map sessionData; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java index 560e5e113..ed5634569 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserChatDTO.java @@ -1,8 +1,7 @@ package de.caritas.cob.userservice.api.adapters.web.dto; import com.fasterxml.jackson.annotation.JsonIgnore; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -19,61 +18,60 @@ @NoArgsConstructor @Getter @Setter -@ApiModel(value = "UserChat") +@Schema(name = "UserChat") public class UserChatDTO { - @ApiModelProperty(example = "153918", position = 0) + @Schema(example = "153918") private Long id; - @ApiModelProperty(example = "Drugs", position = 1) + @Schema(example = "Drugs") private String topic; - @ApiModelProperty(required = true, example = "2019-10-23", position = 2) + @Schema(required = true, example = "2019-10-23") private LocalDate startDate; - @ApiModelProperty(required = true, example = "12:05", position = 3) + @Schema(required = true, example = "12:05") private LocalTime startTime; - @ApiModelProperty(required = true, example = "120", position = 4) + @Schema(required = true, example = "120") private int duration; - @ApiModelProperty(required = true, example = "true", position = 5) + @Schema(required = true, example = "true") private boolean repetitive; - @ApiModelProperty(required = true, example = "false", position = 6) + @Schema(required = true, example = "false") private boolean active; - @ApiModelProperty(required = true, example = "0", position = 7) + @Schema(required = true, example = "0") private Integer consultingType; - @ApiModelProperty(example = "Thanks for the answer", position = 8) + @Schema(example = "Thanks for the answer") private String lastMessage; - @ApiModelProperty(example = "1539184948", position = 9) + @Schema(example = "1539184948") private Long messageDate; - @ApiModelProperty(example = "false", position = 10) + @Schema(example = "false") private boolean messagesRead; - @ApiModelProperty(example = "xGklslk2JJKK", position = 11) + @Schema(example = "xGklslk2JJKK") private String groupId; - @ApiModelProperty(position = 12) - private SessionAttachmentDTO attachment; + @Schema private SessionAttachmentDTO attachment; - @ApiModelProperty(example = "false", position = 13) + @Schema(example = "false") private boolean subscribed; - @ApiModelProperty(example = "ajsasdkjsdfkj3, 23njds9f8jhi", position = 14) + @Schema(example = "ajsasdkjsdfkj3, 23njds9f8jhi") private String[] moderators; @JsonIgnore private LocalDateTime startDateWithTime; - @ApiModelProperty private LastMessageDTO e2eLastMessage; + @Schema private LastMessageDTO e2eLastMessage; - @ApiModelProperty private String createdAt; + @Schema private String createdAt; - @ApiModelProperty private List assignedAgencies; + @Schema private List assignedAgencies; - @ApiModelProperty private String hintMessage; + @Schema private String hintMessage; } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDTO.java index bc8f8a762..98c6c9b39 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDTO.java @@ -20,15 +20,14 @@ import de.caritas.cob.userservice.api.adapters.web.dto.serialization.UrlDecodePasswordJsonDeserializer; import de.caritas.cob.userservice.api.adapters.web.dto.validation.ValidAge; import de.caritas.cob.userservice.api.adapters.web.dto.validation.ValidState; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.util.Collection; -import javax.validation.constraints.Email; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -41,7 +40,7 @@ @NoArgsConstructor @Getter @Setter -@ApiModel(value = "User") +@Schema(name = "User") @ValidAge @ValidState @Builder @@ -49,7 +48,7 @@ public class UserDTO implements UserRegistrationDTO { @NotBlank(message = "{user.username.notBlank}") @NotNull(message = "{user.username.notBlank}") - @ApiModelProperty(required = true, example = "max94") + @Schema(required = true, example = "max94") @JsonDeserialize(using = EncodeUsernameJsonDeserializer.class) @JsonProperty("username") private String username; @@ -57,48 +56,48 @@ public class UserDTO implements UserRegistrationDTO { @NotBlank(message = "{user.custom.postcode.notNull}") @NotNull(message = "{user.custom.postcode.notNull}") @Pattern(regexp = VALID_POSTCODE_REGEX, message = "{user.custom.postcode.invalid}") - @ApiModelProperty(required = true, example = "\"79098\"", position = 1) + @Schema(required = true, example = "\"79098\"") @JsonProperty("postcode") private String postcode; @NotNull(message = "{user.custom.agency.notNull}") @Min(value = AGENCY_ID_MIN, message = "{user.custom.agency.invalid}") @Max(value = AGENCY_ID_MAX, message = "{user.custom.agency.invalid}") - @ApiModelProperty(required = true, example = "\"15\"", position = 2) + @Schema(required = true, example = "\"15\"") @JsonProperty("agencyId") private Long agencyId; @NotBlank(message = "{user.password.notBlank}") - @ApiModelProperty(required = true, example = "pass@w0rd", position = 3) + @Schema(required = true, example = "pass@w0rd") @JsonDeserialize(using = UrlDecodePasswordJsonDeserializer.class) @JsonProperty("password") private String password; @JsonInclude(value = Include.NON_NULL) @Email(message = "{user.email.invalid}") - @ApiModelProperty(example = "max@mustermann.de", position = 4) + @Schema(example = "max@mustermann.de") @JsonProperty("email") private String email; @JsonInclude(value = Include.NON_NULL) @Pattern(regexp = AGE_REGEXP, message = "{user.custom.age.invalid}") - @ApiModelProperty(example = "1", position = 7) + @Schema(example = "1") @JsonProperty("age") private String age; @JsonInclude(value = Include.NON_NULL) @Pattern(regexp = STATE_REGEXP, message = "{user.custom.state.invalid}") @JsonProperty("state") - @ApiModelProperty(example = "\"16\"", position = 9) + @Schema(example = "\"16\"") private String state; @Pattern(regexp = TERMS_ACCEPTED_REGEXP, message = "{user.custom.termsAccepted.invalid}") - @ApiModelProperty(required = true, example = "\"true\"", position = 10) + @Schema(required = true, example = "\"true\"") @JsonProperty("termsAccepted") private String termsAccepted; @Pattern(regexp = CONSULTING_TYPE_REGEXP, message = "{user.consultingType.invalid}") - @ApiModelProperty(required = true, example = "\"0\"", position = 11) + @Schema(required = true, example = "\"0\"") @JsonProperty("consultingType") private String consultingType; @@ -107,29 +106,29 @@ public class UserDTO implements UserRegistrationDTO { private boolean newUserAccount; - @ApiModelProperty(required = false, example = "\"1\"", position = 12) + @Schema(required = false, example = "\"1\"") @JsonProperty("tenantId") private Long tenantId; - @ApiModelProperty(required = false, example = "\"2\"", position = 13) + @Schema(required = false, example = "\"2\"") @JsonProperty("mainTopicId") private Long mainTopicId; - @ApiModelProperty(required = false, example = "\"MALE\"", position = 14) + @Schema(required = false, example = "\"MALE\"") @JsonProperty("gender") private String userGender; - @ApiModelProperty(required = false, example = "\"[1,5]\"") + @Schema(required = false, example = "\"[1,5]\"") @JsonProperty("topicIds") private Collection topicIds = Lists.newArrayList(); - @ApiModelProperty(required = false, example = "\"RELATIVE_COUNSELLING\"") + @Schema(required = false, example = "\"RELATIVE_COUNSELLING\"") @JsonProperty("counsellingRelation") private String counsellingRelation; private LanguageCode preferredLanguage; - @ApiModelProperty(required = false, example = "\"referer\"") + @Schema(required = false, example = "\"referer\"") @Pattern(regexp = REFERER_REGEXP, message = "{user.custom.referer.invalid}") @JsonProperty("referer") private String referer; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDataResponseDTO.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDataResponseDTO.java index 891ff9cf0..9ea7956a3 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDataResponseDTO.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/UserDataResponseDTO.java @@ -3,8 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.caritas.cob.userservice.api.adapters.web.dto.serialization.DecodeUsernameJsonSerializer; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; +import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.List; @@ -20,48 +19,44 @@ @Getter @Setter @Builder -@ApiModel(value = "UserData") +@Schema(name = "UserData") public class UserDataResponseDTO { - @ApiModelProperty(example = "ajsd89-sdf9-sadk-as8j-asdf8jo") + @Schema(example = "ajsd89-sdf9-sadk-as8j-asdf8jo") private String userId; - @ApiModelProperty(example = "max.muster", position = 1) + @Schema(example = "max.muster") @JsonSerialize(using = DecodeUsernameJsonSerializer.class) private String userName; - @ApiModelProperty(example = "Max", position = 2) + @Schema(example = "Max") private String firstName; - @ApiModelProperty(example = "Mustermann", position = 3) + @Schema(example = "Mustermann") private String lastName; - @ApiModelProperty(example = "maxmuster@mann.com", position = 4) + @Schema(example = "maxmuster@mann.com") private String email; - @ApiModelProperty(example = "true", position = 5) + @Schema(example = "true") private boolean isAbsent; - @ApiModelProperty(example = "true", position = 6) + @Schema(example = "true") private boolean isFormalLanguage; - @ApiModelProperty(position = 7) - private Set languages; + @Schema private Set languages; - @ApiModelProperty(example = "Bin mal weg...", position = 8) + @Schema(example = "Bin mal weg...") private String absenceMessage; - @ApiModelProperty(example = "true", position = 9) + @Schema(example = "true") private boolean isInTeamAgency; - @ApiModelProperty(position = 10) - private List agencies; + @Schema private List agencies; - @ApiModelProperty(position = 11) - private Set userRoles; + @Schema private Set userRoles; - @ApiModelProperty(position = 12) - private Set grantedAuthorities; + @Schema private Set grantedAuthorities; private LinkedHashMap consultingTypes; private boolean hasAnonymousConversations; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProvider.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProvider.java index 4a0412e75..b8235cfba 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/MandatoryFieldsProvider.java @@ -40,9 +40,8 @@ private void ensureConsultingTypeSettingsAreNotNull( if (isNull(extendedConsultingTypeResponseDTO.getRegistration()) || isNull(extendedConsultingTypeResponseDTO.getRegistration().getMandatoryFields())) { throw new InternalServerErrorException( - String.format( - "Could not get mandatory fields for consulting type %s. Please check configuration", - consultingTypeId), + "Could not get mandatory fields for consulting type %s. Please check configuration" + .formatted(consultingTypeId), LogService::logInternalServerError); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAge.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAge.java index 912e7fb73..614406fe6 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAge.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAge.java @@ -1,13 +1,13 @@ package de.caritas.cob.userservice.api.adapters.web.dto.validation; import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.validation.Constraint; -import javax.validation.Payload; /** * Custom validation annotation for the age property of the registration {@link UserDTO}. The age is diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidator.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidator.java index 971591960..b6239e299 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidator.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidAgeValidator.java @@ -5,9 +5,9 @@ import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; import de.caritas.cob.userservice.api.manager.consultingtype.registration.mandatoryfields.MandatoryFields; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; import java.util.regex.Pattern; -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; import lombok.NonNull; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidState.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidState.java index 1f3d78b45..bf58380c9 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidState.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidState.java @@ -1,12 +1,12 @@ package de.caritas.cob.userservice.api.adapters.web.dto.validation; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.validation.Constraint; -import javax.validation.Payload; /** * Custom validation annotation for the state property of the registration {@link UserDTO}. The diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidator.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidator.java index f2f231a31..21b3ba986 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidator.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/dto/validation/ValidStateValidator.java @@ -5,9 +5,9 @@ import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; import de.caritas.cob.userservice.api.manager.consultingtype.registration.mandatoryfields.MandatoryFields; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; import java.util.regex.Pattern; -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; import lombok.NonNull; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/ConsultantDtoMapper.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/ConsultantDtoMapper.java index a1a02fcd3..528e95a07 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/ConsultantDtoMapper.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/ConsultantDtoMapper.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import lombok.val; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.stereotype.Service; @@ -120,7 +119,7 @@ public ConsultantDTO consultantDtoOf(Map consultantMap) { consultant.setTenantId(tenantId.intValue()); } consultant.setTenantName((String) consultantMap.get("tenantName")); - val isGroupChatConsultant = + final var isGroupChatConsultant = identityClient.userHasRole(consultant.getId(), UserRole.GROUP_CHAT_CONSULTANT.getValue()); consultant.setIsGroupchatConsultant(isGroupChatConsultant); diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapper.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapper.java index bc6167215..6a285b3ee 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapper.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/mapping/UserDtoMapper.java @@ -8,7 +8,6 @@ import de.caritas.cob.userservice.api.adapters.web.dto.OtpType; import de.caritas.cob.userservice.api.adapters.web.dto.PatchUserDTO; import de.caritas.cob.userservice.api.adapters.web.dto.TwoFactorAuthDTO; -import de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO; import de.caritas.cob.userservice.api.config.auth.UserRole; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.model.OtpInfoDTO; @@ -28,8 +27,8 @@ public class UserDtoMapper { @Value("${feature.appointment.enabled}") private boolean appointmentFeatureEnabled; - public UserDataResponseDTO userDataOf( - UserDataResponseDTO userData, + public de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO userDataOf( + de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO userData, OtpInfoDTO otpInfoDTO, boolean isE2eEncEnabled, boolean isDisplayNameAllowed) { diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacade.java b/src/main/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacade.java index cc2fd74f4..3db10bf46 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/facade/AskerUserAdminFacade.java @@ -36,7 +36,7 @@ public void markAskerForDeletion(String userId) { if (nonNull(user.getDeleteDate())) { throw new ConflictException( - String.format("Asker with id %s is already marked for deletion", userId)); + "Asker with id %s is already marked for deletion".formatted(userId)); } this.identityClient.deactivateUser(userId); diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacade.java b/src/main/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacade.java index 8c394a7b8..3f9e9c1c4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacade.java @@ -95,7 +95,7 @@ private Sort getValidSorter(Sort sort) { if (sort == null || Stream.of(FieldEnum.values()).noneMatch(providedSortFieldIgnoringCase(sort))) { sort = new Sort(); - sort.setField(FieldEnum.LASTNAME); + sort.setField(FieldEnum.LAST_NAME); sort.setOrder(OrderEnum.ASC); } return sort; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistry.java b/src/main/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistry.java index ff9e44ee3..e8ea12d5c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistry.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/report/registry/ViolationRuleRegistry.java @@ -48,8 +48,8 @@ public List getViolationReportRules( : new ArrayList<>(this.violationReportRules); reportingRules.forEach( reportRule -> { - if (reportRule instanceof AgencyDependedViolationReportRule) { - ((AgencyDependedViolationReportRule) reportRule).setAllAgencies(allAgencies); + if (reportRule instanceof AgencyDependedViolationReportRule rule) { + rule.setAllAgencies(allAgencies); } }); return reportingRules; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGenerator.java b/src/main/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGenerator.java index 673324660..e1472b07d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGenerator.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/report/service/ViolationReportGenerator.java @@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.format.DateTimeFormatter; import java.util.Collection; @@ -58,9 +57,9 @@ public List generateReport() { private Path buildFilePath() throws IOException { String path = VIOLATION_REPORT_BASE_PATH + nowInUtc().format(DATE_TIME_FORMAT) + ".json"; - if (!Paths.get(path).getParent().toFile().exists()) { - Files.createDirectory(Paths.get(path).getParent()); + if (!Path.of(path).getParent().toFile().exists()) { + Files.createDirectory(Path.of(path).getParent()); } - return Paths.get(path); + return Path.of(path); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/FilterQueryBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/FilterQueryBuilder.java deleted file mode 100644 index 116f3d80f..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/FilterQueryBuilder.java +++ /dev/null @@ -1,40 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service; - -import static java.util.Objects.nonNull; - -import org.apache.commons.lang3.StringUtils; -import org.apache.lucene.search.Query; -import org.hibernate.search.query.dsl.BooleanJunction; -import org.hibernate.search.query.dsl.QueryBuilder; - -public abstract class FilterQueryBuilder { - protected final QueryBuilder queryBuilder; - - protected FilterQueryBuilder(QueryBuilder queryBuilder) { - this.queryBuilder = queryBuilder; - } - - public abstract Query buildQuery(); - - protected abstract Query buildFilteredQuery(); - - protected void addStringFilterCondition( - String filterValue, String targetField, BooleanJunction junction) { - if (StringUtils.isNotBlank(filterValue)) { - addFilterCondition(filterValue, targetField, junction); - } - } - - protected void addFilterCondition( - Object filterValue, String targetField, BooleanJunction junction) { - junction.must( - this.queryBuilder.keyword().onField(targetField).matching(filterValue).createQuery()); - } - - protected void addObjectFilterCondition( - Object filterValue, String targetField, BooleanJunction junction) { - if (nonNull(filterValue)) { - addFilterCondition(filterValue, targetField, junction); - } - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java deleted file mode 100644 index f7fccab64..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java +++ /dev/null @@ -1,70 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service; - -import de.caritas.cob.userservice.api.adapters.web.dto.HalLink; -import de.caritas.cob.userservice.api.adapters.web.dto.Sort; -import de.caritas.cob.userservice.api.admin.hallink.HalLinkBuilder; -import org.hibernate.search.jpa.FullTextQuery; -import org.springframework.http.ResponseEntity; - -public abstract class SearchResultBuilder implements HalLinkBuilder { - - protected final FullTextQuery fullTextQuery; - protected F filter; - - protected S searchResultDto; - protected Sort sort; - protected Integer page; - protected Integer perPage; - - protected SearchResultBuilder(FullTextQuery fullTextQuery) { - this.fullTextQuery = fullTextQuery; - } - - public SearchResultBuilder withFilter(F filter) { - this.filter = filter; - return this; - } - - public SearchResultBuilder withSort(Sort sort) { - this.sort = sort; - return this; - } - - public SearchResultBuilder withPage(Integer page) { - this.page = page; - return this; - } - - public SearchResultBuilder withPerPage(Integer perPage) { - this.perPage = perPage; - return this; - } - - public abstract S buildSearchResult(); - - protected HalLink buildSelfLink(final ResponseEntity responseEntity) { - return buildHalLinkForParams(responseEntity); - } - - protected HalLink buildHalLinkForParams(final ResponseEntity responseEntity) { - return buildHalLink(responseEntity, HalLink.MethodEnum.GET); - } - - protected HalLink buildNextLink(final ResponseEntity results) { - if (hasNextPage()) { - return buildHalLinkForParams(results); - } - return null; - } - - protected boolean hasNextPage() { - return this.fullTextQuery.getResultSize() > this.page * this.perPage; - } - - protected HalLink buildPreviousLink(final ResponseEntity results) { - if (this.page > 1) { - return buildHalLinkForParams(results); - } - return null; - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/AdminSearchResultBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/AdminSearchResultBuilder.java deleted file mode 100644 index 4127afc6a..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/AdminSearchResultBuilder.java +++ /dev/null @@ -1,60 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.admin; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; - -import de.caritas.cob.userservice.api.adapters.web.dto.AdminFilter; -import de.caritas.cob.userservice.api.adapters.web.dto.AdminSearchResultDTO; -import de.caritas.cob.userservice.api.adapters.web.dto.HalLink; -import de.caritas.cob.userservice.api.adapters.web.dto.PaginationLinks; -import de.caritas.cob.userservice.api.admin.service.SearchResultBuilder; -import de.caritas.cob.userservice.api.model.Admin; -import de.caritas.cob.userservice.generated.api.adapters.web.controller.UseradminApi; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.hibernate.search.jpa.FullTextQuery; - -public class AdminSearchResultBuilder - extends SearchResultBuilder { - private AdminSearchResultBuilder(FullTextQuery fullTextQuery) { - super(fullTextQuery); - } - - public static AdminSearchResultBuilder getInstance(FullTextQuery fullTextQuery) { - return new AdminSearchResultBuilder(fullTextQuery); - } - - public AdminSearchResultDTO buildSearchResult() { - Stream resultStream = fullTextQuery.getResultStream(); - var resultList = - resultStream - .map(AdminResponseDTOBuilder::getInstance) - .map(AdminResponseDTOBuilder::buildAgencyAdminResponseDTO) - .collect(Collectors.toList()); - - var paginationLinks = - new PaginationLinks() - .self(buildSelfLink()) - .next(buildNextLink()) - .previous(buildPreviousLink()); - - return new AdminSearchResultDTO() - .embedded(resultList) - .links(paginationLinks) - .total(fullTextQuery.getResultSize()); - } - - private HalLink buildSelfLink() { - return super.buildSelfLink( - methodOn(UseradminApi.class).getAgencyAdmins(page, perPage, filter, sort)); - } - - private HalLink buildNextLink() { - return super.buildNextLink( - methodOn(UseradminApi.class).getAgencyAdmins(page + 1, perPage, filter, sort)); - } - - private HalLink buildPreviousLink() { - return buildPreviousLink( - methodOn(UseradminApi.class).getAgencyAdmins(page - 1, perPage, filter, sort)); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationService.java index 86f23b952..8c7b01830 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/create/agencyrelation/CreateAdminAgencyRelationService.java @@ -34,9 +34,7 @@ private AgencyDTO retrieveAgency(Long agencyId) { var agencyDto = this.agencyService.getAgencyWithoutCaching(agencyId); return Optional.ofNullable(agencyDto) .orElseThrow( - () -> - new BadRequestException( - String.format("AgencyId %s is not a valid agency", agencyId))); + () -> new BadRequestException("AgencyId %s is not a valid agency".formatted(agencyId))); } private AdminAgency buildAdminAgency(final Admin admin, final Long agencyId) { diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/AdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/AdminFilterService.java index 4145be1ba..eb2bc6cf1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/AdminFilterService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/AdminFilterService.java @@ -3,21 +3,24 @@ import static java.util.Objects.nonNull; import de.caritas.cob.userservice.api.adapters.web.dto.AdminFilter; +import de.caritas.cob.userservice.api.adapters.web.dto.AdminResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.AdminSearchResultDTO; import de.caritas.cob.userservice.api.adapters.web.dto.Sort; import de.caritas.cob.userservice.api.adapters.web.dto.Sort.FieldEnum; -import de.caritas.cob.userservice.api.admin.service.admin.AdminSearchResultBuilder; -import de.caritas.cob.userservice.api.admin.service.admin.search.querybuilder.AdminFilterQueryBuilder; +import de.caritas.cob.userservice.api.admin.service.admin.AdminResponseDTOBuilder; import de.caritas.cob.userservice.api.model.Admin; +import jakarta.persistence.EntityManagerFactory; +import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream; -import javax.persistence.EntityManagerFactory; import lombok.NonNull; import lombok.RequiredArgsConstructor; -import org.apache.lucene.search.SortField; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.hibernate.search.jpa.FullTextQuery; -import org.hibernate.search.jpa.Search; +import org.hibernate.Session; +import org.hibernate.search.engine.search.sort.dsl.SearchSortFactory; +import org.hibernate.search.engine.search.sort.dsl.SortFinalStep; +import org.hibernate.search.engine.search.sort.dsl.SortOrder; +import org.hibernate.search.mapper.orm.Search; +import org.hibernate.search.mapper.orm.session.SearchSession; import org.springframework.stereotype.Service; @Service @@ -28,56 +31,85 @@ public class AdminFilterService { public AdminSearchResultDTO findFilteredAdmins( final Integer page, final Integer perPage, final AdminFilter adminFilter, Sort sort) { - var fullTextEntityManager = - Search.getFullTextEntityManager(entityManagerFactory.createEntityManager()); - - sort = getValidSorter(sort); - var fullTextQuery = buildFilteredQuery(adminFilter, fullTextEntityManager); - fullTextQuery.setMaxResults(Math.max(perPage, 1)); - fullTextQuery.setFirstResult(Math.max((page - 1) * perPage, 0)); - fullTextQuery.setSort(buildSort(sort)); - - var searchResultDTO = - AdminSearchResultBuilder.getInstance(fullTextQuery) - .withFilter(adminFilter) - .withSort(sort) - .withPage(page) - .withPerPage(perPage) - .buildSearchResult(); - - fullTextEntityManager.close(); - return searchResultDTO; - } - protected FullTextQuery buildFilteredQuery( - AdminFilter adminFilter, FullTextEntityManager fullTextEntityManager) { + try (var entityManager = entityManagerFactory.createEntityManager()) { + var session = entityManager.unwrap(Session.class); + + // Obtain a SearchSession from the Hibernate Session + SearchSession searchSession = Search.session(session); - var queryBuilder = - fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Admin.class).get(); + // Ensure the sort is valid + sort = getValidSorter(sort); - var query = - AdminFilterQueryBuilder.getInstance(queryBuilder).onAdminFilter(adminFilter).buildQuery(); + // Build the search query + var admins = fetchAdmins(adminFilter, searchSession, sort, page, perPage); - return fullTextEntityManager.createFullTextQuery(query, Admin.class); + // Build the result + return convertToSearchResultDTO(admins); + } } - private org.apache.lucene.search.Sort buildSort(Sort sort) { - var luceneSort = new org.apache.lucene.search.Sort(); - if (nonNull(sort) && nonNull(sort.getField())) { - var reverse = Sort.OrderEnum.DESC.equals(sort.getOrder()); - luceneSort.setSort( - SortField.FIELD_SCORE, - new SortField(sort.getField().getValue(), SortField.Type.STRING, reverse)); + private AdminSearchResultDTO convertToSearchResultDTO(List admins) { + AdminSearchResultDTO result = new AdminSearchResultDTO(); + for (Admin admin : admins) { + AdminResponseDTO adminResponseDTO = + AdminResponseDTOBuilder.getInstance(admin).buildAgencyAdminResponseDTO(); + result.addEmbeddedItem(adminResponseDTO); } + return result; + } - return luceneSort; + protected List fetchAdmins( + AdminFilter adminFilter, + SearchSession searchSession, + Sort sortDefinition, + Integer page, + Integer perPage) { + int offset = Math.max((page - 1) * perPage, 0); + + return searchSession + .search(Admin.class) + .where( + f -> + f.bool( + bool -> { + // Apply username filter if present + if (adminFilter.getUsername() != null) { + bool.must(f.match().field("username").matching(adminFilter.getUsername())); + } + // Apply lastname filter if present + if (adminFilter.getLastname() != null) { + bool.must(f.match().field("lastname").matching(adminFilter.getLastname())); + } + // Apply email filter if present + if (adminFilter.getEmail() != null) { + bool.must(f.match().field("email").matching(adminFilter.getEmail())); + } + // Apply agencyId filter if present + if (adminFilter.getAgencyId() != null) { + bool.must(f.match().field("agencyId").matching(adminFilter.getAgencyId())); + } + })) + .sort(f -> buildSort(f, sortDefinition)) // Apply sorting here + .fetchHits(offset, Math.max(perPage, 1)); // Apply pagination + } + + private SortFinalStep buildSort(SearchSortFactory factory, Sort sort) { + if (sort != null && sort.getField() != null) { + boolean reverse = Sort.OrderEnum.DESC.equals(sort.getOrder()); + return factory + .field(sort.getField().getValue()) + .order(reverse ? SortOrder.DESC : SortOrder.ASC); + } else { + return factory.field(FieldEnum.LAST_NAME.getValue()).order(SortOrder.ASC); + } } private Sort getValidSorter(Sort sort) { if (sort == null || Stream.of(Sort.FieldEnum.values()).noneMatch(providedSortFieldIgnoringCase(sort))) { sort = new Sort(); - sort.setField(Sort.FieldEnum.LASTNAME); + sort.setField(FieldEnum.LAST_NAME); sort.setOrder(Sort.OrderEnum.ASC); } return sort; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminService.java index d5d4e467d..ff101abd4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminService.java @@ -30,14 +30,13 @@ public class RetrieveAdminService { public Admin findAdmin(final String adminId, Admin.AdminType adminType) { Optional byId = this.adminRepository.findByIdAndType(adminId, adminType); return byId.filter(admin -> admin.getType().equals(adminType)) - .orElseThrow( - () -> new NoContentException(String.format(ADMIN_WITH_ID_S_NOT_FOUND, adminId))); + .orElseThrow(() -> new NoContentException(ADMIN_WITH_ID_S_NOT_FOUND.formatted(adminId))); } public List findAgencyIdsOfAdmin(final String adminId) { final Optional admin = adminRepository.findById(adminId); if (admin.isEmpty()) { - throw new BadRequestException(String.format(ADMIN_WITH_ID_S_NOT_FOUND, adminId)); + throw new BadRequestException(ADMIN_WITH_ID_S_NOT_FOUND.formatted(adminId)); } return adminAgencyRepository.findByAdminId(adminId).stream() diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/querybuilder/AdminFilterQueryBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/querybuilder/AdminFilterQueryBuilder.java deleted file mode 100644 index 2efabc872..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/admin/search/querybuilder/AdminFilterQueryBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.admin.search.querybuilder; - -import static java.util.Objects.nonNull; - -import de.caritas.cob.userservice.api.adapters.web.dto.AdminFilter; -import de.caritas.cob.userservice.api.admin.service.FilterQueryBuilder; -import org.apache.lucene.search.Query; -import org.hibernate.search.query.dsl.BooleanJunction; -import org.hibernate.search.query.dsl.QueryBuilder; - -public class AdminFilterQueryBuilder extends FilterQueryBuilder { - - private static final String FIELD_USERNAME = "username"; - private static final String FIELD_LAST_NAME = "lastName"; - private static final String FIELD_EMAIL = "email"; - private static final String FIELD_AGENCY_IDS = "adminAgencies.agencyId"; - - private AdminFilter adminFilter; - - protected AdminFilterQueryBuilder(final QueryBuilder queryBuilder) { - super(queryBuilder); - } - - public static AdminFilterQueryBuilder getInstance(QueryBuilder queryBuilder) { - return new AdminFilterQueryBuilder(queryBuilder); - } - - public AdminFilterQueryBuilder onAdminFilter(AdminFilter adminFilter) { - this.adminFilter = adminFilter; - return this; - } - - @Override - public Query buildQuery() { - return nonNull(this.adminFilter) ? buildFilteredQuery() : this.queryBuilder.all().createQuery(); - } - - @Override - protected Query buildFilteredQuery() { - BooleanJunction junction = this.queryBuilder.bool(); - - addStringFilterCondition(this.adminFilter.getUsername(), FIELD_USERNAME, junction); - addStringFilterCondition(this.adminFilter.getLastname(), FIELD_LAST_NAME, junction); - addStringFilterCondition(this.adminFilter.getEmail(), FIELD_EMAIL, junction); - addObjectFilterCondition(this.adminFilter.getAgencyId(), FIELD_AGENCY_IDS, junction); - - return junction.isEmpty() ? this.queryBuilder.all().createQuery() : junction.createQuery(); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminService.java index eed7588b2..f27d734f8 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminService.java @@ -54,8 +54,7 @@ public class ConsultantAgencyAdminService { public ConsultantAgencyResponseDTO findConsultantAgencies(String consultantId) { var consultant = consultantRepository.findByIdAndDeleteDateIsNull(consultantId); if (consultant.isEmpty()) { - throw new BadRequestException( - String.format("Consultant with id %s does not exist", consultantId)); + throw new BadRequestException("Consultant with id %s does not exist".formatted(consultantId)); } var consultantAgencyIds = diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java index 3368990d0..879c30843 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java @@ -1,21 +1,22 @@ package de.caritas.cob.userservice.api.admin.service.consultant; -import static java.util.Objects.nonNull; - +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantAdminResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSearchResultDTO; import de.caritas.cob.userservice.api.adapters.web.dto.Sort; -import de.caritas.cob.userservice.api.adapters.web.dto.Sort.OrderEnum; -import de.caritas.cob.userservice.api.admin.service.consultant.querybuilder.ConsultantFilterQueryBuilder; +import de.caritas.cob.userservice.api.adapters.web.dto.Sort.FieldEnum; import de.caritas.cob.userservice.api.model.Consultant; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; +import java.util.List; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.lucene.search.SortField; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.hibernate.search.jpa.FullTextQuery; -import org.hibernate.search.jpa.Search; +import org.hibernate.Session; +import org.hibernate.search.engine.search.sort.dsl.SearchSortFactory; +import org.hibernate.search.engine.search.sort.dsl.SortFinalStep; +import org.hibernate.search.engine.search.sort.dsl.SortOrder; +import org.hibernate.search.mapper.orm.Search; +import org.hibernate.search.mapper.orm.session.SearchSession; import org.springframework.stereotype.Service; /** Service class to provide filtered search for all {@link Consultant} entities. */ @@ -40,62 +41,77 @@ public ConsultantSearchResultDTO findFilteredConsultants( final Integer perPage, final ConsultantFilter consultantFilter, final Sort sort) { - var fullTextEntityManager = - Search.getFullTextEntityManager(entityManagerFactory.createEntityManager()); - triggerLuceneToBuildIndex(fullTextEntityManager); - var fullTextQuery = buildFilteredQuery(consultantFilter, fullTextEntityManager); - fullTextQuery.setMaxResults(Math.max(perPage, 1)); - fullTextQuery.setFirstResult(Math.max((page - 1) * perPage, 0)); - fullTextQuery.setSort(buildSort(sort)); - var searchResultDTO = - ConsultantSearchResultBuilder.getInstance(fullTextQuery) - .withFilter(consultantFilter) - .withSort(sort) - .withPage(page) - .withPerPage(perPage) - .buildSearchResult(); + try (var entityManager = entityManagerFactory.createEntityManager()) { + var session = entityManager.unwrap(Session.class); - fullTextEntityManager.close(); - return searchResultDTO; - } + // Obtain a SearchSession from the Hibernate Session + SearchSession searchSession = Search.session(session); - private static void triggerLuceneToBuildIndex(FullTextEntityManager fullTextEntityManager) { - try { - fullTextEntityManager.createIndexer(Consultant.class).startAndWait(); - } catch (InterruptedException e) { - log.info("Lucene index building was interrupted."); - Thread.currentThread().interrupt(); + // Build the search query + var admins = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); + + // Build the result + return convertToSearchResultDTO(admins); } } - protected FullTextQuery buildFilteredQuery( - ConsultantFilter consultantFilter, FullTextEntityManager fullTextEntityManager) { - - var queryBuilder = - fullTextEntityManager - .getSearchFactory() - .buildQueryBuilder() - .forEntity(Consultant.class) - .get(); + private ConsultantSearchResultDTO convertToSearchResultDTO(List admins) { + ConsultantSearchResultDTO result = new ConsultantSearchResultDTO(); + for (Consultant admin : admins) { + ConsultantAdminResponseDTO adminResponseDTO = + ConsultantResponseDTOBuilder.getInstance(admin).buildResponseDTO(); + result.addEmbeddedItem(adminResponseDTO); + } + return result; + } - var query = - ConsultantFilterQueryBuilder.getInstance(queryBuilder) - .onConsultantFilter(consultantFilter) - .buildQuery(); + protected List fetchConsultants( + ConsultantFilter consultantFilter, + SearchSession searchSession, + Sort sortDefinition, + Integer page, + Integer perPage) { + int offset = Math.max((page - 1) * perPage, 0); - return fullTextEntityManager.createFullTextQuery(query, Consultant.class); + return searchSession + .search(Consultant.class) + .where( + f -> + f.bool( + bool -> { + // Apply username filter if present + if (consultantFilter.getUsername() != null) { + bool.must( + f.match().field("username").matching(consultantFilter.getUsername())); + } + // Apply lastname filter if present + if (consultantFilter.getLastname() != null) { + bool.must( + f.match().field("lastname").matching(consultantFilter.getLastname())); + } + // Apply email filter if present + if (consultantFilter.getEmail() != null) { + bool.must(f.match().field("email").matching(consultantFilter.getEmail())); + } + // Apply agencyId filter if present + if (consultantFilter.getAgencyId() != null) { + bool.must( + f.match().field("agencyId").matching(consultantFilter.getAgencyId())); + } + })) + .sort(f -> buildSort(f, sortDefinition)) // Apply sorting here + .fetchHits(offset, Math.max(perPage, 1)); // Apply pagination } - private org.apache.lucene.search.Sort buildSort(Sort sort) { - var luceneSort = new org.apache.lucene.search.Sort(); - if (nonNull(sort) && nonNull(sort.getField())) { - var reverse = OrderEnum.DESC.equals(sort.getOrder()); - luceneSort.setSort( - SortField.FIELD_SCORE, - new SortField(sort.getField().getValue(), SortField.Type.STRING, reverse)); + private SortFinalStep buildSort(SearchSortFactory factory, Sort sort) { + if (sort != null && sort.getField() != null) { + boolean reverse = Sort.OrderEnum.DESC.equals(sort.getOrder()); + return factory + .field(sort.getField().getValue()) + .order(reverse ? SortOrder.DESC : SortOrder.ASC); + } else { + return factory.field(FieldEnum.LAST_NAME.getValue()).order(SortOrder.ASC); } - - return luceneSort; } } diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareService.java deleted file mode 100644 index fac62f711..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareService.java +++ /dev/null @@ -1,63 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.consultant; - -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; -import de.caritas.cob.userservice.api.admin.service.consultant.querybuilder.ConsultantFilterQueryBuilder; -import de.caritas.cob.userservice.api.model.Consultant; -import de.caritas.cob.userservice.api.tenant.TenantContext; -import javax.persistence.EntityManagerFactory; -import lombok.NonNull; -import org.apache.lucene.search.Query; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.hibernate.search.jpa.FullTextQuery; -import org.hibernate.search.query.dsl.QueryBuilder; -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Service; - -/** Service class to provide filtered search for all {@link Consultant} entities based on tenant. */ -@Service -@Primary -@ConditionalOnExpression("${multitenancy.enabled:true}") -public class ConsultantAdminFilterTenantAwareService extends ConsultantAdminFilterService { - - protected static final String TENANT_ID_SEARCH_FIELD = "tenantId"; - - public ConsultantAdminFilterTenantAwareService( - @NonNull EntityManagerFactory entityManagerFactory) { - super(entityManagerFactory); - } - - @Override - protected FullTextQuery buildFilteredQuery( - ConsultantFilter consultantFilter, FullTextEntityManager fullTextEntityManager) { - - QueryBuilder queryBuilder = - fullTextEntityManager - .getSearchFactory() - .buildQueryBuilder() - .forEntity(Consultant.class) - .get(); - - Query tenantQuery = - fullTextEntityManager - .getSearchFactory() - .buildQueryBuilder() - .forEntity(Consultant.class) - .get() - .keyword() - .onField(TENANT_ID_SEARCH_FIELD) - .matching(TenantContext.getCurrentTenant()) - .createQuery(); - - Query query = - ConsultantFilterQueryBuilder.getInstance(queryBuilder) - .onConsultantFilter(consultantFilter) - .buildQuery(); - - Query resultQuery = - TenantContext.isTechnicalOrSuperAdminContext() - ? query - : queryBuilder.bool().must(tenantQuery).must(query).createQuery(); - return fullTextEntityManager.createFullTextQuery(resultQuery, Consultant.class); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminService.java index c7131ce98..37acb96ce 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminService.java @@ -64,7 +64,7 @@ public ConsultantAdminResponseDTO findConsultantById(String consultantId) { .orElseThrow( () -> new NoContentException( - String.format("Consultant with id %s not found", consultantId))); + "Consultant with id %s not found".formatted(consultantId))); var response = ConsultantResponseDTOBuilder.getInstance(consultant).buildResponseDTO(); enrichWithDisplayName(consultantId, response); return response; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantReindexer.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantReindexer.java deleted file mode 100644 index cac2844c5..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantReindexer.java +++ /dev/null @@ -1,21 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.consultant; - -import de.caritas.cob.userservice.api.service.LogService; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.springframework.beans.factory.InitializingBean; - -/** Reindexer class for all indexed entities. */ -@RequiredArgsConstructor -public class ConsultantReindexer implements InitializingBean { - - private final @NonNull FullTextEntityManager fullTextEntityManager; - - /** Indexes all entity fields marked as indexed on startup. */ - @Override - public void afterPropertiesSet() throws Exception { - LogService.logInfo("Going to index entities"); - this.fullTextEntityManager.createIndexer().startAndWait(); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java deleted file mode 100644 index 94515ff2b..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java +++ /dev/null @@ -1,78 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.consultant; - -import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; - -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantDTO; -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSearchResultDTO; -import de.caritas.cob.userservice.api.adapters.web.dto.HalLink; -import de.caritas.cob.userservice.api.adapters.web.dto.PaginationLinks; -import de.caritas.cob.userservice.api.admin.service.SearchResultBuilder; -import de.caritas.cob.userservice.api.model.Consultant; -import de.caritas.cob.userservice.generated.api.adapters.web.controller.UseradminApi; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.hibernate.search.jpa.FullTextQuery; - -/** - * Builder class to generate a {@link ConsultantSearchResultDTO} containing available hal links and - * result of {@link ConsultantDTO} elements. - */ -public class ConsultantSearchResultBuilder - extends SearchResultBuilder { - - private ConsultantSearchResultBuilder(FullTextQuery fullTextQuery) { - super(fullTextQuery); - } - - /** - * Creates the {@link ConsultantSearchResultBuilder} instance. - * - * @param fullTextQuery mandatory filtered search query for result extraction - * @return a instance of {@link ConsultantSearchResultBuilder} - */ - public static ConsultantSearchResultBuilder getInstance(FullTextQuery fullTextQuery) { - return new ConsultantSearchResultBuilder(fullTextQuery); - } - - /** - * Generates the {@link ConsultantSearchResultDTO} containing all results and navigation hal - * links. - * - * @return the generated {@link ConsultantSearchResultDTO} - */ - public ConsultantSearchResultDTO buildSearchResult() { - Stream resultStream = fullTextQuery.getResultStream(); - var resultList = - resultStream - .map(ConsultantResponseDTOBuilder::getInstance) - .map(ConsultantResponseDTOBuilder::buildResponseDTO) - .collect(Collectors.toList()); - - var paginationLinks = - new PaginationLinks() - .self(buildSelfLink()) - .next(buildNextLink()) - .previous(buildPreviousLink()); - - return new ConsultantSearchResultDTO() - .embedded(resultList) - .links(paginationLinks) - .total(fullTextQuery.getResultSize()); - } - - private HalLink buildSelfLink() { - return super.buildSelfLink( - methodOn(UseradminApi.class).getConsultants(page, perPage, filter, sort)); - } - - private HalLink buildNextLink() { - return super.buildNextLink( - methodOn(UseradminApi.class).getConsultants(page + 1, perPage, filter, sort)); - } - - private HalLink buildPreviousLink() { - return buildPreviousLink( - methodOn(UseradminApi.class).getConsultants(page - 1, perPage, filter, sort)); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorService.java index 5fe9c32ee..13bdd7ed1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorService.java @@ -126,7 +126,7 @@ private Consultant retrieveConsultant(String consultantId) { .orElseThrow( () -> new BadRequestException( - String.format("Consultant with id %s does not exist", consultantId))); + "Consultant with id %s does not exist".formatted(consultantId))); } private void checkConsultantHasRoleSet(Set roles, String consultantId) { @@ -136,18 +136,15 @@ private void checkConsultantHasRoleSet(Set roles, String consultantId) { .orElseThrow( () -> new BadRequestException( - String.format( - "Consultant with id %s does not have the role set %s", - consultantId, roles))); + "Consultant with id %s does not have the role set %s" + .formatted(consultantId, roles))); } private AgencyDTO retrieveAgency(Long agencyId) { var agencyDto = this.agencyService.getAgencyWithoutCaching(agencyId); return Optional.ofNullable(agencyDto) .orElseThrow( - () -> - new BadRequestException( - String.format("AgencyId %s is not a valid agency", agencyId))); + () -> new BadRequestException("AgencyId %s is not a valid agency".formatted(agencyId))); } private void verifyAllAssignedAgenciesHaveSameConsultingType( diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/CreateConsultantAgencyDTOInputAdapter.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/CreateConsultantAgencyDTOInputAdapter.java index ca428e4c0..602ec5ff2 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/CreateConsultantAgencyDTOInputAdapter.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/CreateConsultantAgencyDTOInputAdapter.java @@ -1,6 +1,6 @@ package de.caritas.cob.userservice.api.admin.service.consultant.create.agencyrelation; -import static org.hibernate.search.util.impl.CollectionHelper.asSet; +import static org.hibernate.validator.internal.util.CollectionHelper.asSet; import de.caritas.cob.userservice.api.adapters.web.dto.CreateConsultantAgencyDTO; import java.util.Set; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/querybuilder/ConsultantFilterQueryBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/querybuilder/ConsultantFilterQueryBuilder.java deleted file mode 100644 index 3863cacbd..000000000 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/querybuilder/ConsultantFilterQueryBuilder.java +++ /dev/null @@ -1,70 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.consultant.querybuilder; - -import static java.util.Objects.nonNull; - -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; -import de.caritas.cob.userservice.api.admin.service.FilterQueryBuilder; -import org.apache.lucene.search.Query; -import org.hibernate.search.query.dsl.BooleanJunction; -import org.hibernate.search.query.dsl.QueryBuilder; - -/** Builder for the filter based query used by hibernate search. */ -public class ConsultantFilterQueryBuilder extends FilterQueryBuilder { - - private static final String FIELD_USERNAME = "username"; - private static final String FIELD_LAST_NAME = "lastName"; - private static final String FIELD_EMAIL = "email"; - private static final String FIELD_ABSENT = "absent"; - private static final String FIELD_AGENCY_IDS = "consultantAgencies.agencyId"; - - private ConsultantFilter consultantFilter; - - private ConsultantFilterQueryBuilder(QueryBuilder queryBuilder) { - super(queryBuilder); - } - - /** - * Creates the {@link ConsultantFilterQueryBuilder} instance. - * - * @param queryBuilder the query builder to build the filters on - * @return the {@link ConsultantFilterQueryBuilder} instance - */ - public static ConsultantFilterQueryBuilder getInstance(QueryBuilder queryBuilder) { - return new ConsultantFilterQueryBuilder(queryBuilder); - } - - /** - * Sets the {@link ConsultantFilter} object to be included in the query. - * - * @param consultantFilter the {@link ConsultantFilter} - * @return the current {@link ConsultantFilterQueryBuilder} - */ - public ConsultantFilterQueryBuilder onConsultantFilter(ConsultantFilter consultantFilter) { - this.consultantFilter = consultantFilter; - return this; - } - - /** - * Builds the filter query for hibernate search. If no filter is set in {@link ConsultantFilter}, - * a unfiltered query will be returned. - * - * @return the created {@link Query} - */ - public Query buildQuery() { - return nonNull(this.consultantFilter) - ? buildFilteredQuery() - : this.queryBuilder.all().createQuery(); - } - - protected Query buildFilteredQuery() { - BooleanJunction junction = this.queryBuilder.bool(); - - addStringFilterCondition(this.consultantFilter.getUsername(), FIELD_USERNAME, junction); - addStringFilterCondition(this.consultantFilter.getLastname(), FIELD_LAST_NAME, junction); - addStringFilterCondition(this.consultantFilter.getEmail(), FIELD_EMAIL, junction); - addObjectFilterCondition(this.consultantFilter.getAbsent(), FIELD_ABSENT, junction); - addObjectFilterCondition(this.consultantFilter.getAgencyId(), FIELD_AGENCY_IDS, junction); - - return junction.isEmpty() ? this.queryBuilder.all().createQuery() : junction.createQuery(); - } -} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateService.java index 7200e2d2c..d59928797 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateService.java @@ -54,7 +54,7 @@ public Consultant updateConsultant( .orElseThrow( () -> new BadRequestException( - String.format("Consultant with id %s does not exist", consultantId))); + "Consultant with id %s does not exist".formatted(consultantId))); UserDTO userDTO = buildValidatedUserDTO(updateConsultantDTO, consultant); this.identityClient.updateUserData( diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidator.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidator.java index bb24f757f..7abbc5723 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidator.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidator.java @@ -12,7 +12,7 @@ import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException; import de.caritas.cob.userservice.api.exception.httpresponses.customheader.HttpStatusExceptionReason; import de.caritas.cob.userservice.api.exception.keycloak.KeycloakException; -import javax.validation.Validator; +import jakarta.validation.Validator; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/config/AppConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/AppConfig.java index a1156e3bf..20151bf57 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/AppConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/AppConfig.java @@ -1,10 +1,6 @@ package de.caritas.cob.userservice.api.config; -import de.caritas.cob.userservice.api.admin.service.consultant.ConsultantReindexer; import java.time.Clock; -import javax.persistence.EntityManagerFactory; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.hibernate.search.jpa.Search; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; @@ -28,7 +24,7 @@ public class AppConfig { * @return */ @Bean - public LocalValidatorFactoryBean validator(MessageSource messageSource) { + LocalValidatorFactoryBean validator(MessageSource messageSource) { LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.setValidationMessageSource(messageSource); return validatorFactoryBean; @@ -36,25 +32,12 @@ public LocalValidatorFactoryBean validator(MessageSource messageSource) { // RestTemplate Bean @Bean - public RestTemplate restTemplate(RestTemplateBuilder builder) { + RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } - /** - * Builds an indexer for hibernate search. - * - * @param entityManagerFactory the manager factory bean - * @return an {@link AgencyReindexer} used to reindex entities - */ - @Bean - public ConsultantReindexer consultantReindexer(EntityManagerFactory entityManagerFactory) { - FullTextEntityManager manager = - Search.getFullTextEntityManager(entityManagerFactory.createEntityManager()); - return new ConsultantReindexer(manager); - } - @Bean - public Clock clock() { + Clock clock() { return Clock.systemUTC(); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/AppointmentConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/AppointmentConfig.java index 9ef77897f..94c6f3a3d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/AppointmentConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/AppointmentConfig.java @@ -1,8 +1,8 @@ package de.caritas.cob.userservice.api.config; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Positive; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Positive; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/de/caritas/cob/userservice/api/config/BeanAwareSpringLiquibase.java b/src/main/java/de/caritas/cob/userservice/api/config/BeanAwareSpringLiquibase.java index 1ce306d90..fa297ed96 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/BeanAwareSpringLiquibase.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/BeanAwareSpringLiquibase.java @@ -11,8 +11,8 @@ public class BeanAwareSpringLiquibase extends SpringLiquibase { private static ResourceLoader applicationContext; public static T getBean(Class beanClass) throws InstantiationException { - if (applicationContext instanceof ApplicationContext) { - return ((ApplicationContext) applicationContext).getBean(beanClass); + if (applicationContext instanceof ApplicationContext context) { + return context.getBean(beanClass); } else { throw new InstantiationException("Resource loader is not an instance of ApplicationContext"); } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/CacheManagerConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/CacheManagerConfig.java index ead53328d..c83ec5d4d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/CacheManagerConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/CacheManagerConfig.java @@ -2,9 +2,7 @@ import net.sf.ehcache.config.CacheConfiguration; import org.springframework.beans.factory.annotation.Value; -import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; -import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -94,13 +92,8 @@ public class CacheManagerConfig { @Value("${cache.rocketchat.configuration.timeToLiveSeconds}") private long rocketchatCacheTimeToLiveSeconds; - @Bean - public CacheManager cacheManager() { - return new EhCacheCacheManager(ehCacheManager()); - } - @Bean(destroyMethod = "shutdown") - public net.sf.ehcache.CacheManager ehCacheManager() { + net.sf.ehcache.CacheManager ehCacheManager() { var config = new net.sf.ehcache.config.Configuration(); config.addCache(buildAgencyCacheConfiguration()); config.addCache(buildConsultingTypeCacheConfiguration()); diff --git a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java index fe19a6ed1..80033efe4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java @@ -11,12 +11,12 @@ import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.access.vote.AuthenticatedVoter; import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; import org.springframework.security.config.core.GrantedAuthorityDefaults; @Configuration -@EnableGlobalMethodSecurity(securedEnabled = true) +@EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override @@ -32,7 +32,7 @@ protected AccessDecisionManager accessDecisionManager() { } @Bean - public GrantedAuthorityDefaults grantedAuthorityDefaults() { + GrantedAuthorityDefaults grantedAuthorityDefaults() { return new GrantedAuthorityDefaults(AuthorityValue.PREFIX); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java index 1efc45e3b..58b51d81a 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/LiquibaseConfig.java @@ -14,7 +14,7 @@ public class LiquibaseConfig { @Bean - public SpringLiquibase liquibase(DataSource dataSource, LiquibaseProperties liquibaseProperties) { + SpringLiquibase liquibase(DataSource dataSource, LiquibaseProperties liquibaseProperties) { var liquibase = new BeanAwareSpringLiquibase(); liquibase.setContexts(liquibaseProperties.getContexts()); diff --git a/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java index 02f620b00..437044891 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/SwaggerConfig.java @@ -12,7 +12,7 @@ public class SwaggerConfig { @Bean - public LinkDiscoverers discoverers() { + LinkDiscoverers discoverers() { List plugins = new ArrayList<>(); plugins.add(new org.springframework.hateoas.mediatype.hal.HalLinkDiscoverer()); return new LinkDiscoverers(SimplePluginRegistry.create(plugins)); diff --git a/src/main/java/de/caritas/cob/userservice/api/config/VideoChatConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/VideoChatConfig.java index de880cd57..6c6ff0505 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/VideoChatConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/VideoChatConfig.java @@ -1,6 +1,6 @@ package de.caritas.cob.userservice.api.config; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/AgencyServiceApiClientConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/AgencyServiceApiClientConfig.java index aa93ff3d3..e0d40a662 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/AgencyServiceApiClientConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/AgencyServiceApiClientConfig.java @@ -23,7 +23,7 @@ public class AgencyServiceApiClientConfig { * @return the AgencyService controller {@link AgencyControllerApi} */ @Bean - public AgencyControllerApi agencyControllerApi(ApiClient apiClient) { + AgencyControllerApi agencyControllerApi(ApiClient apiClient) { return new AgencyControllerApi(apiClient); } @@ -36,7 +36,7 @@ public AgencyControllerApi agencyControllerApi(ApiClient apiClient) { @Bean @Primary @Scope("prototype") - public ApiClient agencyApiClient(RestTemplate restTemplate) { + ApiClient agencyApiClient(RestTemplate restTemplate) { return new ApiClient(restTemplate).setBasePath(this.agencyServiceApiUrl); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/ApplicationSettingsApiClient.java b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/ApplicationSettingsApiClient.java index 131ce2442..c7082f037 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/ApplicationSettingsApiClient.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/ApplicationSettingsApiClient.java @@ -62,8 +62,7 @@ private MultiValueMap obtainQueryParameters(Object queryValue) { } catch (IntrospectionException exception) { throw new InternalServerErrorException( - String.format("Could not obtain method properties of %s", queryValue.toString()), - exception); + "Could not obtain method properties of %s".formatted(queryValue.toString()), exception); } } @@ -76,7 +75,7 @@ private void setMethodKeyValuePairs( } } catch (Exception exception) { throw new InternalServerErrorException( - String.format("Could not obtain method key value pairs of %s", queryValue.toString()), + "Could not obtain method key value pairs of %s".formatted(queryValue.toString()), exception); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TenantServiceHelper.java b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TenantServiceHelper.java index 08fe3d399..d0d090776 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TenantServiceHelper.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TenantServiceHelper.java @@ -37,8 +37,7 @@ public static MultiValueMap obtainQueryParameters(Object queryVa } catch (IntrospectionException exception) { throw new InternalServerErrorException( - String.format("Could not obtain method properties of %s", queryValue.toString()), - exception); + "Could not obtain method properties of %s".formatted(queryValue.toString()), exception); } } @@ -51,7 +50,7 @@ private static void setMethodKeyValuePairs( } } catch (Exception exception) { throw new InternalServerErrorException( - String.format("Could not obtain method key value pairs of %s", queryValue.toString()), + "Could not obtain method key value pairs of %s".formatted(queryValue.toString()), exception); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TopicServiceApiClient.java b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TopicServiceApiClient.java index 37c542b6f..c0577faf7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TopicServiceApiClient.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/apiclient/TopicServiceApiClient.java @@ -62,8 +62,7 @@ private MultiValueMap obtainQueryParameters(Object queryValue) { } catch (IntrospectionException exception) { throw new InternalServerErrorException( - String.format("Could not obtain method properties of %s", queryValue.toString()), - exception); + "Could not obtain method properties of %s".formatted(queryValue.toString()), exception); } } @@ -76,7 +75,7 @@ private void setMethodKeyValuePairs( } } catch (Exception exception) { throw new InternalServerErrorException( - String.format("Could not obtain method key value pairs of %s", queryValue.toString()), + "Could not obtain method key value pairs of %s".formatted(queryValue.toString()), exception); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/IdentityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/IdentityConfig.java index 98e7e3365..ac4677e80 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/IdentityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/IdentityConfig.java @@ -1,11 +1,11 @@ package de.caritas.cob.userservice.api.config.auth; import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; import java.util.Arrays; import java.util.Set; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; import lombok.Data; import org.hibernate.validator.constraints.URL; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapper.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapper.java index 24f1eb5fd..256a9646b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapper.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapper.java @@ -25,11 +25,10 @@ public Collection mapAuthorities( return mapAuthorities(roleNames); } - private Set mapAuthorities(Set roleNames) { + public Set mapAuthorities(Set roleNames) { return roleNames.parallelStream() .map(UserRole::getRoleByValue) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(Optional::stream) .map(Authority::getAuthoritiesByUserRole) .flatMap(Collection::parallelStream) .map(SimpleGrantedAuthority::new) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 1d470a71c..0da8cd4b4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -5,29 +5,36 @@ import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.HttpTenantFilter; import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.StatelessCsrfFilter; import de.caritas.cob.userservice.api.config.CsrfSecurityProperties; +import de.caritas.cob.userservice.api.service.security.AuthorisationService; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverter; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; +import lombok.RequiredArgsConstructor; import org.keycloak.adapters.springsecurity.KeycloakConfiguration; import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory; -import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; -import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter; -import org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter; -import org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; import org.springframework.lang.Nullable; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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.http.SessionCreationPolicy; -import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; -import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.csrf.CsrfFilter; +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** Provides the Keycloak/Spring Security configuration. */ +@Configuration @KeycloakConfiguration -public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { +@EnableMethodSecurity +@EnableWebSecurity +@RequiredArgsConstructor +public class SecurityConfig implements WebMvcConfigurer { private static final String UUID_PATTERN = "\\b[0-9a-f]{8}\\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\\b[0-9a-f]{12}\\b"; @@ -38,6 +45,17 @@ public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { private final CsrfSecurityProperties csrfSecurityProperties; + @Autowired AuthorisationService authorisationService; + @Autowired JwtAuthConverterProperties jwtAuthConverterProperties; + + @Value("${csrf.cookie.property}") + private String csrfCookieProperty; + + @Value("${csrf.header.property}") + private String csrfHeaderProperty; + + @Autowired private Environment environment; + @Value("${multitenancy.enabled}") private boolean multitenancy; @@ -62,170 +80,182 @@ public SecurityConfig( * custom {@link StatelessCsrfFilter}, set all sessions to be fully stateless, define necessary * Keycloak roles for specific REST API paths */ - @Override - @SuppressWarnings("java:S4502") // Disabling CSRF protections is security-sensitive - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); + @Bean + @SuppressWarnings("java:S4502") + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { var httpSecurity = - http.csrf() - .disable() + http.csrf(csrf -> csrf.disable()) .addFilterBefore(new StatelessCsrfFilter(csrfSecurityProperties), CsrfFilter.class); httpSecurity = enableTenantFilterIfMultitenancyEnabled(httpSecurity); httpSecurity - .sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .sessionAuthenticationStrategy(sessionAuthenticationStrategy()) - .and() - .authorizeRequests() - .antMatchers(csrfSecurityProperties.getWhitelist().getConfigUris()) - .permitAll() - .antMatchers( - "/users/askers/new", - "/conversations/askers/anonymous/new", - "/users/consultants/{consultantId:" + UUID_PATTERN + "}", - "/users/consultants/languages") - .permitAll() - .antMatchers(HttpMethod.GET, "/conversations/anonymous/{sessionId:[0-9]+}") - .hasAnyAuthority(ANONYMOUS_DEFAULT) - .antMatchers("/users/notifications") - .hasAnyAuthority(NOTIFICATIONS_TECHNICAL) - .antMatchers("/users/data") - .hasAnyAuthority( - ANONYMOUS_DEFAULT, - USER_DEFAULT, - CONSULTANT_DEFAULT, - SINGLE_TENANT_ADMIN, - TENANT_ADMIN, - RESTRICTED_AGENCY_ADMIN) - .antMatchers(HttpMethod.GET, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") - .permitAll() - .antMatchers("/users/sessions/askers") - .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT) - .antMatchers( - "/users/email", - "/users/mails/messages/new", - "/users/chat/{chatId:[0-9]+}", - "/users/chat/e2e", - "/users/chat/{chatId:[0-9]+}/join", - "/users/chat/{chatId:[0-9]+}/members", - "/users/chat/{chatId:[0-9]+}/leave", - "/users/chat/{groupId:[\\dA-Za-z-,]+}/assign", - "/users/consultants/toggleWalkThrough") - .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) - .antMatchers("/users/chat/{chatId:[0-9]+}/verify") - .hasAnyAuthority(CONSULTANT_DEFAULT) - .antMatchers("/users/password/change") - .hasAnyAuthority( - USER_DEFAULT, - CONSULTANT_DEFAULT, - SINGLE_TENANT_ADMIN, - TENANT_ADMIN, - RESTRICTED_AGENCY_ADMIN) - .antMatchers("/users/twoFactorAuth", "/users/2fa/**", "/users/mobile/app/token") - .hasAnyAuthority( - SINGLE_TENANT_ADMIN, - TENANT_ADMIN, - USER_DEFAULT, - CONSULTANT_DEFAULT, - RESTRICTED_AGENCY_ADMIN) - .antMatchers("/users/statistics/registration") - .hasAnyAuthority(SINGLE_TENANT_ADMIN, TENANT_ADMIN) - .antMatchers( - "/users/sessions/{sessionId:[0-9]+}/enquiry/new", - "/appointments/sessions/{sessionId:[0-9]+}/enquiry/new", - "/users/askers/consultingType/new", - "/users/account", - "/users/mobiletoken", - "/users/sessions/{sessionId:[0-9]+}/data") - .hasAuthority(USER_DEFAULT) - .regexMatchers(HttpMethod.GET, "/users/sessions/room\\?rcGroupIds=[\\dA-Za-z-,]+") - .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT, CONSULTANT_DEFAULT) - .antMatchers(HttpMethod.GET, "/users/sessions/room/{sessionId:[0-9]+}") - .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT, CONSULTANT_DEFAULT) - .antMatchers(HttpMethod.GET, "/users/chat/room/{chatId:[0-9]+}") - .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) - .antMatchers( - "/users/sessions/open", - "/users/sessions/consultants/new", - "/users/sessions/new/{sessionId:[0-9]+}", - "/users/consultants/absences", - "/users/sessions/consultants", - "/users/sessions/teams", - "/conversations/askers/anonymous/{sessionId:[0-9]+}/accept", - "/conversations/consultants/**") - .hasAuthority(CONSULTANT_DEFAULT) - .antMatchers("/conversations/anonymous/{sessionId:[0-9]+}/finish") - .hasAnyAuthority(CONSULTANT_DEFAULT, ANONYMOUS_DEFAULT) - .antMatchers("/users/sessions/{sessionId:[0-9]+}/consultant/{consultantId:[0-9A-Za-z-]+}") - .hasAnyAuthority(ASSIGN_CONSULTANT_TO_ENQUIRY, ASSIGN_CONSULTANT_TO_SESSION) - .antMatchers("/users/consultants") - .hasAuthority(VIEW_AGENCY_CONSULTANTS) - .antMatchers( - "/users/consultants/import", - "/users/askers/import", - "/users/askersWithoutSession/import", - "/users/sessions/rocketChatGroupId") - .hasAuthority(TECHNICAL_DEFAULT) - .antMatchers("/liveproxy/send") - .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT, ANONYMOUS_DEFAULT) - .antMatchers("/users/mails/messages/feedback/new") - .hasAuthority(USE_FEEDBACK) - .antMatchers("/users/messages/key") - .hasAuthority(TECHNICAL_DEFAULT) - .antMatchers("/users/chat/new", "/users/chat/v2/new") - .hasAuthority(CREATE_NEW_CHAT) - .antMatchers("/users/chat/{chatId:[0-9]+}/start") - .hasAuthority(START_CHAT) - .antMatchers("/users/chat/{chatId:[0-9]+}/stop") - .hasAuthority(STOP_CHAT) - .antMatchers( - "/users/chat/{chatId:[0-9]+}/update", - "/users/{chatUserId:[0-9A-Za-z]+}/chat/{chatId:[0-9]+}/ban") - .hasAuthority(UPDATE_CHAT) - .antMatchers("/useradmin/tenantadmins/", "/useradmin/tenantadmins/**") - .hasAuthority(TENANT_ADMIN) - .antMatchers("/useradmin/data/*") - .hasAnyAuthority(SINGLE_TENANT_ADMIN, RESTRICTED_AGENCY_ADMIN) - .antMatchers(HttpMethod.POST, "/useradmin/consultants/") - .hasAnyAuthority(CONSULTANT_CREATE, TECHNICAL_DEFAULT) - .antMatchers(HttpMethod.PUT, "/useradmin/consultants/{consultantId:" + UUID_PATTERN + "}") - .hasAnyAuthority(CONSULTANT_UPDATE, TECHNICAL_DEFAULT) - .antMatchers( - HttpMethod.PUT, "/useradmin/consultants/{consultantId:" + UUID_PATTERN + "}/agencies") - .hasAnyAuthority(CONSULTANT_UPDATE, TECHNICAL_DEFAULT) - .antMatchers("/useradmin", "/useradmin/**") - .hasAnyAuthority(USER_ADMIN, TECHNICAL_DEFAULT) - .antMatchers("/users/consultants/search") - .hasAnyAuthority(USER_ADMIN, TECHNICAL_DEFAULT) - .antMatchers( - "/users/consultants/sessions/{sessionId:[0-9]+}", - "/users/sessions/{sessionId:[0-9]+}/archive", - "/users/sessions/{sessionId:[0-9]+}") - .hasAnyAuthority(CONSULTANT_DEFAULT) - .antMatchers("/appointments") - .hasAnyAuthority(CONSULTANT_DEFAULT, TECHNICAL_DEFAULT) - .antMatchers("/appointments/booking/{id:[0-9]+}") - .hasAnyAuthority(CONSULTANT_DEFAULT, TECHNICAL_DEFAULT) - .antMatchers(HttpMethod.PUT, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") - .hasAuthority(CONSULTANT_DEFAULT) - .antMatchers(HttpMethod.DELETE, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") - .hasAuthority(CONSULTANT_DEFAULT) - .antMatchers("/users/sessions/{sessionId:[0-9]+}/dearchive", "/users/mails/reassignment") - .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) - .antMatchers("/userstatistics", "/userstatistics/**") - .permitAll() - .antMatchers(HttpMethod.DELETE, "/useradmin/consultants/{consultantId:[0-9]+}/delete") - .hasAnyAuthority(USER_ADMIN, RESTRICTED_AGENCY_ADMIN) - .antMatchers(HttpMethod.GET, "/actuator/health") - .permitAll() - .antMatchers(HttpMethod.GET, "/actuator/health/*") - .permitAll() - .mvcMatchers(HttpMethod.GET, "/users/{username}") - .permitAll() - .anyRequest() - .denyAll(); + .sessionManagement( + management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests( + requests -> + requests + .requestMatchers(csrfSecurityProperties.getWhitelist().getConfigUris()) + .permitAll() + .requestMatchers( + "/users/askers/new", + "/conversations/askers/anonymous/new", + "/users/consultants/{consultantId:" + UUID_PATTERN + "}", + "/users/consultants/languages") + .permitAll() + .requestMatchers(HttpMethod.GET, "/conversations/anonymous/{sessionId:[0-9]+}") + .hasAnyAuthority(ANONYMOUS_DEFAULT) + .requestMatchers("/users/notifications") + .hasAnyAuthority(NOTIFICATIONS_TECHNICAL) + .requestMatchers("/users/data") + .hasAnyAuthority( + ANONYMOUS_DEFAULT, + USER_DEFAULT, + CONSULTANT_DEFAULT, + SINGLE_TENANT_ADMIN, + TENANT_ADMIN, + RESTRICTED_AGENCY_ADMIN) + .requestMatchers( + HttpMethod.GET, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") + .permitAll() + .requestMatchers("/users/sessions/askers") + .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT) + .requestMatchers( + "/users/email", + "/users/mails/messages/new", + "/users/chat/{chatId:[0-9]+}", + "/users/chat/e2e", + "/users/chat/{chatId:[0-9]+}/join", + "/users/chat/{chatId:[0-9]+}/members", + "/users/chat/{chatId:[0-9]+}/leave", + "/users/chat/{groupId:[\\dA-Za-z-,]+}/assign", + "/users/consultants/toggleWalkThrough") + .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) + .requestMatchers("/users/chat/{chatId:[0-9]+}/verify") + .hasAnyAuthority(CONSULTANT_DEFAULT) + .requestMatchers("/users/password/change") + .hasAnyAuthority( + USER_DEFAULT, + CONSULTANT_DEFAULT, + SINGLE_TENANT_ADMIN, + TENANT_ADMIN, + RESTRICTED_AGENCY_ADMIN) + .requestMatchers( + "/users/twoFactorAuth", "/users/2fa/**", "/users/mobile/app/token") + .hasAnyAuthority( + SINGLE_TENANT_ADMIN, + TENANT_ADMIN, + USER_DEFAULT, + CONSULTANT_DEFAULT, + RESTRICTED_AGENCY_ADMIN) + .requestMatchers("/users/statistics/registration") + .hasAnyAuthority(SINGLE_TENANT_ADMIN, TENANT_ADMIN) + .requestMatchers( + "/users/sessions/{sessionId:[0-9]+}/enquiry/new", + "/appointments/sessions/{sessionId:[0-9]+}/enquiry/new", + "/users/askers/consultingType/new", + "/users/account", + "/users/mobiletoken", + "/users/sessions/{sessionId:[0-9]+}/data") + .hasAuthority(USER_DEFAULT) + .requestMatchers(HttpMethod.GET, "/users/sessions/room") + .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT, CONSULTANT_DEFAULT) + .requestMatchers(HttpMethod.GET, "/users/sessions/room/{sessionId:[0-9]+}") + .hasAnyAuthority(ANONYMOUS_DEFAULT, USER_DEFAULT, CONSULTANT_DEFAULT) + .requestMatchers(HttpMethod.GET, "/users/chat/room/{chatId:[0-9]+}") + .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) + .requestMatchers( + "/users/sessions/open", + "/users/sessions/consultants/new", + "/users/sessions/new/{sessionId:[0-9]+}", + "/users/consultants/absences", + "/users/sessions/consultants", + "/users/sessions/teams", + "/conversations/askers/anonymous/{sessionId:[0-9]+}/accept", + "/conversations/consultants/**") + .hasAuthority(CONSULTANT_DEFAULT) + .requestMatchers("/conversations/anonymous/{sessionId:[0-9]+}/finish") + .hasAnyAuthority(CONSULTANT_DEFAULT, ANONYMOUS_DEFAULT) + .requestMatchers( + "/users/sessions/{sessionId:[0-9]+}/consultant/{consultantId:[0-9A-Za-z-]+}") + .hasAnyAuthority(ASSIGN_CONSULTANT_TO_ENQUIRY, ASSIGN_CONSULTANT_TO_SESSION) + .requestMatchers("/users/consultants") + .hasAuthority(VIEW_AGENCY_CONSULTANTS) + .requestMatchers( + "/users/consultants/import", + "/users/askers/import", + "/users/askersWithoutSession/import", + "/users/sessions/rocketChatGroupId") + .hasAuthority(TECHNICAL_DEFAULT) + .requestMatchers("/liveproxy/send") + .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT, ANONYMOUS_DEFAULT) + .requestMatchers("/users/mails/messages/feedback/new") + .hasAuthority(USE_FEEDBACK) + .requestMatchers("/users/messages/key") + .hasAuthority(TECHNICAL_DEFAULT) + .requestMatchers("/users/chat/new", "/users/chat/v2/new") + .hasAuthority(CREATE_NEW_CHAT) + .requestMatchers("/users/chat/{chatId:[0-9]+}/start") + .hasAuthority(START_CHAT) + .requestMatchers("/users/chat/{chatId:[0-9]+}/stop") + .hasAuthority(STOP_CHAT) + .requestMatchers( + "/users/chat/{chatId:[0-9]+}/update", + "/users/{chatUserId:[0-9A-Za-z]+}/chat/{chatId:[0-9]+}/ban") + .hasAuthority(UPDATE_CHAT) + .requestMatchers("/useradmin/tenantadmins/", "/useradmin/tenantadmins/**") + .hasAuthority(TENANT_ADMIN) + .requestMatchers("/useradmin/data/*") + .hasAnyAuthority(SINGLE_TENANT_ADMIN, RESTRICTED_AGENCY_ADMIN) + .requestMatchers(HttpMethod.POST, "/useradmin/consultants/") + .hasAnyAuthority(CONSULTANT_CREATE, TECHNICAL_DEFAULT) + .requestMatchers( + HttpMethod.PUT, + "/useradmin/consultants/{consultantId:" + UUID_PATTERN + "}") + .hasAnyAuthority(CONSULTANT_UPDATE, TECHNICAL_DEFAULT) + .requestMatchers( + HttpMethod.PUT, + "/useradmin/consultants/{consultantId:" + UUID_PATTERN + "}/agencies") + .hasAnyAuthority(CONSULTANT_UPDATE, TECHNICAL_DEFAULT) + .requestMatchers("/useradmin", "/useradmin/**") + .hasAnyAuthority(USER_ADMIN, TECHNICAL_DEFAULT) + .requestMatchers("/users/consultants/search") + .hasAnyAuthority(USER_ADMIN, TECHNICAL_DEFAULT) + .requestMatchers( + "/users/consultants/sessions/{sessionId:[0-9]+}", + "/users/sessions/{sessionId:[0-9]+}/archive", + "/users/sessions/{sessionId:[0-9]+}") + .hasAnyAuthority(CONSULTANT_DEFAULT) + .requestMatchers("/appointments") + .hasAnyAuthority(CONSULTANT_DEFAULT, TECHNICAL_DEFAULT) + .requestMatchers("/appointments/booking/{id:[0-9]+}") + .hasAnyAuthority(CONSULTANT_DEFAULT, TECHNICAL_DEFAULT) + .requestMatchers( + HttpMethod.PUT, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") + .hasAuthority(CONSULTANT_DEFAULT) + .requestMatchers( + HttpMethod.DELETE, APPOINTMENTS_APPOINTMENT_ID + UUID_PATTERN + "}") + .hasAuthority(CONSULTANT_DEFAULT) + .requestMatchers( + "/users/sessions/{sessionId:[0-9]+}/dearchive", "/users/mails/reassignment") + .hasAnyAuthority(USER_DEFAULT, CONSULTANT_DEFAULT) + .requestMatchers("/userstatistics", "/userstatistics/**") + .permitAll() + .requestMatchers( + HttpMethod.DELETE, "/useradmin/consultants/{consultantId:[0-9]+}/delete") + .hasAnyAuthority(USER_ADMIN, RESTRICTED_AGENCY_ADMIN) + .requestMatchers(HttpMethod.GET, "/actuator/health") + .permitAll() + .requestMatchers(HttpMethod.GET, "/actuator/health/*") + .permitAll() + .requestMatchers(HttpMethod.GET, "/users/{username}") + .permitAll() + .anyRequest() + .denyAll()); + + httpSecurity.oauth2ResourceServer( + server -> server.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter()))); + return httpSecurity.build(); } /** @@ -242,85 +272,18 @@ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSe return httpSecurity; } - /** Change springs authentication strategy to be stateless (no session is being created). */ - @Bean - @Override - protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { - return new NullAuthenticatedSessionStrategy(); - } - /** - * Change the default AuthenticationProvider to KeycloakAuthenticationProvider and register it in - * the spring security context. Set the GrantedAuthoritiesMapper to map the Keycloak roles to the - * granted authorities. + * Configure trailing slash match for all endpoints (needed as Spring Boot 3.0.0 changed default + * behaviour for trailing slash match) https://www.baeldung.com/spring-boot-3-migration (section + * 3.1) */ - @Autowired - public void configureGlobal( - final AuthenticationManagerBuilder auth, RoleAuthorizationAuthorityMapper authorityMapper) { - var keyCloakAuthProvider = keycloakAuthenticationProvider(); - keyCloakAuthProvider.setGrantedAuthoritiesMapper(authorityMapper); - auth.authenticationProvider(keyCloakAuthProvider); - } - - /** - * From the Keycloak documentation: "Spring Boot attempts to eagerly register filter beans with - * the web application context. Therefore, when running the Keycloak Spring Security adapter in a - * Spring Boot environment, it may be necessary to add FilterRegistrationBeans to your security - * configuration to prevent the Keycloak filters from being registered twice." - * - *

https://github.com/keycloak/keycloak-documentation/blob/master/securing_apps/topics/oidc/java/spring-security-adapter.adoc - * - * @param filter {@link KeycloakAuthenticationProcessingFilter} - * @return {@link FilterRegistrationBean} - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @Bean - public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean( - KeycloakAuthenticationProcessingFilter filter) { - var registrationBean = new FilterRegistrationBean(filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - /** - * see above: - * {@link - * SecurityConfig#keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter) - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @Bean - public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean( - KeycloakPreAuthActionsFilter filter) { - var registrationBean = new FilterRegistrationBean(filter); - registrationBean.setEnabled(false); - return registrationBean; - } - - /** - * see above: - * {@link - * SecurityConfig#keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter) - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @Bean - public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean( - KeycloakAuthenticatedActionsFilter filter) { - var registrationBean = new FilterRegistrationBean(filter); - registrationBean.setEnabled(false); - return registrationBean; + @Override + public void configurePathMatch(PathMatchConfigurer configurer) { + configurer.setUseTrailingSlashMatch(true); } - /** - * see above: - * {@link - * SecurityConfig#keycloakAuthenticationProcessingFilterRegistrationBean(KeycloakAuthenticationProcessingFilter) - */ - @SuppressWarnings({"rawtypes", "unchecked"}) @Bean - public FilterRegistrationBean keycloakSecurityContextRequestFilterBean( - KeycloakSecurityContextRequestFilter filter) { - var registrationBean = new FilterRegistrationBean(filter); - registrationBean.setEnabled(false); - return registrationBean; + JwtAuthConverter jwtAuthConverter() { + return new JwtAuthConverter(jwtAuthConverterProperties, authorisationService); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/TechnicalUserConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/TechnicalUserConfig.java index b00280752..ce1523e34 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/TechnicalUserConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/TechnicalUserConfig.java @@ -1,6 +1,6 @@ package de.caritas.cob.userservice.api.config.auth; -import javax.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotBlank; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/UserRole.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/UserRole.java index 9ece84b32..79c50aad7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/UserRole.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/UserRole.java @@ -2,10 +2,8 @@ import java.util.Arrays; import java.util.Optional; -import lombok.AllArgsConstructor; import lombok.Getter; -@AllArgsConstructor @Getter public enum UserRole { ANONYMOUS("anonymous"), @@ -26,6 +24,10 @@ public enum UserRole { private final String value; + UserRole(String value) { + this.value = value; + } + public static Optional getRoleByValue(String value) { return Arrays.stream(values()).filter(userRole -> userRole.value.equals(value)).findFirst(); } diff --git a/src/main/java/de/caritas/cob/userservice/api/conversation/service/ConversationListResolver.java b/src/main/java/de/caritas/cob/userservice/api/conversation/service/ConversationListResolver.java index c9e1ccd2e..51c8e6c45 100644 --- a/src/main/java/de/caritas/cob/userservice/api/conversation/service/ConversationListResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/conversation/service/ConversationListResolver.java @@ -40,7 +40,7 @@ public ConsultantSessionListResponseDTO resolveConversations( } var exceptionMessage = - String.format("No sessions found for parameters offset=%s, count=%s", offset, count); + "No sessions found for parameters offset=%s, count=%s".formatted(offset, count); throw new NoContentException(exceptionMessage); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/CreateEnquiryException.java b/src/main/java/de/caritas/cob/userservice/api/exception/CreateEnquiryException.java index e89be259f..62333e601 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/CreateEnquiryException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/CreateEnquiryException.java @@ -1,6 +1,7 @@ package de.caritas.cob.userservice.api.exception; import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; +import java.io.Serial; import lombok.Getter; import lombok.Setter; @@ -8,7 +9,7 @@ @Setter public class CreateEnquiryException extends Exception { - private static final long serialVersionUID = -4322443849222920981L; + @Serial private static final long serialVersionUID = -4322443849222920981L; private CreateEnquiryExceptionInformation exceptionInformation; /** diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/CustomCryptoException.java b/src/main/java/de/caritas/cob/userservice/api/exception/CustomCryptoException.java index a846ae488..abe884ed7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/CustomCryptoException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/CustomCryptoException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class CustomCryptoException extends Exception { - private static final long serialVersionUID = 1232112575979020932L; + @Serial private static final long serialVersionUID = 1232112575979020932L; /** * Exception when something with the encryption goes wrong diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/EmailNotificationException.java b/src/main/java/de/caritas/cob/userservice/api/exception/EmailNotificationException.java index 48fc522a8..9ef0c82de 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/EmailNotificationException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/EmailNotificationException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class EmailNotificationException extends RuntimeException { - private static final long serialVersionUID = -2260264511268139498L; + @Serial private static final long serialVersionUID = -2260264511268139498L; /** * E-mail notification exception diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/HelperException.java b/src/main/java/de/caritas/cob/userservice/api/exception/HelperException.java index 0925d025e..12aedd16b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/HelperException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/HelperException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class HelperException extends RuntimeException { - private static final long serialVersionUID = -1321906171569622899L; + @Serial private static final long serialVersionUID = -1321906171569622899L; /** Exception for helper errors */ public HelperException(String message, Exception exception) { diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/ImportException.java b/src/main/java/de/caritas/cob/userservice/api/exception/ImportException.java index 66ff4e56c..05ebe74c4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/ImportException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/ImportException.java @@ -1,9 +1,11 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class ImportException extends RuntimeException { /** Exception for import errors */ - private static final long serialVersionUID = -4222451820639535874L; + @Serial private static final long serialVersionUID = -4222451820639535874L; public ImportException(String message) { super(message); diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/MessageHasAlreadyBeenSavedException.java b/src/main/java/de/caritas/cob/userservice/api/exception/MessageHasAlreadyBeenSavedException.java index 07be84b6c..1845392d6 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/MessageHasAlreadyBeenSavedException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/MessageHasAlreadyBeenSavedException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class MessageHasAlreadyBeenSavedException extends Exception { - private static final long serialVersionUID = 3067609195162892096L; + @Serial private static final long serialVersionUID = 3067609195162892096L; /** * Enquiry message conflict exception. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/MissingConsultingTypeException.java b/src/main/java/de/caritas/cob/userservice/api/exception/MissingConsultingTypeException.java index 445e04d3d..beec1ea06 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/MissingConsultingTypeException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/MissingConsultingTypeException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class MissingConsultingTypeException extends RuntimeException { - private static final long serialVersionUID = -6127271234647444277L; + @Serial private static final long serialVersionUID = -6127271234647444277L; /** * Exception, when settings for an requested consulting type are missing diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/NewMessageNotificationException.java b/src/main/java/de/caritas/cob/userservice/api/exception/NewMessageNotificationException.java index 021b8c938..689281bcc 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/NewMessageNotificationException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/NewMessageNotificationException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class NewMessageNotificationException extends RuntimeException { - private static final long serialVersionUID = 5573541126570935402L; + @Serial private static final long serialVersionUID = 5573541126570935402L; /** * New message notification exception diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/NoMasterKeyException.java b/src/main/java/de/caritas/cob/userservice/api/exception/NoMasterKeyException.java index 247e47c62..977ea55f4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/NoMasterKeyException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/NoMasterKeyException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class NoMasterKeyException extends RuntimeException { - private static final long serialVersionUID = 362702101121444833L; + @Serial private static final long serialVersionUID = 362702101121444833L; /** * Exception, when no master key is set diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/NoUserSessionException.java b/src/main/java/de/caritas/cob/userservice/api/exception/NoUserSessionException.java index f4d65937a..b002f8119 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/NoUserSessionException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/NoUserSessionException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class NoUserSessionException extends Exception { - private static final long serialVersionUID = -5465524493469707522L; + @Serial private static final long serialVersionUID = -5465524493469707522L; /** * Exception for enquiry message, when no user session is available. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/UpdateFeedbackGroupIdException.java b/src/main/java/de/caritas/cob/userservice/api/exception/UpdateFeedbackGroupIdException.java index 62744a78b..9d69c6e3d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/UpdateFeedbackGroupIdException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/UpdateFeedbackGroupIdException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class UpdateFeedbackGroupIdException extends Exception { - private static final long serialVersionUID = -6538582440490471213L; + @Serial private static final long serialVersionUID = -6538582440490471213L; /** * Exception when the update of the feedback group id of a session fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/UpdateSessionException.java b/src/main/java/de/caritas/cob/userservice/api/exception/UpdateSessionException.java index 7655ab371..6e7bb0946 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/UpdateSessionException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/UpdateSessionException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception; +import java.io.Serial; + public class UpdateSessionException extends Exception { - private static final long serialVersionUID = -3666710126372746391L; + @Serial private static final long serialVersionUID = -3666710126372746391L; /** * Exception when update of session fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/BadRequestException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/BadRequestException.java index 9d94a9fe6..544ce7d7c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/BadRequestException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/BadRequestException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.httpresponses; +import java.io.Serial; + public class BadRequestException extends RuntimeException { - private static final long serialVersionUID = -3553609955386498237L; + @Serial private static final long serialVersionUID = -3553609955386498237L; public BadRequestException(String message) { super(message); diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ConflictException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ConflictException.java index 6ef4c62fa..cd5e1356f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ConflictException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ConflictException.java @@ -1,11 +1,12 @@ package de.caritas.cob.userservice.api.exception.httpresponses; import de.caritas.cob.userservice.api.service.LogService; +import java.io.Serial; import java.util.function.Consumer; public class ConflictException extends CustomHttpStatusException { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; /** * Conflict exception. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/CreateEnquiryMessageException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/CreateEnquiryMessageException.java index 63a0a9fad..5cf2a3566 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/CreateEnquiryMessageException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/CreateEnquiryMessageException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.httpresponses; +import java.io.Serial; + public class CreateEnquiryMessageException extends RuntimeException { - private static final long serialVersionUID = -3553609955386498237L; + @Serial private static final long serialVersionUID = -3553609955386498237L; public CreateEnquiryMessageException(String message) { super(message); diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ForbiddenException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ForbiddenException.java index 52913a602..d99bbac36 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ForbiddenException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/ForbiddenException.java @@ -1,11 +1,12 @@ package de.caritas.cob.userservice.api.exception.httpresponses; import de.caritas.cob.userservice.api.service.LogService; +import java.io.Serial; import java.util.function.Consumer; public class ForbiddenException extends CustomHttpStatusException { - private static final long serialVersionUID = 7560597708504748234L; + @Serial private static final long serialVersionUID = 7560597708504748234L; /** * Forbidden exception. @@ -17,7 +18,7 @@ public ForbiddenException(String message) { } public ForbiddenException(String message, Long arg) { - this(String.format(message, arg)); + this(message.formatted(arg)); } /** diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NoContentException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NoContentException.java index 89cb09de0..25b760ea9 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NoContentException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NoContentException.java @@ -1,10 +1,11 @@ package de.caritas.cob.userservice.api.exception.httpresponses; import de.caritas.cob.userservice.api.service.LogService; +import java.io.Serial; public class NoContentException extends CustomHttpStatusException { - private static final long serialVersionUID = -4160810917274267137L; + @Serial private static final long serialVersionUID = -4160810917274267137L; /** * No content exception. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NotFoundException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NotFoundException.java index 6109f780a..3b14a82c3 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NotFoundException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/NotFoundException.java @@ -1,11 +1,12 @@ package de.caritas.cob.userservice.api.exception.httpresponses; import de.caritas.cob.userservice.api.service.LogService; +import java.io.Serial; import java.util.function.Consumer; public class NotFoundException extends CustomHttpStatusException { - private static final long serialVersionUID = -4160810917274267037L; + @Serial private static final long serialVersionUID = -4160810917274267037L; /** * Not found exception. @@ -17,19 +18,19 @@ public NotFoundException(String message) { } public NotFoundException(String message, String arg) { - super(String.format(message, arg), LogService::logWarn); + super(message.formatted(arg), LogService::logWarn); } public NotFoundException(String message, Long arg) { - super(String.format(message, arg), LogService::logWarn); + super(message.formatted(arg), LogService::logWarn); } public NotFoundException(String message, String arg1, Long arg2) { - super(String.format(message, arg1, arg2), LogService::logWarn); + super(message.formatted(arg1, arg2), LogService::logWarn); } public NotFoundException(String message, Long arg1, String arg2) { - super(String.format(message, arg1, arg2), LogService::logWarn); + super(message.formatted(arg1, arg2), LogService::logWarn); } /** diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/RocketChatUnauthorizedException.java b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/RocketChatUnauthorizedException.java index 3835e9513..601264db3 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/RocketChatUnauthorizedException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/httpresponses/RocketChatUnauthorizedException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.httpresponses; +import java.io.Serial; + public class RocketChatUnauthorizedException extends RuntimeException { - private static final long serialVersionUID = -3553609955386498237L; + @Serial private static final long serialVersionUID = -3553609955386498237L; public RocketChatUnauthorizedException(final String userId, final Throwable exception) { super( diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/keycloak/KeycloakException.java b/src/main/java/de/caritas/cob/userservice/api/exception/keycloak/KeycloakException.java index 006bbf8b3..735df0671 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/keycloak/KeycloakException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/keycloak/KeycloakException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.keycloak; +import java.io.Serial; + public class KeycloakException extends RuntimeException { - private static final long serialVersionUID = -5083156826149548581L; + @Serial private static final long serialVersionUID = -5083156826149548581L; /** * Keycloak 409 Conflict exception diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddConsultantsException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddConsultantsException.java index 7510f2431..1674b9a43 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddConsultantsException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddConsultantsException.java @@ -2,10 +2,11 @@ import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; +import java.io.Serial; public class RocketChatAddConsultantsException extends CreateEnquiryException { - private static final long serialVersionUID = -3027804676762081926L; + @Serial private static final long serialVersionUID = -3027804676762081926L; /** * Exception when adding consultants to a Rocket.Chat group fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddSystemUserException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddSystemUserException.java index 5a55d092c..2de9defa2 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddSystemUserException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddSystemUserException.java @@ -2,10 +2,11 @@ import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; +import java.io.Serial; public class RocketChatAddSystemUserException extends CreateEnquiryException { - private static final long serialVersionUID = -3027804676762081926L; + @Serial private static final long serialVersionUID = -3027804676762081926L; /** * Exception when adding the system user to a Rocket.Chat group fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddUserToGroupException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddUserToGroupException.java index a5055a820..ce0f174c4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddUserToGroupException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatAddUserToGroupException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatAddUserToGroupException extends Exception { - private static final long serialVersionUID = -8314892688280190524L; + @Serial private static final long serialVersionUID = -8314892688280190524L; /** * Exception, when a Rocket.Chat API call to add a user to a group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatCreateGroupException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatCreateGroupException.java index e45e7ff74..7db626547 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatCreateGroupException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatCreateGroupException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatCreateGroupException extends Exception { - private static final long serialVersionUID = -2247287831013110339L; + @Serial private static final long serialVersionUID = -2247287831013110339L; /** * Exception, when a Rocket.Chat API call for group creation fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupMembersException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupMembersException.java index 0290d7876..b9a551704 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupMembersException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupMembersException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatGetGroupMembersException extends Exception { - private static final long serialVersionUID = -6467348860210122736L; + @Serial private static final long serialVersionUID = -6467348860210122736L; /** * Exception, when a Rocket.Chat API call to get group m embers fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupsListAllException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupsListAllException.java index eb7e343fb..4a8b4f0ff 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupsListAllException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetGroupsListAllException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatGetGroupsListAllException extends Exception { - private static final long serialVersionUID = -6467348860210122736L; + @Serial private static final long serialVersionUID = -6467348860210122736L; /** * Exception, when a Rocket.Chat API call to get all groups fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetUserIdException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetUserIdException.java index 97df33444..439b148a9 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetUserIdException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatGetUserIdException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatGetUserIdException extends Exception { - private static final long serialVersionUID = -6467348860210122736L; + @Serial private static final long serialVersionUID = -6467348860210122736L; /** * Exception, when a Rocket.Chat API call to get all groups fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLeaveFromGroupException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLeaveFromGroupException.java index bb6a490b9..1ef93443e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLeaveFromGroupException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLeaveFromGroupException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatLeaveFromGroupException extends Exception { - private static final long serialVersionUID = 2106829666296656057L; + @Serial private static final long serialVersionUID = 2106829666296656057L; /** * Exception, when a Rocket.Chat API call to leave a group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLoginException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLoginException.java index b9661b51c..b14e8be5d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLoginException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatLoginException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatLoginException extends Exception { - private static final long serialVersionUID = 5198347832036308397L; + @Serial private static final long serialVersionUID = 5198347832036308397L; /** * Exception when login for technical user in Rocket.Chat fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostFurtherStepsMessageException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostFurtherStepsMessageException.java index d61661078..930b7ba9f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostFurtherStepsMessageException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostFurtherStepsMessageException.java @@ -2,11 +2,12 @@ import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; +import java.io.Serial; /** Exception when posting a further step message fails. */ public class RocketChatPostFurtherStepsMessageException extends CreateEnquiryException { - private static final long serialVersionUID = -1247285841233110339L; + @Serial private static final long serialVersionUID = -1247285841233110339L; /** * Exception when posting the further steps message to a Rocket.Chat group fails. diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostMessageException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostMessageException.java index 7d5cff735..2715a6410 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostMessageException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostMessageException.java @@ -2,10 +2,11 @@ import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; +import java.io.Serial; public class RocketChatPostMessageException extends CreateEnquiryException { - private static final long serialVersionUID = -2247287831013110339L; + @Serial private static final long serialVersionUID = -2247287831013110339L; /** * Exception when posting a message to a Rocket.Chat group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostWelcomeMessageException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostWelcomeMessageException.java index 1fbd92965..5cceea285 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostWelcomeMessageException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatPostWelcomeMessageException.java @@ -2,10 +2,11 @@ import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; +import java.io.Serial; public class RocketChatPostWelcomeMessageException extends CreateEnquiryException { - private static final long serialVersionUID = -2247287831013110339L; + @Serial private static final long serialVersionUID = -2247287831013110339L; /** * Exception when posting the welcome message to a Rocket.Chat group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveSystemMessagesException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveSystemMessagesException.java index 4f7f3b830..27b2199a6 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveSystemMessagesException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveSystemMessagesException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatRemoveSystemMessagesException extends Exception { - private static final long serialVersionUID = 7966120004575237483L; + @Serial private static final long serialVersionUID = 7966120004575237483L; /** * Exception, when a Rocket.Chat API call to remove system messages of a group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveUserFromGroupException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveUserFromGroupException.java index 183e2118d..477cf7105 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveUserFromGroupException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatRemoveUserFromGroupException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatRemoveUserFromGroupException extends Exception { - private static final long serialVersionUID = 2106829666296656057L; + @Serial private static final long serialVersionUID = 2106829666296656057L; /** * Exception, when a Rocket.Chat API call to remove a user to a group fails diff --git a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatUserNotInitializedException.java b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatUserNotInitializedException.java index 0712dc758..59684b226 100644 --- a/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatUserNotInitializedException.java +++ b/src/main/java/de/caritas/cob/userservice/api/exception/rocketchat/RocketChatUserNotInitializedException.java @@ -1,8 +1,10 @@ package de.caritas.cob.userservice.api.exception.rocketchat; +import java.io.Serial; + public class RocketChatUserNotInitializedException extends Exception { - private static final long serialVersionUID = -6444815503348502528L; + @Serial private static final long serialVersionUID = -6444815503348502528L; public RocketChatUserNotInitializedException(String message) { super(message); diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacade.java index 792ddc4b5..274a52390 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacade.java @@ -272,9 +272,8 @@ private GroupResponseDTO retrieveRcGroupResponseDto( return groupResponseDTO.orElseThrow( () -> new InternalServerErrorException( - String.format( - "Could not create Rocket.Chat room for session %s and Rocket.Chat user %s", - sessionId, rocketChatUserId))); + "Could not create Rocket.Chat room for session %s and Rocket.Chat user %s" + .formatted(sessionId, rocketChatUserId))); } private void addSystemUserToGroup(String rcGroupId) throws RocketChatAddSystemUserException { @@ -283,9 +282,8 @@ private void addSystemUserToGroup(String rcGroupId) throws RocketChatAddSystemUs rocketChatService.addUserToGroup(rocketChatSystemUserId, rcGroupId); } catch (RocketChatAddUserToGroupException rocketChatAddUserToGroupException) { throw new RocketChatAddSystemUserException( - String.format( - "Add system user error: Could not add user with ID %s to Rocket.Chat group %s", - rocketChatSystemUserId, rcGroupId), + "Add system user error: Could not add user with ID %s to Rocket.Chat group %s" + .formatted(rocketChatSystemUserId, rcGroupId), rocketChatAddUserToGroupException, CreateEnquiryExceptionInformation.builder().rcGroupId(rcGroupId).build()); } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/CreateUserFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/CreateUserFacade.java index 23d3049bf..7cf26f1db 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/CreateUserFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/CreateUserFacade.java @@ -150,7 +150,7 @@ private void updateKeycloakRoleAndPassword(String userId, UserDTO userDTO, UserR private void checkIfUserIdNotNull(String userId, UserDTO userDTO) { if (isNull(userId)) { throw new InternalServerErrorException( - String.format("Could not create Keycloak account for: %s", userDTO.toString())); + "Could not create Keycloak account for: %s".formatted(userDTO.toString())); } } @@ -169,6 +169,6 @@ private void rollBackAccountInitialization(String userId, UserDTO userDTO) { .rollBackUserAccount(Boolean.parseBoolean(userDTO.getTermsAccepted())) .build()); throw new InternalServerErrorException( - String.format("Could not update account data on registration for: %s", userDTO)); + "Could not update account data on registration for: %s".formatted(userDTO)); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacade.java index 7f96f8fde..63877733a 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/JoinAndLeaveChatFacade.java @@ -87,7 +87,7 @@ public void leaveChat(Long chatId, AuthenticatedUser authenticatedUser) { private void deleteMessengerChat(String groupId) { if (!rocketChatService.deleteGroupAsSystemUser(groupId)) { - var message = String.format("Could not delete Rocket.Chat group with id %s", groupId); + var message = "Could not delete Rocket.Chat group with id %s".formatted(groupId); throw new InternalServerErrorException(message); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/RocketChatFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/RocketChatFacade.java index 48a30022f..f36968175 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/RocketChatFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/RocketChatFacade.java @@ -40,9 +40,8 @@ public void addUserToRocketChatGroup(String rcUserId, String groupId) { leaveFromGroupAsTechnicalUser(groupId); } catch (RocketChatAddUserToGroupException addUserEx) { var message = - String.format( - "Could not add user with id %s to Rocket.Chat group with id %s. Initiate rollback.", - rcUserId, groupId); + "Could not add user with id %s to Rocket.Chat group with id %s. Initiate rollback." + .formatted(rcUserId, groupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } @@ -61,7 +60,7 @@ public void removeSystemMessagesFromRocketChatGroup(String groupId) { leaveFromGroupAsTechnicalUser(groupId); } catch (RocketChatRemoveSystemMessagesException | RocketChatUserNotInitializedException e) { var message = - String.format("Could not remove system messages from Rocket.Chat group id %s", groupId); + "Could not remove system messages from Rocket.Chat group id %s".formatted(groupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } @@ -83,9 +82,8 @@ public List retrieveRocketChatMembers(String rcGroupId) { return memberList; } catch (Exception exception) { var message = - String.format( - "Could not get Rocket.Chat group members of group id %s. Initiate rollback.", - rcGroupId); + "Could not get Rocket.Chat group members of group id %s. Initiate rollback." + .formatted(rcGroupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } @@ -100,9 +98,8 @@ public void addTechnicalUserToGroup(String groupId) { rocketChatService.addTechnicalUserToGroup(groupId); } catch (RocketChatAddUserToGroupException | RocketChatUserNotInitializedException addUserEx) { var message = - String.format( - "Could not add Rocket.Chat technical user to Rocket.Chat group with id %s. Initiate rollback.", - groupId); + "Could not add Rocket.Chat technical user to Rocket.Chat group with id %s. Initiate rollback." + .formatted(groupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } @@ -117,7 +114,7 @@ public void leaveFromGroupAsTechnicalUser(String groupId) { rocketChatService.leaveFromGroupAsTechnicalUser(groupId); } catch (RocketChatLeaveFromGroupException e) { var message = - String.format("Could not leave from Rocket.Chat group id %s as technical user", groupId); + "Could not leave from Rocket.Chat group id %s as technical user".formatted(groupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } @@ -133,8 +130,8 @@ public void removeUserFromGroup(String rcUserId, String groupId) { this.rocketChatService.removeUserFromGroup(rcUserId, groupId); } catch (RocketChatRemoveUserFromGroupException e) { var message = - String.format( - "Could not remove user with id %s from Rocket.Chat group id %s", rcUserId, groupId); + "Could not remove user with id %s from Rocket.Chat group id %s" + .formatted(rcUserId, groupId); throw new InternalServerErrorException(message, LogService::logInternalServerError); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacade.java index 9983253bb..e418ad466 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacade.java @@ -20,10 +20,10 @@ import de.caritas.cob.userservice.api.tenant.TenantContext; import de.caritas.cob.userservice.api.tenant.TenantContextProvider; import de.caritas.cob.userservice.statisticsservice.generated.web.model.UserRole; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; import java.util.function.Supplier; -import javax.servlet.http.HttpServletRequest; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpHeaders; diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacade.java index d5b56aa1f..e09434b8e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacade.java @@ -24,10 +24,10 @@ import de.caritas.cob.userservice.api.tenant.TenantContext; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; import de.caritas.cob.userservice.statisticsservice.generated.web.model.UserRole; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.constraints.NotNull; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.validation.constraints.NotNull; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProvider.java b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProvider.java index 448399314..e9b58500f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/assignsession/UnauthorizedMembersProvider.java @@ -12,12 +12,12 @@ import de.caritas.cob.userservice.api.model.Session; import de.caritas.cob.userservice.api.port.out.IdentityClient; import de.caritas.cob.userservice.api.service.ConsultantService; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java index 52aa0f360..9a9c426f5 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/sessionlist/SessionListFacade.java @@ -12,6 +12,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionListResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionResponseDTO; import de.caritas.cob.userservice.api.container.SessionListQueryParameter; +import de.caritas.cob.userservice.api.helper.LatestMessageParseUtil; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.Session.SessionStatus; import de.caritas.cob.userservice.api.service.session.SessionFilter; @@ -67,7 +68,7 @@ public UserSessionListResponseDTO retrieveSortedSessionsForAuthenticatedUser( List userSessions = userSessionListService.retrieveSessionsForAuthenticatedUser(userId, rocketChatCredentials); - userSessions.sort(comparing(UserSessionResponseDTO::getLatestMessage).reversed()); + userSessions.sort(comparing(LatestMessageParseUtil::parseLatestMessage).reversed()); return new UserSessionListResponseDTO().sessions(userSessions); } @@ -90,7 +91,7 @@ public GroupSessionListResponseDTO retrieveSessionsForAuthenticatedUserByGroupId List userSessions = userSessionListService.retrieveSessionsForAuthenticatedUserAndGroupIds( userId, rcGroupIds, rocketChatCredentials, roles); - userSessions.sort(comparing(UserSessionResponseDTO::getLatestMessage).reversed()); + userSessions.sort(comparing(LatestMessageParseUtil::parseLatestMessage).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -119,7 +120,7 @@ public GroupSessionListResponseDTO retrieveSessionsForAuthenticatedUserBySession List userSessions = userSessionListService.retrieveSessionsForAuthenticatedUserAndSessionIds( userId, sessionIds, rocketChatCredentials, roles); - userSessions.sort(comparing(UserSessionResponseDTO::getLatestMessage).reversed()); + userSessions.sort(comparing(LatestMessageParseUtil::parseLatestMessage).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -134,7 +135,7 @@ public GroupSessionListResponseDTO retrieveChatsForUserByChatIds( List chatIds, RocketChatCredentials rocketChatCredentials) { var userChatSessions = userSessionListService.retrieveChatsForUserAndChatIds(chatIds, rocketChatCredentials); - userChatSessions.sort(comparing(UserSessionResponseDTO::getLatestMessage).reversed()); + userChatSessions.sort(comparing(LatestMessageParseUtil::parseLatestMessage).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -156,7 +157,8 @@ public GroupSessionListResponseDTO retrieveSessionsForAuthenticatedConsultantByG List consultantSessions = consultantSessionListService.retrieveSessionsForConsultantAndGroupIds( consultant, rcGroupIds, roles); - consultantSessions.sort(comparing(ConsultantSessionResponseDTO::getLatestMessage).reversed()); + consultantSessions.sort( + comparing(LatestMessageParseUtil::parseLatestMessageForConsultantSession).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -178,7 +180,8 @@ public GroupSessionListResponseDTO retrieveSessionsForAuthenticatedConsultantByS List consultantSessions = consultantSessionListService.retrieveSessionsForConsultantAndSessionIds( consultant, sessionIds, roles); - consultantSessions.sort(comparing(ConsultantSessionResponseDTO::getLatestMessage).reversed()); + consultantSessions.sort( + comparing(LatestMessageParseUtil::parseLatestMessageForConsultantSession).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -195,7 +198,7 @@ public GroupSessionListResponseDTO retrieveChatsForConsultantByChatIds( consultantSessionListService.retrieveChatsForConsultantAndChatIds( consultant, chatIds, rocketChatCredentials.getRocketChatToken()); consultantChatSessions.sort( - comparing(ConsultantSessionResponseDTO::getLatestMessage).reversed()); + comparing(LatestMessageParseUtil::parseLatestMessageForConsultantSession).reversed()); SessionMapper sessionMapper = new SessionMapper(); var sessions = @@ -326,7 +329,8 @@ public ConsultantSessionListResponseDTO retrieveTeamSessionsDtoForAuthenticatedC } private void sortSessionsByLastMessageDateDesc(List sessions) { - sessions.sort(comparing(ConsultantSessionResponseDTO::getLatestMessage).reversed()); + sessions.sort( + comparing(LatestMessageParseUtil::parseLatestMessageForConsultantSession).reversed()); } private void removeAllChatsAndSessionsWithoutUnreadFeedback( diff --git a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProvider.java b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProvider.java index 2c4c58a95..062be229d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/facade/userdata/ConsultantDataProvider.java @@ -45,7 +45,8 @@ public class ConsultantDataProvider { * @param consultant a {@link Consultant} instance * @return the user data */ - public UserDataResponseDTO retrieveData(Consultant consultant) { + public de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO retrieveData( + Consultant consultant) { if (isEmpty(consultant.getConsultantAgencies())) { throw new InternalServerErrorException( String.format("No agency available for consultant %s", consultant.getId())); @@ -58,7 +59,8 @@ private List agencyIdsOf(Set agencies) { return agencies.stream().map(ConsultantAgency::getAgencyId).collect(Collectors.toList()); } - private UserDataResponseDTO userDataResponseDtoOf(Consultant consultant) { + private de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO userDataResponseDtoOf( + Consultant consultant) { return UserDataResponseDTO.builder() .userId(consultant.getId()) diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/AgencyVerifier.java b/src/main/java/de/caritas/cob/userservice/api/helper/AgencyVerifier.java index 4493a167c..aa3c6a11e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/AgencyVerifier.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/AgencyVerifier.java @@ -31,9 +31,8 @@ public AgencyDTO getVerifiedAgency(Long agencyId, int consultingTypeId) { var agencyDTO = agencyService.getAgencyWithoutCaching(agencyId); if (nonNull(agencyDTO) && !agencyDTO.getConsultingType().equals(consultingTypeId)) { throw new BadRequestException( - String.format( - "The provided agency with id %s is not assigned to the provided consulting type %s", - agencyId, consultingTypeId)); + "The provided agency with id %s is not assigned to the provided consulting type %s" + .formatted(agencyId, consultingTypeId)); } return agencyDTO; diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializer.java b/src/main/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializer.java index 57d6bb06e..8f906c956 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializer.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/EmptyObjectSerializer.java @@ -4,11 +4,12 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; +import java.io.Serial; /** Special json serializer for empty objects. Necessary for some Rocket.Chat API calls. */ public class EmptyObjectSerializer extends StdSerializer { - private static final long serialVersionUID = 1L; + @Serial private static final long serialVersionUID = 1L; public EmptyObjectSerializer() { super(Object.class); diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/Helper.java b/src/main/java/de/caritas/cob/userservice/api/helper/Helper.java index 1d06f93e1..8852e41db 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/Helper.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/Helper.java @@ -1,9 +1,9 @@ package de.caritas.cob.userservice.api.helper; +import jakarta.ws.rs.InternalServerErrorException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.Date; -import javax.ws.rs.InternalServerErrorException; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document.OutputSettings; diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java b/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java new file mode 100644 index 000000000..c4930c723 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java @@ -0,0 +1,37 @@ +package de.caritas.cob.userservice.api.helper; + +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.UserSessionResponseDTO; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class LatestMessageParseUtil { + + public static Date parseLatestMessage(UserSessionResponseDTO userSession) { + Object latestMessage = userSession.getLatestMessage(); + return parseLatestMessageObject(latestMessage); + } + + public static Date parseLatestMessageForConsultantSession( + ConsultantSessionResponseDTO userSession) { + Object latestMessage = userSession.getLatestMessage(); + return parseLatestMessageObject(latestMessage); + } + + private static Date parseLatestMessageObject(Object latestMessage) { + if (latestMessage instanceof Date) { + return (Date) latestMessage; + } else if (latestMessage instanceof String) { + try { + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse((String) latestMessage); + } catch (ParseException e) { + log.error("Could not parse timestamp string"); + return null; + } + } + return null; + } +} diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java b/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java index 51390877e..fcc425adf 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/SessionListAnalyser.java @@ -35,7 +35,7 @@ public String prepareMessageForSessionList(String message, String groupId) { return decryptionService.decrypt(message, groupId); } catch (CustomCryptoException cryptoEx) { throw new InternalServerErrorException( - String.format("Could not decrypt message for group id %s", groupId), + "Could not decrypt message for group id %s".formatted(groupId), LogService::logInternalServerError); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManager.java b/src/main/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManager.java index 3a9ff22a8..0c86915b4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManager.java +++ b/src/main/java/de/caritas/cob/userservice/api/manager/consultingtype/ConsultingTypeManager.java @@ -31,7 +31,7 @@ public ExtendedConsultingTypeResponseDTO getConsultingTypeSettings(int consultin return consultingTypeService.getExtendedConsultingTypeResponseDTO(consultingTypeId); } catch (RestClientException ex) { throw new MissingConsultingTypeException( - String.format("No settings for consulting type %s found.", consultingTypeId)); + "No settings for consulting type %s found.".formatted(consultingTypeId)); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java index f66b58096..4c2e55c21 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java @@ -1,16 +1,16 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import java.time.LocalDateTime; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.Table; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -21,10 +21,6 @@ import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.ParamDef; -import org.hibernate.search.annotations.Analyzer; -import org.hibernate.search.annotations.Field; -import org.hibernate.search.annotations.Indexed; -import org.hibernate.search.annotations.SortableField; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @@ -44,11 +40,10 @@ @Setter @ToString @Builder -@Indexed @EntityListeners(AuditingEntityListener.class) @FilterDef( name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = "long")}) + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Admin implements TenantAware { @@ -67,36 +62,26 @@ public enum AdminType { private String id; @Column(name = "tenant_id") - @Field private Long tenantId; @Column(name = "username", updatable = false, nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String username; @Column(name = "first_name", nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String firstName; @Column(name = "last_name", nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String lastName; @Column(name = "email", nullable = false) @Size(max = 255) @NonNull - @Field - @Analyzer(definition = EMAIL_ANALYZER) - @SortableField private String email; @Enumerated(EnumType.STRING) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/AdminAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/AdminAgency.java index cfe9d14e7..882c33f03 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/AdminAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/AdminAgency.java @@ -1,24 +1,23 @@ package de.caritas.cob.userservice.api.model; +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.SequenceGenerator; +import jakarta.persistence.Table; import java.io.Serializable; import java.time.LocalDateTime; 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.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import org.hibernate.search.annotations.Field; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @@ -43,7 +42,6 @@ public class AdminAgency implements Serializable { private Admin admin; @Column(name = "agency_id") - @Field private Long agencyId; @CreatedDate diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Appointment.java b/src/main/java/de/caritas/cob/userservice/api/model/Appointment.java index 23eb868ce..9e73e9ee7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Appointment.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Appointment.java @@ -1,26 +1,25 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import java.time.Instant; import java.util.Objects; import java.util.UUID; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.Hibernate; import org.hibernate.annotations.GenericGenerator; -import org.hibernate.annotations.Type; @Table @Entity @@ -40,7 +39,6 @@ public enum AppointmentStatus { @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") @Column(columnDefinition = "char(36)") - @Type(type = "org.hibernate.type.UUIDCharType") private UUID id; @Column(length = 300) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java index 95cea8a17..13b763d44 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java @@ -2,22 +2,22 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import de.caritas.cob.userservice.api.exception.httpresponses.InternalServerErrorException; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import java.time.LocalDateTime; import java.util.Objects; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -131,7 +131,7 @@ public LocalDateTime nextStart() { if (!ChatInterval.WEEKLY.equals(chatInterval)) { var message = "Repetitive chat with id %s does not have a valid interval."; - throw new InternalServerErrorException(String.format(message, id)); + throw new InternalServerErrorException(message.formatted(id)); } return startDate.plusWeeks(1); diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java index 93ffc5901..e8ca8ffd4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ChatAgency.java @@ -1,15 +1,15 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java index 0e99b4da4..9a284277c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java @@ -1,48 +1,39 @@ package de.caritas.cob.userservice.api.model; -import static de.caritas.cob.userservice.api.model.Consultant.EMAIL_ANALYZER; import static java.util.Objects.isNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.neovisionaries.i18n.LanguageCode; import de.caritas.cob.userservice.mailservice.generated.web.model.Dialect; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; +import jakarta.persistence.Index; +import jakarta.persistence.Lob; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.validation.constraints.Size; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.Lob; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; -import org.apache.lucene.analysis.core.LowerCaseFilterFactory; -import org.apache.lucene.analysis.standard.ClassicTokenizerFactory; import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.ParamDef; import org.hibernate.annotations.Where; -import org.hibernate.search.annotations.Analyzer; -import org.hibernate.search.annotations.AnalyzerDef; -import org.hibernate.search.annotations.Field; -import org.hibernate.search.annotations.Indexed; -import org.hibernate.search.annotations.IndexedEmbedded; -import org.hibernate.search.annotations.SortableField; -import org.hibernate.search.annotations.TokenFilterDef; -import org.hibernate.search.annotations.TokenizerDef; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded; import org.springframework.lang.Nullable; /** Represents a consultant */ @@ -61,15 +52,9 @@ @Setter @Builder @Indexed -@AnalyzerDef( - name = EMAIL_ANALYZER, - tokenizer = @TokenizerDef(factory = ClassicTokenizerFactory.class), - filters = { - @TokenFilterDef(factory = LowerCaseFilterFactory.class), - }) @FilterDef( name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = "long")}) + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Consultant implements TenantAware, NotificationsAware { @@ -89,34 +74,24 @@ public class Consultant implements TenantAware, NotificationsAware { @Column(name = "username", updatable = false, nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String username; @Column(name = "first_name", nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String firstName; @Column(name = "last_name", nullable = false) @Size(max = 255) @NonNull - @Field - @SortableField private String lastName; @Column(name = "email", nullable = false) @Size(max = 255) @NonNull - @Field - @Analyzer(definition = EMAIL_ANALYZER) - @SortableField private String email; @Column(name = "is_absent", nullable = false, columnDefinition = "tinyint") - @Field private boolean absent; @Column(name = "is_team_consultant", nullable = false, columnDefinition = "tinyint") @@ -178,7 +153,6 @@ public class Consultant implements TenantAware, NotificationsAware { private Boolean notifyNewFeedbackMessageFromAdviceSeeker; @Column(name = "tenant_id") - @Field private Long tenantId; @OneToMany(mappedBy = "consultant", cascade = CascadeType.ALL) @@ -186,7 +160,6 @@ public class Consultant implements TenantAware, NotificationsAware { @Column(name = "status", length = 11) @Enumerated(EnumType.STRING) - @Field private ConsultantStatus status = ConsultantStatus.IN_PROGRESS; @Column(name = "walk_through_enabled", columnDefinition = "tinyint", nullable = false) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java index ad2d00ac4..cac6191c1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java @@ -1,18 +1,18 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.time.LocalDateTime; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -21,9 +21,6 @@ import org.hibernate.annotations.Filter; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.ParamDef; -import org.hibernate.search.annotations.Field; -import org.hibernate.search.annotations.FieldBridge; -import org.hibernate.search.bridge.builtin.LongBridge; /** Represents the relation between consultant and agency */ @Entity @@ -35,7 +32,7 @@ @Setter @FilterDef( name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = "long")}) + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class ConsultantAgency implements TenantAware { @@ -53,8 +50,6 @@ public class ConsultantAgency implements TenantAware { private Consultant consultant; @Column(name = "agency_id") - @Field - @FieldBridge(impl = LongBridge.class) private Long agencyId; @Column(name = "create_date") @@ -71,7 +66,6 @@ public class ConsultantAgency implements TenantAware { @Column(name = "status", length = 11) @Enumerated(EnumType.STRING) - @Field private ConsultantAgencyStatus status = ConsultantAgencyStatus.IN_PROGRESS; @Override diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantMobileToken.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantMobileToken.java index de83bdab4..b3b2d6324 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantMobileToken.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantMobileToken.java @@ -1,16 +1,16 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Language.java b/src/main/java/de/caritas/cob/userservice/api/model/Language.java index 29c1a35c1..bb277e9fe 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Language.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Language.java @@ -1,17 +1,17 @@ package de.caritas.cob.userservice.api.model; import com.neovisionaries.i18n.LanguageCode; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.ForeignKey; -import javax.persistence.Id; -import javax.persistence.IdClass; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.ForeignKey; +import jakarta.persistence.Id; +import jakarta.persistence.IdClass; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Session.java b/src/main/java/de/caritas/cob/userservice/api/model/Session.java index d85c5e3bd..2ce42c129 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Session.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Session.java @@ -6,26 +6,26 @@ import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.neovisionaries.i18n.LanguageCode; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -51,7 +51,7 @@ @ToString @FilterDef( name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = "long")}) + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Session implements TenantAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java b/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java index 450642b7d..55cd78afb 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java @@ -1,17 +1,17 @@ package de.caritas.cob.userservice.api.model; import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.validation.constraints.Size; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/SessionTopic.java b/src/main/java/de/caritas/cob/userservice/api/model/SessionTopic.java index 57a7692ae..68d84076e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/SessionTopic.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/SessionTopic.java @@ -1,16 +1,16 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.time.LocalDateTime; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/User.java b/src/main/java/de/caritas/cob/userservice/api/model/User.java index 75915a15f..ef0795ddb 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/User.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/User.java @@ -1,22 +1,24 @@ package de.caritas.cob.userservice.api.model; +import static de.caritas.cob.userservice.mailservice.generated.web.model.Dialect.FORMAL; +import static de.caritas.cob.userservice.mailservice.generated.web.model.Dialect.INFORMAL; + import com.fasterxml.jackson.annotation.JsonIgnore; import com.neovisionaries.i18n.LanguageCode; -import de.caritas.cob.userservice.mailservice.generated.web.model.Dialect; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import jakarta.validation.constraints.Size; import java.time.LocalDateTime; import java.util.Objects; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; -import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -42,7 +44,7 @@ @EntityListeners(AuditingEntityListener.class) @FilterDef( name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = "long")}) + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class User implements TenantAware, NotificationsAware { @@ -156,7 +158,7 @@ public int hashCode() { @JsonIgnore @Transient - public Dialect getDialect() { - return isLanguageFormal() ? Dialect.FORMAL : Dialect.INFORMAL; + public de.caritas.cob.userservice.mailservice.generated.web.model.Dialect getDialect() { + return isLanguageFormal() ? FORMAL : INFORMAL; } } diff --git a/src/main/java/de/caritas/cob/userservice/api/model/UserAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/UserAgency.java index abf24fa72..955ae3e74 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/UserAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/UserAgency.java @@ -1,17 +1,17 @@ package de.caritas.cob.userservice.api.model; +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.SequenceGenerator; +import jakarta.persistence.Table; import java.time.LocalDateTime; 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.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/UserChat.java b/src/main/java/de/caritas/cob/userservice/api/model/UserChat.java index f6d340e3d..66fb1b513 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/UserChat.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/UserChat.java @@ -1,15 +1,15 @@ package de.caritas.cob.userservice.api.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import jakarta.persistence.UniqueConstraint; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/UserMobileToken.java b/src/main/java/de/caritas/cob/userservice/api/model/UserMobileToken.java index 24457419f..a7c8eaa6b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/UserMobileToken.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/UserMobileToken.java @@ -1,16 +1,16 @@ package de.caritas.cob.userservice.api.model; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; import java.util.Objects; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.SequenceGenerator; -import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClientConfig.java b/src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClientConfig.java index f5786ca48..67f1bee2d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClientConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/IdentityClientConfig.java @@ -1,8 +1,8 @@ package de.caritas.cob.userservice.api.port.out; import de.caritas.cob.userservice.api.config.auth.TechnicalUserConfig; +import jakarta.validation.constraints.NotNull; import java.util.Set; -import javax.validation.constraints.NotNull; public interface IdentityClientConfig { diff --git a/src/main/java/de/caritas/cob/userservice/api/scheduler/ScheduledLogger.java b/src/main/java/de/caritas/cob/userservice/api/scheduler/ScheduledLogger.java index de0eebe29..43d53b1af 100644 --- a/src/main/java/de/caritas/cob/userservice/api/scheduler/ScheduledLogger.java +++ b/src/main/java/de/caritas/cob/userservice/api/scheduler/ScheduledLogger.java @@ -2,7 +2,6 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; -import lombok.val; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -16,7 +15,7 @@ public class ScheduledLogger { @SneakyThrows @Around("@annotation(org.springframework.scheduling.annotation.Scheduled)") public void logMethod(ProceedingJoinPoint joinPoint) { - val schedulerName = joinPoint.getSignature().toShortString(); + final var schedulerName = joinPoint.getSignature().toShortString(); try { log.info("{} Scheduler started", schedulerName); joinPoint.proceed(); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/AskerImportService.java b/src/main/java/de/caritas/cob/userservice/api/service/AskerImportService.java index 5efe55a88..f1721411d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/AskerImportService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/AskerImportService.java @@ -41,7 +41,7 @@ import java.io.IOException; import java.io.Reader; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Date; import java.util.List; @@ -120,9 +120,9 @@ public void startImportForAskersWithoutSession() { } catch (Exception exception) { writeToImportLog( - String.format( - "Error while reading import file: %s", - org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)), + "Error while reading import file: %s" + .formatted( + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)), protocolFile); return; } @@ -292,9 +292,9 @@ public void startImport() { return; } catch (Exception exception) { writeToImportLog( - String.format( - "Error while reading import file or logging in Rocket.Chat system message user: %s", - org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)), + "Error while reading import file or logging in Rocket.Chat system message user: %s" + .formatted( + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)), protocolFile); return; } @@ -325,7 +325,7 @@ public void startImport() { // Check if consultant exists and is in agency Optional consultant = consultantService.getConsultant(record.getConsultantId()); - if (!consultant.isPresent()) { + if (consultant.isEmpty()) { writeToImportLog( String.format( "Consultant with id %s does not exist. Skipping import of user %s", @@ -581,7 +581,7 @@ public void startImport() { private void writeToImportLog(String message, String protocolFile) { try { Files.write( - Paths.get(protocolFile), + Path.of(protocolFile), (message + NEWLINE_CHAR).getBytes(IMPORT_LOG_CHARSET), StandardOpenOption.CREATE, StandardOpenOption.APPEND); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java b/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java index 75fbcc075..b809a0a67 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/ChatService.java @@ -250,18 +250,15 @@ public UpdateChatResponseDTO updateChat( Chat chat = getChat(chatId) .orElseThrow( - () -> - new BadRequestException( - String.format("Chat with id %s does not exist", chatId))); + () -> new BadRequestException("Chat with id %s does not exist".formatted(chatId))); if (!authenticatedUser.getUserId().equals(chat.getChatOwner().getId())) { throw new ForbiddenException("Only the chat owner is allowed to change chat settings"); } if (isTrue(chat.isActive())) { throw new ConflictException( - String.format( - "Chat with id %s is active. Therefore changing the chat settings is not supported.", - chatId)); + "Chat with id %s is active. Therefore changing the chat settings is not supported." + .formatted(chatId)); } LocalDateTime startDate = LocalDateTime.of(chatDTO.getStartDate(), chatDTO.getStartTime()); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/ConsultantImportService.java b/src/main/java/de/caritas/cob/userservice/api/service/ConsultantImportService.java index 04abace2f..7dd27f3cf 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/ConsultantImportService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/ConsultantImportService.java @@ -19,7 +19,7 @@ import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashSet; @@ -272,7 +272,7 @@ private void writeToImportLog(String message) { try { Files.write( - Paths.get(protocolFile), + Path.of(protocolFile), (message + NEWLINE_CHAR).getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/TenantHibernateInterceptor.java b/src/main/java/de/caritas/cob/userservice/api/service/TenantHibernateInterceptor.java index 7aec50bd2..722bebe56 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/TenantHibernateInterceptor.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/TenantHibernateInterceptor.java @@ -5,27 +5,26 @@ import java.util.Iterator; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.hibernate.EmptyInterceptor; +import org.hibernate.Interceptor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor @Slf4j -public class TenantHibernateInterceptor extends EmptyInterceptor { +public class TenantHibernateInterceptor implements Interceptor { @Override - public void preFlush(Iterator entities) { + public void preFlush(Iterator entities) { Object entity; while (entities.hasNext()) { entity = entities.next(); - if (entity instanceof TenantAware) { - var tenantAware = (TenantAware) entity; + if (entity instanceof TenantAware tenantAware) { if (tenantAware.getTenantId() == null && !TenantContext.isTechnicalOrSuperAdminContext()) { - ((TenantAware) entity).setTenantId(TenantContext.getCurrentTenant()); + tenantAware.setTenantId(TenantContext.getCurrentTenant()); } } } - super.preFlush(entities); + Interceptor.super.preFlush(entities); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/service/archive/SessionDeleteService.java b/src/main/java/de/caritas/cob/userservice/api/service/archive/SessionDeleteService.java index b2d554362..46f663405 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/archive/SessionDeleteService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/archive/SessionDeleteService.java @@ -10,8 +10,8 @@ import de.caritas.cob.userservice.api.service.statistics.event.ArchiveOrDeleteSessionStatisticsEvent; import de.caritas.cob.userservice.api.workflow.delete.action.asker.DeleteSingleRoomAndSessionAction; import de.caritas.cob.userservice.api.workflow.delete.model.SessionDeletionWorkflowDTO; +import jakarta.validation.constraints.NotNull; import java.time.LocalDateTime; -import javax.validation.constraints.NotNull; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplier.java index bbbe35e7e..5d4fbf15c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/AssignEnquiryEmailSupplier.java @@ -11,10 +11,10 @@ import de.caritas.cob.userservice.api.service.ConsultantService; import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO; import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import javax.transaction.Transactional; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Setter; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplier.java index c5f25af4d..8f601c690 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewDirectEnquiryEmailSupplier.java @@ -14,10 +14,10 @@ import de.caritas.cob.userservice.api.service.consultingtype.ReleaseToggleService; import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO; import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplier.java index 83ccf8f1e..d98f6a8a7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewEnquiryEmailSupplier.java @@ -18,11 +18,11 @@ import de.caritas.cob.userservice.api.service.consultingtype.ReleaseToggleService; import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO; import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplier.java index 25fa0d95c..8de412b65 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/NewMessageEmailSupplier.java @@ -249,7 +249,7 @@ private String obtainConsultantUsername() { .orElseThrow( () -> new InternalServerErrorException( - String.format("Consultant with id %s not found.", userId))) + "Consultant with id %s not found.".formatted(userId))) .getUsername(); } } diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentConfirmationEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentConfirmationEmailSupplier.java index 19f31fa5e..0093bd48d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentConfirmationEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentConfirmationEmailSupplier.java @@ -7,10 +7,10 @@ import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO; import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import javax.transaction.Transactional; import lombok.Builder; @Builder diff --git a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentRequestEmailSupplier.java b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentRequestEmailSupplier.java index b8201217a..974bf02c1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentRequestEmailSupplier.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/emailsupplier/ReassignmentRequestEmailSupplier.java @@ -5,10 +5,10 @@ import de.caritas.cob.userservice.mailservice.generated.web.model.Dialect; import de.caritas.cob.userservice.mailservice.generated.web.model.MailDTO; import de.caritas.cob.userservice.mailservice.generated.web.model.TemplateDataDTO; +import jakarta.transaction.Transactional; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import javax.transaction.Transactional; import lombok.Builder; @Builder diff --git a/src/main/java/de/caritas/cob/userservice/api/service/httpheader/HttpHeadersResolver.java b/src/main/java/de/caritas/cob/userservice/api/service/httpheader/HttpHeadersResolver.java index 14c769767..0b64ebe20 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/httpheader/HttpHeadersResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/httpheader/HttpHeadersResolver.java @@ -1,7 +1,7 @@ package de.caritas.cob.userservice.api.service.httpheader; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationService.java b/src/main/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationService.java index ed4b368dc..21c35f01b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationService.java @@ -1,9 +1,9 @@ package de.caritas.cob.userservice.api.service.liveevents; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUSCONVERSATIONFINISHED; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUSENQUIRYACCEPTED; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.DIRECTMESSAGE; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.NEWANONYMOUSENQUIRY; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUS_CONVERSATION_FINISHED; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUS_ENQUIRY_ACCEPTED; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.DIRECT_MESSAGE; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.NEW_ANONYMOUS_ENQUIRY; import static java.util.Collections.singletonList; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.isNotBlank; @@ -45,7 +45,9 @@ public class LiveEventNotificationService { public void sendAcceptAnonymousEnquiryEventToUser(String userId) { if (isNotBlank(userId)) { var liveEventMessage = - new LiveEventMessage().eventType(ANONYMOUSENQUIRYACCEPTED).userIds(singletonList(userId)); + new LiveEventMessage() + .eventType(ANONYMOUS_ENQUIRY_ACCEPTED) + .userIds(singletonList(userId)); sendLiveEventMessage(liveEventMessage); } } @@ -53,7 +55,7 @@ public void sendAcceptAnonymousEnquiryEventToUser(String userId) { private void sendLiveEventMessage(LiveEventMessage liveEventMessage) { sendLiveEventMessage( liveEventMessage, - () -> String.format("Unable to trigger live event message %s", liveEventMessage)); + () -> "Unable to trigger live event message %s".formatted(liveEventMessage)); } private void sendLiveEventMessage( @@ -92,12 +94,12 @@ private boolean notInitiatingUser(String userId) { private void triggerDirectMessageLiveEvent(List userIds, String rcGroupId) { if (isNotEmpty(userIds)) { - var liveEventMessage = new LiveEventMessage().eventType(DIRECTMESSAGE).userIds(userIds); + var liveEventMessage = new LiveEventMessage().eventType(DIRECT_MESSAGE).userIds(userIds); sendLiveEventMessage( liveEventMessage, () -> { - var rcMessage = String.format(RC_GROUP_ID_MESSAGE_TEMPLATE, rcGroupId); + var rcMessage = RC_GROUP_ID_MESSAGE_TEMPLATE.formatted(rcGroupId); return makeUserIdsEventTypeMessage(liveEventMessage, rcMessage); }); } @@ -105,9 +107,8 @@ private void triggerDirectMessageLiveEvent(List userIds, String rcGroupI private String makeUserIdsEventTypeMessage( LiveEventMessage triggeredLiveEventMessage, String withMessage) { - return String.format( - "Unable to trigger %s live event message %s", - triggeredLiveEventMessage.getEventType(), withMessage); + return "Unable to trigger %s live event message %s" + .formatted(triggeredLiveEventMessage.getEventType(), withMessage); } /** @@ -118,13 +119,14 @@ private String makeUserIdsEventTypeMessage( */ public void sendLiveNewAnonymousEnquiryEventToUsers(List userIds, Long sessionId) { if (isNotEmpty(userIds)) { - var liveEventMessage = new LiveEventMessage().eventType(NEWANONYMOUSENQUIRY).userIds(userIds); + var liveEventMessage = + new LiveEventMessage().eventType(NEW_ANONYMOUS_ENQUIRY).userIds(userIds); sendLiveEventMessage( liveEventMessage, () -> { var anonymousEnquiryMessage = - String.format(NEW_ANONYMOUS_ENQUIRY_MESSAGE_TEMPLATE, sessionId); + NEW_ANONYMOUS_ENQUIRY_MESSAGE_TEMPLATE.formatted(sessionId); return makeUserIdsEventTypeMessage(liveEventMessage, anonymousEnquiryMessage); }); } @@ -140,7 +142,7 @@ public void sendLiveFinishedAnonymousConversationToUsers( if (isNotEmpty(userIds)) { var liveEventMessage = new LiveEventMessage() - .eventType(ANONYMOUSCONVERSATIONFINISHED) + .eventType(ANONYMOUS_CONVERSATION_FINISHED) .eventContent(new StatusSource().finishConversationPhase(finishConversationPhase)) .userIds(userIds); diff --git a/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java b/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java index 737bd0f0d..fdc14aafe 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java @@ -112,7 +112,7 @@ public void postWelcomeMessageIfConfigured( } catch (RestClientException | RocketChatUserNotInitializedException exception) { log.error("Exception calling RocketChat API: {}", exception.getMessage()); throw new RocketChatPostWelcomeMessageException( - String.format("Could not post welcome message in Rocket.Chat group %s", rcGroupId), + "Could not post welcome message in Rocket.Chat group %s".formatted(rcGroupId), exception, exceptionInformation); } @@ -154,8 +154,8 @@ public MessageResponseDTO assignUserToRocketChatGroup( } catch (RestClientException exception) { throw new RocketChatPostFurtherStepsMessageException( - String.format( - "Could not post further steps message in Rocket.Chat group with id %s", rcGroupId), + "Could not post further steps message in Rocket.Chat group with id %s" + .formatted(rcGroupId), exception, exceptionInformation); } @@ -174,8 +174,8 @@ private void postAliasOnlyMessage( } catch (RestClientException exception) { throw new RocketChatPostFurtherStepsMessageException( - String.format( - "Could not post further steps message in Rocket.Chat group with id %s", rcGroupId), + "Could not post further steps message in Rocket.Chat group with id %s" + .formatted(rcGroupId), exception, exceptionInformation); } diff --git a/src/main/java/de/caritas/cob/userservice/api/service/security/AuthorisationService.java b/src/main/java/de/caritas/cob/userservice/api/service/security/AuthorisationService.java new file mode 100644 index 000000000..3044f6cdf --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/service/security/AuthorisationService.java @@ -0,0 +1,49 @@ +package de.caritas.cob.userservice.api.service.security; + +import com.google.common.collect.Lists; +import de.caritas.cob.userservice.api.config.auth.RoleAuthorizationAuthorityMapper; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.stereotype.Service; + +@Service +public class AuthorisationService { + + private final RoleAuthorizationAuthorityMapper roleAuthorizationAuthorityMapper = + new RoleAuthorizationAuthorityMapper(); + + public Object getUsername() { + return getPrincipal().getClaims().get("username"); + } + + private Authentication getAuthentication() { + return SecurityContextHolder.getContext().getAuthentication(); + } + + private Jwt getPrincipal() { + return (Jwt) getAuthentication().getPrincipal(); + } + + public Collection extractRealmAuthorities(Jwt jwt) { + var roles = extractRealmRoles(jwt); + return roleAuthorizationAuthorityMapper.mapAuthorities( + roles.stream().collect(Collectors.toSet())); + } + + public Collection extractRealmRoles(Jwt jwt) { + Map realmAccess = (Map) jwt.getClaims().get("realm_access"); + if (realmAccess != null) { + var roles = (List) realmAccess.get("roles"); + if (roles != null) { + return roles; + } + } + return Lists.newArrayList(); + } +} diff --git a/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverter.java b/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverter.java new file mode 100644 index 000000000..9fb51e9a1 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverter.java @@ -0,0 +1,60 @@ +package de.caritas.cob.userservice.api.service.security; + +import java.util.Collection; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class JwtAuthConverter implements Converter { + + private final @NonNull AuthorisationService authorisationService; + + private final JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = + new JwtGrantedAuthoritiesConverter(); + + private final JwtAuthConverterProperties properties; + + public JwtAuthConverter( + JwtAuthConverterProperties properties, AuthorisationService authorisationService) { + this.properties = properties; + this.authorisationService = authorisationService; + } + + @Override + public AbstractAuthenticationToken convert(Jwt jwt) { + var authorities = getGrantedAuthorities(jwt); + return new JwtAuthenticationToken(jwt, authorities, getPrincipalClaimName(jwt)); + } + + private Collection getGrantedAuthorities(Jwt jwt) { + Collection convertedGrantedAuthorities = + jwtGrantedAuthoritiesConverter.convert(jwt); + if (convertedGrantedAuthorities != null) { + return Stream.concat( + convertedGrantedAuthorities.stream(), + authorisationService.extractRealmAuthorities(jwt).stream()) + .collect(Collectors.toSet()); + } else { + return authorisationService.extractRealmAuthorities(jwt); + } + } + + private String getPrincipalClaimName(Jwt jwt) { + String claimName = JwtClaimNames.SUB; + if (properties.getPrincipalAttribute() != null) { + claimName = properties.getPrincipalAttribute(); + } + return jwt.getClaim(claimName); + } +} diff --git a/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverterProperties.java b/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverterProperties.java new file mode 100644 index 000000000..c73b2ec67 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/service/security/JwtAuthConverterProperties.java @@ -0,0 +1,16 @@ +package de.caritas.cob.userservice.api.service.security; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +@Data +@Validated +@Configuration +@ConfigurationProperties(prefix = "jwt.auth.converter") +public class JwtAuthConverterProperties { + + private String resourceId; + private String principalAttribute; +} diff --git a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java index 177233fe9..5e49aa559 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java @@ -35,6 +35,7 @@ import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.user.UserService; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; +import jakarta.ws.rs.BadRequestException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; @@ -46,7 +47,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; -import javax.ws.rs.BadRequestException; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -625,8 +625,7 @@ private Consultant loadConsultantOrThrow(String userId) { } private Supplier newBadRequestException(String userId) { - return () -> - new BadRequestException(String.format("Consultant with id %s does not exist", userId)); + return () -> new BadRequestException("Consultant with id %s does not exist".formatted(userId)); } private ConsultantSessionDTO toConsultantSessionDTO(Session session) { @@ -750,13 +749,12 @@ public Optional findSessionByConsultantAndUserAndConsultingType( public String findGroupIdByConsultantAndUser(String consultantId, String askerId) { Optional consultant = consultantService.getConsultant(consultantId); - if (!consultant.isPresent()) { - throw new BadRequestException( - String.format("Consultant for given id %s not found", consultantId)); + if (consultant.isEmpty()) { + throw new BadRequestException("Consultant for given id %s not found".formatted(consultantId)); } Optional user = userService.getUser(askerId); - if (!user.isPresent()) { - throw new BadRequestException(String.format("Asker for given id %s not found", askerId)); + if (user.isEmpty()) { + throw new BadRequestException("Asker for given id %s not found".formatted(askerId)); } List sessions = diff --git a/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListService.java b/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListService.java index b5fabef37..132dda055 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/sessionlist/ConsultantSessionListService.java @@ -10,6 +10,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; import de.caritas.cob.userservice.api.container.SessionListQueryParameter; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; +import de.caritas.cob.userservice.api.helper.LatestMessageParseUtil; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.Session.SessionStatus; import de.caritas.cob.userservice.api.service.ChatService; @@ -116,8 +117,7 @@ private List retrieveSessionsForStatus( private SessionStatus getVerifiedSessionStatus(Integer status) { return SessionStatus.valueOf(status) - .orElseThrow( - () -> new BadRequestException(String.format("Invalid session status %s ", status))); + .orElseThrow(() -> new BadRequestException("Invalid session status %s ".formatted(status))); } /** @@ -166,7 +166,9 @@ private List mergeConsultantSessionsAndChats( } private void sortSessionsByLastMessageDateDesc(List sessions) { - sessions.sort(Comparator.comparing(ConsultantSessionResponseDTO::getLatestMessage).reversed()); + sessions.sort( + Comparator.comparing(LatestMessageParseUtil::parseLatestMessageForConsultantSession) + .reversed()); } private void removeAllChatsAndSessionsWithoutUnreadFeedback( diff --git a/src/main/java/de/caritas/cob/userservice/api/service/statistics/StatisticsService.java b/src/main/java/de/caritas/cob/userservice/api/service/statistics/StatisticsService.java index 5857d282e..d6a250b4c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/statistics/StatisticsService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/statistics/StatisticsService.java @@ -3,8 +3,8 @@ import static java.util.Objects.nonNull; import de.caritas.cob.userservice.api.service.statistics.event.StatisticsEvent; +import jakarta.validation.constraints.NotNull; import java.nio.charset.StandardCharsets; -import javax.validation.constraints.NotNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.AmqpTemplate; diff --git a/src/main/java/de/caritas/cob/userservice/api/service/user/UserAccountService.java b/src/main/java/de/caritas/cob/userservice/api/service/user/UserAccountService.java index d77c5f575..02bdd4e09 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/user/UserAccountService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/user/UserAccountService.java @@ -91,7 +91,7 @@ public Consultant retrieveValidatedConsultantById(String consultantId) { .orElseThrow( () -> new InternalServerErrorException( - String.format("Consultant with id %s not found", consultantId))); + "Consultant with id %s not found".formatted(consultantId))); } /** diff --git a/src/main/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidator.java b/src/main/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidator.java index d348942ff..73b0b5f1c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidator.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/user/validation/UserAccountValidator.java @@ -3,7 +3,7 @@ import de.caritas.cob.userservice.api.adapters.keycloak.dto.KeycloakLoginResponseDTO; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; import de.caritas.cob.userservice.api.port.out.IdentityClient; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java index 28a587b62..b02d1962b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java @@ -1,8 +1,8 @@ package de.caritas.cob.userservice.api.tenant; +import jakarta.servlet.http.HttpServletRequest; import java.util.Map; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.keycloak.KeycloakSecurityContext; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolver.java index 851f9577c..48e36b734 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolver.java @@ -1,8 +1,8 @@ package de.caritas.cob.userservice.api.tenant; import de.caritas.cob.userservice.api.service.httpheader.TenantHeaderSupplier; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolver.java index 007b410c5..106ab4bd6 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolver.java @@ -6,8 +6,8 @@ import de.caritas.cob.userservice.api.service.ConsultantService; import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.httpheader.HttpHeadersResolver; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolver.java index 917966124..06ee28900 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolver.java @@ -5,8 +5,8 @@ import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.SubdomainExtractor; import de.caritas.cob.userservice.api.admin.service.tenant.TenantService; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java index a3cb2b052..2f5655214 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java @@ -3,10 +3,10 @@ import static de.caritas.cob.userservice.api.config.auth.UserRole.TECHNICAL; import static de.caritas.cob.userservice.api.config.auth.UserRole.TENANT_ADMIN; +import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.Optional; import java.util.Set; -import javax.servlet.http.HttpServletRequest; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; import org.springframework.stereotype.Component; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantAspect.java b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantAspect.java index 91a5d57e3..d2aba9319 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantAspect.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantAspect.java @@ -1,7 +1,7 @@ package de.caritas.cob.userservice.api.tenant; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.aspectj.lang.annotation.Aspect; diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolver.java index a5e78a63a..3e733c1a4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolver.java @@ -1,7 +1,7 @@ package de.caritas.cob.userservice.api.tenant; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; public interface TenantResolver { diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolverService.java b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolverService.java index b4c311601..47e44df72 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolverService.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/TenantResolverService.java @@ -2,10 +2,10 @@ import static com.google.common.collect.Lists.newArrayList; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateAnonymousUserService.java b/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateAnonymousUserService.java index ad804ff60..43a19e28b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateAnonymousUserService.java +++ b/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateAnonymousUserService.java @@ -13,12 +13,12 @@ import de.caritas.cob.userservice.api.model.Session; import de.caritas.cob.userservice.api.model.User; import de.caritas.cob.userservice.api.port.out.SessionRepository; +import jakarta.transaction.Transactional; import java.time.LocalDateTime; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateGroupChatService.java b/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateGroupChatService.java index 724fd02b2..3652d6fd1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateGroupChatService.java +++ b/src/main/java/de/caritas/cob/userservice/api/workflow/deactivate/service/DeactivateGroupChatService.java @@ -4,9 +4,9 @@ import de.caritas.cob.userservice.api.actions.registry.ActionsRegistry; import de.caritas.cob.userservice.api.model.Chat; import de.caritas.cob.userservice.api.port.out.ChatRepository; +import jakarta.transaction.Transactional; import java.time.LocalDateTime; import java.util.function.Predicate; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAnonymousService.java b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAnonymousService.java index 5569a6486..41fddaa68 100644 --- a/src/main/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAnonymousService.java +++ b/src/main/java/de/caritas/cob/userservice/api/workflow/delete/service/DeleteUserAnonymousService.java @@ -7,13 +7,13 @@ import de.caritas.cob.userservice.api.model.User; import de.caritas.cob.userservice.api.port.out.SessionRepository; import de.caritas.cob.userservice.api.workflow.delete.model.DeletionWorkflowError; +import jakarta.transaction.Transactional; import java.time.LocalDateTime; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; -import javax.transaction.Transactional; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.commons.collections4.CollectionUtils; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index e833eb76a..1ee3e1b6d 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -40,10 +40,10 @@ import de.caritas.cob.userservice.api.helper.UsernameTranscoder; import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; +import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.core.Response; import java.util.HashMap; import java.util.List; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.core.Response; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ActuatorControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ActuatorControllerIT.java index 1fcfc24e3..4d6cf85dc 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ActuatorControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ActuatorControllerIT.java @@ -1,6 +1,6 @@ package de.caritas.cob.userservice.api.adapters.web.controller; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON; import static org.hamcrest.Matchers.is; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java index f7eb7c868..8c7c6e680 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerAuthorizationIT.java @@ -9,8 +9,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import de.caritas.cob.userservice.api.adapters.web.dto.Appointment; import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue; +import jakarta.servlet.http.Cookie; import java.util.UUID; -import javax.servlet.http.Cookie; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java index ca5b795d2..7058d0bb2 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java @@ -25,6 +25,7 @@ import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.port.out.AppointmentRepository; import de.caritas.cob.userservice.api.port.out.ConsultantRepository; +import jakarta.servlet.http.Cookie; import java.lang.reflect.Method; import java.time.Clock; import java.time.Instant; @@ -32,7 +33,6 @@ import java.time.ZoneOffset; import java.util.Set; import java.util.UUID; -import javax.servlet.http.Cookie; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java index 6a07c3788..ac9830b76 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerAuthorizationIT.java @@ -38,7 +38,7 @@ import de.caritas.cob.userservice.api.conversation.facade.FinishAnonymousConversationFacade; import de.caritas.cob.userservice.api.conversation.service.ConversationListResolver; import de.caritas.cob.userservice.api.helper.UsernameTranscoder; -import javax.servlet.http.Cookie; +import jakarta.servlet.http.Cookie; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java index db9e018ae..1dfa42893 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerAuthorizationIT.java @@ -32,9 +32,9 @@ import de.caritas.cob.userservice.api.admin.report.service.ViolationReportGenerator; import de.caritas.cob.userservice.api.admin.service.session.SessionAdminService; import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue; +import jakarta.servlet.http.Cookie; import java.util.List; import java.util.UUID; -import javax.servlet.http.Cookie; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -274,7 +274,7 @@ public void getConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdmi getConsultantAgencies_Should_ReturnUnauthorizedAndCallNoMethods_When_noKeycloakAuthorizationIsPresent() throws Exception { String consultantAgencyPath = - String.format(CONSULTANT_AGENCIES_PATH, "1da238c6-cd46-4162-80f1-bff74eafeAAA"); + CONSULTANT_AGENCIES_PATH.formatted("1da238c6-cd46-4162-80f1-bff74eafeAAA"); mvc.perform(get(consultantAgencyPath).cookie(CSRF_COOKIE).header(CSRF_HEADER, CSRF_VALUE)) .andExpect(status().isUnauthorized()); @@ -300,7 +300,7 @@ public void getConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdmi getConsultantAgencies_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdminAuthority() throws Exception { String consultantAgencyPath = - String.format(CONSULTANT_AGENCIES_PATH, "1da238c6-cd46-4162-80f1-bff74eafeAAA"); + CONSULTANT_AGENCIES_PATH.formatted("1da238c6-cd46-4162-80f1-bff74eafeAAA"); mvc.perform(get(consultantAgencyPath).cookie(CSRF_COOKIE).header(CSRF_HEADER, CSRF_VALUE)) .andExpect(status().isForbidden()); @@ -315,7 +315,7 @@ public void getConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdmi throws Exception { String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA"; - String consultantAgencyPath = String.format(CONSULTANT_AGENCIES_PATH, consultantId); + String consultantAgencyPath = CONSULTANT_AGENCIES_PATH.formatted(consultantId); mvc.perform(get(consultantAgencyPath).cookie(CSRF_COOKIE).header(CSRF_HEADER, CSRF_VALUE)) .andExpect(status().isOk()); @@ -429,7 +429,7 @@ public void updateConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserA createConsultantAgency_Should_ReturnUnauthorizedAndCallNoMethods_When_noKeycloakAuthorizationIsPresent() throws Exception { mvc.perform( - post(String.format(CONSULTANT_AGENCY_PATH, "consultantId")) + post(CONSULTANT_AGENCY_PATH.formatted("consultantId")) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE)) .andExpect(status().isUnauthorized()); @@ -455,7 +455,7 @@ public void updateConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserA createConsultantAgency_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdminAuthority() throws Exception { mvc.perform( - post(String.format(CONSULTANT_AGENCY_PATH, "consultantId")) + post(CONSULTANT_AGENCY_PATH.formatted("consultantId")) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE)) .andExpect(status().isForbidden()); @@ -472,7 +472,7 @@ public void updateConsultant_Should_ReturnForbiddenAndCallNoMethods_When_noUserA easyRandom.nextObject(CreateConsultantAgencyDTO.class); mvc.perform( - post(String.format(CONSULTANT_AGENCY_PATH, "consultantId")) + post(CONSULTANT_AGENCY_PATH.formatted("consultantId")) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .contentType(MediaType.APPLICATION_JSON) @@ -602,7 +602,7 @@ public void changeAgencyType_Should_ReturnCreatedAndCallConsultantAdmin_When_use deleteConsultantAgency_Should_ReturnUnauthorizedAndCallNoMethods_When_noKeycloakAuthorizationIsPresent() throws Exception { mvc.perform( - delete(String.format(DELETE_CONSULTANT_AGENCY_PATH, "1", 1L)) + delete(DELETE_CONSULTANT_AGENCY_PATH.formatted("1", 1L)) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .contentType(MediaType.APPLICATION_JSON)) @@ -629,7 +629,7 @@ public void changeAgencyType_Should_ReturnCreatedAndCallConsultantAdmin_When_use deleteConsultantAgency_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdminAuthority() throws Exception { mvc.perform( - delete(String.format(DELETE_CONSULTANT_AGENCY_PATH, "1", 1L)) + delete(DELETE_CONSULTANT_AGENCY_PATH.formatted("1", 1L)) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .contentType(MediaType.APPLICATION_JSON)) @@ -644,7 +644,7 @@ public void changeAgencyType_Should_ReturnCreatedAndCallConsultantAdmin_When_use deleteConsultantAgency_Should_ReturnCreatedAndCallConsultantAdmin_When_userAdminAuthority() throws Exception { mvc.perform( - delete(String.format(DELETE_CONSULTANT_AGENCY_PATH, "1", 1L)) + delete(DELETE_CONSULTANT_AGENCY_PATH.formatted("1", 1L)) .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .contentType(MediaType.APPLICATION_JSON)) @@ -768,8 +768,7 @@ public void deleteAsker_Should_ReturnOkAndCallUserAdminFacade_When_userAdminAuth public void getAgencyConsultants_Should_ReturnUnauthorizedAndCallNoMethods_When_noKeycloakAuthorizationIsPresent() throws Exception { - mvc.perform( - get(String.format(AGENCY_CONSULTANT_PATH, "1")).contentType(MediaType.APPLICATION_JSON)) + mvc.perform(get(AGENCY_CONSULTANT_PATH.formatted("1")).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isUnauthorized()); verifyNoMoreInteractions(consultantAdminFacade); @@ -792,8 +791,7 @@ public void deleteAsker_Should_ReturnOkAndCallUserAdminFacade_When_userAdminAuth public void getAgencyConsultants_Should_ReturnForbiddenAndCallNoMethods_When_noUserAdminAuthority() throws Exception { - mvc.perform( - get(String.format(AGENCY_CONSULTANT_PATH, "1")).contentType(MediaType.APPLICATION_JSON)) + mvc.perform(get(AGENCY_CONSULTANT_PATH.formatted("1")).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); verifyNoMoreInteractions(consultantAdminFacade); @@ -803,8 +801,7 @@ public void deleteAsker_Should_ReturnOkAndCallUserAdminFacade_When_userAdminAuth @WithMockUser(authorities = {AuthorityValue.USER_ADMIN}) public void getAgencyConsultants_Should_ReturnOkAndCallUserAdminFacade_When_userAdminAuthority() throws Exception { - mvc.perform( - get(String.format(AGENCY_CONSULTANT_PATH, "1")).contentType(MediaType.APPLICATION_JSON)) + mvc.perform(get(AGENCY_CONSULTANT_PATH.formatted("1")).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(this.consultantAdminFacade, times(1)).findConsultantsForAgency(any()); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java index d21ed1124..6194f80c1 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java @@ -43,8 +43,8 @@ import de.caritas.cob.userservice.mailservice.generated.web.MailsControllerApi; import de.caritas.cob.userservice.tenantservice.generated.web.model.RestrictedTenantDTO; import de.caritas.cob.userservice.topicservice.generated.web.TopicControllerApi; +import jakarta.servlet.http.Cookie; import java.util.LinkedHashMap; -import javax.servlet.http.Cookie; import net.minidev.json.JSONArray; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java index 13b55c0c1..3a5c66167 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java @@ -150,7 +150,7 @@ void getConsultantAgency_Should_returnOk_When_requiredConsultantIdParamIsGiven() throws Exception { String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA"; - String consultantAgencyPath = String.format(CONSULTANT_AGENCIES_PATH, consultantId); + String consultantAgencyPath = CONSULTANT_AGENCIES_PATH.formatted(consultantId); this.mvc.perform(get(consultantAgencyPath)).andExpect(status().isOk()); @@ -243,7 +243,7 @@ void updateConsultant_Should_returnBadRequest_When_requiredParamsAreMissing() th void createConsultantAgency_Should_returnCreated_When_requiredParamsAreGiven() throws Exception { String consultantId = "1da238c6-cd46-4162-80f1-bff74eafeAAA"; - String consultantAgencyPath = String.format(CONSULTANT_AGENCY_PATH, consultantId); + String consultantAgencyPath = CONSULTANT_AGENCY_PATH.formatted(consultantId); CreateConsultantAgencyDTO createConsultantAgencyDTO = new CreateConsultantAgencyDTO(); createConsultantAgencyDTO.setAgencyId(15L); @@ -311,7 +311,7 @@ void deleteConsultantAgency_Should_returnOk_When_requiredParamsAreGiven() throws Long agencyId = 1L; String consultantAgencyDeletePath = - String.format(DELETE_CONSULTANT_AGENCY_PATH, consultantId, agencyId); + DELETE_CONSULTANT_AGENCY_PATH.formatted(consultantId, agencyId); this.mvc .perform(delete(consultantAgencyDeletePath).contentType(MediaType.APPLICATION_JSON)) @@ -354,7 +354,7 @@ void deleteAsker_Should_returnOk_When_requiredParamIsGiven() throws Exception { @Test void getAgencyConsultants_Should_returnOk_When_requiredAgencyIdParamIsGiven() throws Exception { var agencyId = "1"; - var agencyConsultantsPath = String.format(AGENCY_CONSULTANT_PATH, agencyId); + var agencyConsultantsPath = AGENCY_CONSULTANT_PATH.formatted(agencyId); this.mvc.perform(get(agencyConsultantsPath)).andExpect(status().isOk()); @@ -505,7 +505,7 @@ void createAdminAgency_Should_returnCreated_When_requiredParamsAreGiven() throws String adminId = "1da238c6-cd46-4162-80f1-bff74eafeAAA"; // given - String adminAgencyPath = String.format(AGENCIES_OF_ADMIN_PATH, adminId); + String adminAgencyPath = AGENCIES_OF_ADMIN_PATH.formatted(adminId); CreateAdminAgencyRelationDTO createAdminAgencyRelationDTO = new CreateAdminAgencyRelationDTO(); createAdminAgencyRelationDTO.setAgencyId(15L); @@ -549,7 +549,7 @@ void deleteAdminAgency_Should_return_Ok_When_requiredParamsAreGiven() throws Exc // when this.mvc .perform( - delete(String.format(DELETE_ADMIN_AGENCY_PATH, adminId, agencyId)) + delete(DELETE_ADMIN_AGENCY_PATH.formatted(adminId, agencyId)) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); @@ -565,7 +565,7 @@ void deleteAgencyAdmin_Should_returnOk_When_requiredParamIsGiven() throws Except // when this.mvc .perform( - delete(String.format(DELETE_AGENCY_ADMIN_PATH, adminId)) + delete(DELETE_AGENCY_ADMIN_PATH.formatted(adminId)) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController2faE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController2faE2EIT.java index 75f507d50..13b970512 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController2faE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController2faE2EIT.java @@ -43,11 +43,11 @@ import de.caritas.cob.userservice.api.port.out.ConsultantRepository; import de.caritas.cob.userservice.api.port.out.UserAgencyRepository; import de.caritas.cob.userservice.api.port.out.UserRepository; +import jakarta.servlet.http.Cookie; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; -import javax.servlet.http.Cookie; import lombok.NonNull; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerAuthorizationIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerAuthorizationIT.java index b8cde7c9e..a5e6e19eb 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerAuthorizationIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerAuthorizationIT.java @@ -94,10 +94,10 @@ import de.caritas.cob.userservice.api.service.session.SessionService; import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.api.service.user.UserService; +import jakarta.servlet.http.Cookie; import java.util.Optional; import java.util.Set; import java.util.UUID; -import javax.servlet.http.Cookie; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java index 25a3f9f52..4e139481a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerChatE2EIT.java @@ -74,6 +74,8 @@ import de.caritas.cob.userservice.api.port.out.UserChatRepository; import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.api.testConfig.TestAgencyControllerApi; +import jakarta.servlet.http.Cookie; +import jakarta.transaction.Transactional; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Comparator; @@ -83,8 +85,6 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import javax.servlet.http.Cookie; -import javax.transaction.Transactional; import org.apache.commons.lang3.RandomStringUtils; import org.bson.Document; import org.bson.conversions.Bson; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java index 00858141c..3ef0653de 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerConsultantE2EIT.java @@ -61,6 +61,9 @@ import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.testConfig.TestAgencyControllerApi; import de.caritas.cob.userservice.topicservice.generated.web.TopicControllerApi; +import jakarta.servlet.http.Cookie; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.PositiveOrZero; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; @@ -70,9 +73,6 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; -import javax.servlet.http.Cookie; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.PositiveOrZero; import lombok.NonNull; import org.apache.commons.lang3.RandomStringUtils; import org.assertj.core.util.Lists; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index aa929c53c..663d3920c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -22,6 +22,9 @@ import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.ApiResponseEntityExceptionHandler; import de.caritas.cob.userservice.api.adapters.web.dto.*; +import de.caritas.cob.userservice.api.adapters.web.dto.SessionConsultantForUserDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.UserDataResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.validation.MandatoryFieldsProvider; import de.caritas.cob.userservice.api.adapters.web.mapping.ConsultantDtoMapper; import de.caritas.cob.userservice.api.adapters.web.mapping.UserDtoMapper; @@ -56,9 +59,8 @@ import de.caritas.cob.userservice.api.service.session.SessionService; import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.api.tenant.TenantContext; +import jakarta.servlet.http.Cookie; import java.util.*; -import javax.servlet.http.Cookie; -import lombok.val; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.hibernate.service.spi.ServiceException; @@ -368,7 +370,7 @@ void setUp() { @Test void userExists_Should_Return404_When_UserDoesNotExist() throws Exception { /* given */ - val username = "john@doe.com"; + final var username = "john@doe.com"; when(identityClient.isUsernameAvailable(username)).thenReturn(Boolean.TRUE); /* when */ mvc.perform(get("/users/{username}", username).accept(MediaType.APPLICATION_JSON)) @@ -379,7 +381,7 @@ void userExists_Should_Return404_When_UserDoesNotExist() throws Exception { @Test void userExists_Should_Return200_When_UserDoesExist() throws Exception { /* given */ - val username = "john@doe.com"; + final var username = "john@doe.com"; when(identityClient.isUsernameAvailable(username)).thenReturn(Boolean.FALSE); /* when */ diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java index ecc2e2d31..9b941a0d2 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java @@ -79,6 +79,7 @@ import de.caritas.cob.userservice.api.port.out.UserAgencyRepository; import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.api.testConfig.TestAgencyControllerApi; +import jakarta.servlet.http.Cookie; import java.lang.reflect.Method; import java.net.URI; import java.time.LocalDateTime; @@ -92,7 +93,6 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import javax.servlet.http.Cookie; import org.apache.commons.lang3.RandomStringUtils; import org.bson.Document; import org.bson.conversions.Bson; @@ -187,7 +187,7 @@ class UserControllerSessionE2EIT { @TestConfiguration static class TestConfig { @Bean(name = "initializeFeedbackChat") - public Boolean initializeFeedbackChat() { + Boolean initializeFeedbackChat() { return false; } } diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilterTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilterTest.java index 264cb0d3d..a1441c22a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilterTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilterTest.java @@ -3,11 +3,11 @@ import de.caritas.cob.userservice.api.admin.service.tenant.TenantService; import de.caritas.cob.userservice.api.tenant.TenantResolverService; import de.caritas.cob.userservice.tenantservice.generated.web.model.RestrictedTenantDTO; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java index f6a4cb782..75faac02f 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/StatelessCsrfFilterTest.java @@ -10,12 +10,12 @@ import de.caritas.cob.userservice.api.config.CsrfSecurityProperties; import de.caritas.cob.userservice.api.config.CsrfSecurityProperties.ConfigProperty; import de.caritas.cob.userservice.api.config.CsrfSecurityProperties.Whitelist; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java index d5468a00f..274f6b51e 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java @@ -29,13 +29,13 @@ import de.caritas.cob.userservice.api.testConfig.TestAgencyControllerApi; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.RolesDTO; +import jakarta.persistence.EntityManager; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; -import javax.persistence.EntityManager; import org.jeasy.random.EasyRandom; import org.jeasy.random.EasyRandomParameters; import org.jeasy.random.FieldPredicates; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java index 983e9aac6..c4a729576 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java @@ -6,7 +6,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.tenant.TenantContext; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import org.apache.lucene.search.Query; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.query.dsl.BooleanJunction; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java index 63bcd3b88..0849e7edd 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceIT.java @@ -6,9 +6,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.*; import de.caritas.cob.userservice.api.AccountManager; import de.caritas.cob.userservice.api.UserServiceApplication; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java index c844bbc08..bfee3b88d 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminServiceTest.java @@ -2,10 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.*; import de.caritas.cob.userservice.api.AccountManager; import de.caritas.cob.userservice.api.admin.service.consultant.create.CreateConsultantSaga; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java index ef3806053..68b7fed56 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/validation/UserAccountInputValidatorTest.java @@ -16,8 +16,8 @@ import de.caritas.cob.userservice.api.adapters.web.dto.CreateConsultantDTO; import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException; import de.caritas.cob.userservice.api.exception.keycloak.KeycloakException; -import javax.validation.Path; -import javax.validation.Validator; +import jakarta.validation.Path; +import jakarta.validation.Validator; import org.hibernate.validator.internal.engine.ConstraintViolationImpl; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java index e04bffbdf..369ab0275 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/user/anonymous/AnonymousUsernameRegistryTest.java @@ -22,14 +22,11 @@ import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; -import org.powermock.modules.junit4.PowerMockRunner; -@RunWith(PowerMockRunner.class) @MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT) class AnonymousUsernameRegistryTest { diff --git a/src/test/java/de/caritas/cob/userservice/api/config/auth/IdentityConfigTest.java b/src/test/java/de/caritas/cob/userservice/api/config/auth/IdentityConfigTest.java index dd4461b5f..63c400e0e 100644 --- a/src/test/java/de/caritas/cob/userservice/api/config/auth/IdentityConfigTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/config/auth/IdentityConfigTest.java @@ -3,11 +3,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; import java.util.Locale; import java.util.Set; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterAll; diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/AssignChatFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/AssignChatFacadeTest.java index d37627598..9c4e8f3e0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/AssignChatFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/AssignChatFacadeTest.java @@ -43,7 +43,7 @@ void assignChat_Should_ThrowNotFoundException_WhenChatDoesNotExist() { verify(chatService).getChatByGroupId(RC_GROUP_ID); assertThat(exception.getMessage()) - .isEqualTo(String.format("Chat with group id %s not found", RC_GROUP_ID)); + .isEqualTo("Chat with group id %s not found".formatted(RC_GROUP_ID)); } @Test @@ -58,8 +58,7 @@ void assignChat_Should_ThrowNotFoundException_WhenUserDoesNotExist() { () -> assignChatFacade.assignChat(RC_GROUP_ID, authenticatedUser)); verify(userService).getUserViaAuthenticatedUser(authenticatedUser); - assertThat(exception.getMessage()) - .isEqualTo(String.format("User with id %s not found", USER_ID)); + assertThat(exception.getMessage()).isEqualTo("User with id %s not found".formatted(USER_ID)); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java index a7bab1c37..b1367e8d3 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/CreateEnquiryMessageFacadeTest.java @@ -87,10 +87,10 @@ import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.SessionDataInitializingDTO; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.WelcomeMessageDTO; import de.caritas.cob.userservice.messageservice.generated.web.model.MessageResponseDTO; +import jakarta.servlet.http.HttpServletRequest; import java.util.Collections; import java.util.List; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index a64d58dea..38837b89b 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -51,8 +51,8 @@ import de.caritas.cob.userservice.api.tenant.TenantContext; import de.caritas.cob.userservice.api.tenant.TenantContextProvider; import de.caritas.cob.userservice.statisticsservice.generated.web.model.UserRole; +import jakarta.servlet.http.HttpServletRequest; import java.util.List; -import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java index afc02c6a0..1a671d0bd 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignSessionFacadeTest.java @@ -49,9 +49,9 @@ import de.caritas.cob.userservice.api.service.statistics.event.AssignSessionStatisticsEvent; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; import de.caritas.cob.userservice.statisticsservice.generated.web.model.UserRole; +import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; -import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/caritas/cob/userservice/api/port/out/ConsultantRepositoryIT.java b/src/test/java/de/caritas/cob/userservice/api/port/out/ConsultantRepositoryIT.java index 7be751d85..cec8d146d 100644 --- a/src/test/java/de/caritas/cob/userservice/api/port/out/ConsultantRepositoryIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/port/out/ConsultantRepositoryIT.java @@ -13,6 +13,8 @@ import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.ConsultantAgency; import de.caritas.cob.userservice.api.model.Language; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.PositiveOrZero; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashSet; @@ -20,8 +22,6 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.PositiveOrZero; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java index cc27f520c..249dae818 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/ConsultingTypeServiceTest.java @@ -11,11 +11,11 @@ import de.caritas.cob.userservice.consultingtypeservice.generated.ApiClient; import de.caritas.cob.userservice.consultingtypeservice.generated.web.ConsultingTypeControllerApi; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.BasicConsultingTypeResponseDTO; +import jakarta.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.List; import java.util.Random; import java.util.stream.Collectors; -import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java index 1d46e5a0c..b70562e1e 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java @@ -185,7 +185,7 @@ void fetchGroupIdWithConsultantAndUser_Should_Return_BadRequestException() { session.setIsConsultantDirectlySet(false); sessionService.saveSession(session); assertThrows( - javax.ws.rs.BadRequestException.class, + jakarta.ws.rs.BadRequestException.class, () -> { sessionService.findGroupIdByConsultantAndUser( "473f7c4b-f011-4fc2-847c-ceb636a5b399", "1da238c6-cd46-4162-80f1-bff74eafe77f"); diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java index dc6c81075..017587405 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java @@ -4,9 +4,9 @@ import static org.mockito.Mockito.when; import com.google.common.collect.Maps; +import jakarta.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolverTest.java index 82aac35e3..3ab63aae7 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/CustomHeaderTenantResolverTest.java @@ -4,8 +4,8 @@ import static org.mockito.Mockito.when; import de.caritas.cob.userservice.api.service.httpheader.TenantHeaderSupplier; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolverTest.java index 19aad5716..76ded320e 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/MultitenancyWithSingleDomainTenantResolverTest.java @@ -10,8 +10,8 @@ import de.caritas.cob.userservice.api.service.ConsultantService; import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.httpheader.HttpHeadersResolver; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolverTest.java index 4bfc92084..4c9321e34 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/SubdomainTenantResolverTest.java @@ -5,8 +5,8 @@ import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.SubdomainExtractor; import de.caritas.cob.userservice.api.admin.service.tenant.TenantService; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java index bb525fd25..81376e225 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java @@ -3,7 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.assertj.core.util.Sets; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java index 4b6c55f98..d8af76430 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java @@ -4,8 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; +import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import javax.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java index b2dd7f18f..47e3bbc45 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java @@ -14,7 +14,7 @@ public class ApiControllerTestConfig { @Bean @Primary - public AgencyServiceApiClientConfig agencyServiceApiClientConfig() { + AgencyServiceApiClientConfig agencyServiceApiClientConfig() { return new AgencyServiceApiClientConfig() { @Override public AgencyControllerApi agencyControllerApi( @@ -26,7 +26,7 @@ public AgencyControllerApi agencyControllerApi( @Bean @Primary - public MailServiceApiControllerFactory mailServiceApiControllerFactory() { + MailServiceApiControllerFactory mailServiceApiControllerFactory() { return new MailServiceApiControllerFactory() { @Override public MailsControllerApi createControllerApi() { diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/ConsultingTypeManagerTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/ConsultingTypeManagerTestConfig.java index 40677d7e7..bd8d1bcd8 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/ConsultingTypeManagerTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/ConsultingTypeManagerTestConfig.java @@ -14,7 +14,7 @@ public class ConsultingTypeManagerTestConfig { @Bean - public ConsultingTypeManager consultingTypeManager( + ConsultingTypeManager consultingTypeManager( ConsultingTypeService consultingTypeService, @Qualifier("initializeFeedbackChat") Optional initializeFeedbackChat) { return new ConsultingTypeManager(consultingTypeService) { diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/KeycloakTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/KeycloakTestConfig.java index e6897b416..20b2155cd 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/KeycloakTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/KeycloakTestConfig.java @@ -26,7 +26,7 @@ public class KeycloakTestConfig { @Bean - public KeycloakService keycloakService( + KeycloakService keycloakService( RestTemplate restTemplate, AuthenticatedUser authenticatedUser, UserAccountInputValidator userAccountInputValidator, diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/RabbitMqTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/RabbitMqTestConfig.java index 98d125be1..ba146310b 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/RabbitMqTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/RabbitMqTestConfig.java @@ -24,7 +24,7 @@ ConnectionFactory connectionFactory() { } @Bean - public Declarables topicBindings() { + Declarables topicBindings() { Queue assignSessionStatisticEventQueue = new Queue(QUEUE_NAME_ASSIGN_SESSION, true); TopicExchange topicExchange = new TopicExchange(STATISTICS_EXCHANGE_NAME, true, false); diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/RocketChatTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/RocketChatTestConfig.java index da650a094..237d841cc 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/RocketChatTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/RocketChatTestConfig.java @@ -31,7 +31,7 @@ public class RocketChatTestConfig { @MockBean MongoClient mongoClient; @Bean - public RocketChatService rocketChatService( + RocketChatService rocketChatService( RestTemplate restTemplate, RocketChatCredentialsProvider rocketChatCredentialsProvider, RocketChatConfig rocketChatConfig, From 9996377687206080c22af247db90cff2fc92ba45 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 19 Dec 2024 18:04:14 +0100 Subject: [PATCH 02/47] feat: upgrade to spring boot 3.0.X --- pom2.xml | 643 ------------------------------------------------------- 1 file changed, 643 deletions(-) delete mode 100644 pom2.xml diff --git a/pom2.xml b/pom2.xml deleted file mode 100644 index 3acb98f67..000000000 --- a/pom2.xml +++ /dev/null @@ -1,643 +0,0 @@ - - - 4.0.0 - - Caritas Online Beratung: AgencyService - - de.caritas.cob - agencyservice - 0.0.1-SNAPSHOT - jar - - AgencyService - - - org.springframework.boot - spring-boot-starter-parent - 3.3.6 - - - - - UTF-8 - UTF-8 - 17 - 17.0.0 - - 2.17.1 - 6.6.0 - 0.2.3 - 2.1.1 - 3.11 - 4.23.2 - 1.4.200 - 2.10.6 - 5.0.0 - 3.0.6 - 4.23.2 - 3.0.0 - 6.3.4 - 2.9.2 - 2.10.0 - 3.0.1 - 17 - 17 - 6.1.1.Final - 3.0.0 - - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-cache - - - org.springframework.boot - spring-boot-starter-hateoas - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-oauth2-resource-server - - - org.springframework.boot - spring-boot-autoconfigure - - - org.springframework.boot - spring-boot-starter-freemarker - - - org.springframework.security - spring-security-web - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-core - - - - org.springframework.boot - spring-boot-starter-actuator - - - - - org.openapitools - openapi-generator-maven-plugin - ${openapi.generator.maven.version} - provided - - - org.openapitools - jackson-databind-nullable - ${jackson-databind-nullable.version} - - - org.codehaus.plexus - plexus-utils - 3.3.0 - - - io.swagger.parser.v3 - swagger-parser - 2.1.15 - - - - org.sonatype.plexus - plexus-build-api - 0.0.7 - provided - - - org.codehaus.plexus - plexus-utils - - - - - - - org.keycloak - keycloak-spring-security-adapter - ${keycloak.version} - - - org.keycloak - keycloak-spring-boot-starter - ${keycloak.version} - - - org.keycloak - keycloak-admin-client - ${keycloak.version} - - - jakarta.ws.rs - jakarta.ws.rs-api - - - - - org.projectlombok - lombok - true - - - - - - org.apache.commons - commons-lang3 - - - - com.github.jknack - handlebars - 4.3.1 - - - - - org.liquibase - liquibase-maven-plugin - ${liquibase-maven-plugin.version} - - - org.liquibase - liquibase-core - - - - - - org.liquibase - liquibase-core - - - - - org.apache.httpcomponents.client5 - httpclient5 - - - - net.sf.ehcache - ehcache - 2.10.9.2 - - - com.fasterxml.jackson.core - jackson-databind - - - - - - - org.mariadb.jdbc - mariadb-java-client - - - - org.apache.logging.log4j - log4j-core - - - org.apache.logging.log4j - log4j-api - - - org.apache.logging.log4j - log4j-to-slf4j - - - - - - org.jeasy - easy-random-core - ${easy-random-core.version} - test - - - org.yaml - snakeyaml - - - - - - - - com.h2database - h2 - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - - com.c4-soft.springaddons - spring-security-oauth2-test-webmvc-addons - ${spring-security-oauth2-test-webmvc-addons.version} - test - - - - - ${project.name} - - - src/main/resources - true - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - org.openapitools - openapi-generator-maven-plugin - ${openapi.generator.maven.version} - - - agency-service - - generate - - - - true - / - true - - ${project.basedir}/api/agencyservice.yaml - spring - ${project.groupId}.${project.artifactId}.generated.api.controller - - ${project.groupId}.${project.artifactId}.api.model - true - target/generated-sources - - - - agency-admin-service - - generate - - - - true - / - true - - ${project.basedir}/api/agencyadminservice.yaml - spring - ${project.groupId}.${project.artifactId}.generated.api.admin.controller - - ${project.groupId}.${project.artifactId}.api.model - true - target/generated-sources - - - - - agency-admin-service-markdown - - generate - - - - - ${project.basedir}/api/agencyadminservice.yaml - markdown - target/generated-sources/markdown/agencyservice - ./ - model - false - false - false - - - - - user-admin-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - true - - ${project.basedir}/services/useradminservice.yaml - java - true - false - false - ${project.groupId}.${project.artifactId}.useradminservice.generated.web - - - ${project.groupId}.${project.artifactId}.useradminservice.generated.web.model - - - - - consulting-type-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - true - - ${project.basedir}/services/consultingtypeservice.yaml - java - true - false - false - - ${project.groupId}.${project.artifactId}.consultingtypeservice.generated.web - - - ${project.groupId}.${project.artifactId}.consultingtypeservice.generated.web.model - - - - - application-settings-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - true - - ${project.basedir}/services/applicationsettingsservice.yml - java - true - false - false - - ${project.groupId}.${project.artifactId}.applicationsettingsservice.generated.web - - - ${project.groupId}.${project.artifactId}.applicationsettingsservice.generated.web.model - - - - - tenant-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - true - - ${project.basedir}/services/tenantservice.yaml - java - true - false - false - - ${project.groupId}.${project.artifactId}.tenantservice.generated.web - - - ${project.groupId}.${project.artifactId}.tenantservice.generated.web.model - - - OffsetDateTime=LocalDateTime - - - java.time.OffsetDateTime=java.time.LocalDateTime - - - - - topic-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - - ${project.basedir}/services/topicservice.yaml - java - true - false - false - - ${project.groupId}.${project.artifactId}.topicservice.generated.web - - - ${project.groupId}.${project.artifactId}.topicservice.generated.web.model - - - - - appointment-service-client-model - generate-sources - - generate - - - - / - resttemplate - java8 - - ${project.basedir}/services/appointmentService.yaml - java - true - false - false - - ${project.groupId}.${project.artifactId}.appointmentservice.generated.web - - - ${project.groupId}.${project.artifactId}.appointmentservice.generated.web.model - - - - - - - - org.liquibase - liquibase-maven-plugin - - src/main/resources/liquibase.properties - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.6.0 - - - validate - validate - - google_checks_light.xml - true - true - true - true - warning - true - - - check - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - --enable-preview - ${java.version} - - - - org.apache.maven.plugins - maven-surefire-plugin - - - true - --enable-preview - - - - unit-tests - test - - test - - - false - - **/*Test.java - - - - - integration-tests - integration-test - - test - - - false - - **/*IT.* - - - - - - - org.openrewrite.maven - rewrite-maven-plugin - 5.46.1 - - true - - org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 - - - - - org.openrewrite.recipe - rewrite-spring - 5.24.1 - - - - - - - - local - - local - - - true - - - - dev - - dev - - - - prod - - prod - - - - - From 1f1803f0c8f08cbd74992b690bc6bc1df183bd61 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 27 Dec 2024 17:36:19 +0100 Subject: [PATCH 03/47] feat: upgrade to spring boot 3.0.X --- pom.xml | 26 ++++- .../cob/userservice/api/model/Admin.java | 3 - .../cob/userservice/api/model/Consultant.java | 3 - .../api/model/ConsultantAgency.java | 3 - .../cob/userservice/api/model/Session.java | 3 - .../cob/userservice/api/model/User.java | 3 - .../userservice/api/model/package-info.java | 11 +++ .../message/MessageServiceProvider.java | 4 +- src/main/resources/hibernate.properties | 2 +- .../keycloak/KeycloakServiceTest.java | 2 +- .../ConversationControllerE2EIT.java | 4 +- .../web/controller/UserControllerE2EIT.java | 3 +- .../UserControllerSessionE2EIT.java | 6 +- .../admin/facade/ConsultantAdminFacadeIT.java | 8 +- .../ConsultantAdminFilterServiceBase.java | 2 +- ...tantAdminFilterTenantAwareServiceTest.java | 97 ------------------- ...sultantAgencyRelationCreatorServiceIT.java | 2 +- ...tRecordAgencyCreationInputAdapterTest.java | 2 +- ...mousEnquiryConversationListProviderIT.java | 5 +- ...SessionConversationListProviderTestIT.java | 5 +- ...SessionConversationListProviderTestIT.java | 5 +- ...eredEnquiryConversationListProviderIT.java | 5 +- .../LiveEventNotificationServiceTest.java | 14 +-- .../tenant/AccessTokenTenantResolverTest.java | 11 ++- .../TechnicalUserTenantResolverTest.java | 15 ++- .../api/tenant/TenantResolverServiceTest.java | 11 ++- .../testConfig/ApiControllerTestConfig.java | 2 +- 27 files changed, 100 insertions(+), 157 deletions(-) create mode 100644 src/main/java/de/caritas/cob/userservice/api/model/package-info.java delete mode 100644 src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java diff --git a/pom.xml b/pom.xml index f08f213f0..d1a6c1c67 100644 --- a/pom.xml +++ b/pom.xml @@ -141,15 +141,27 @@ - net.minidev - json-smart + org.hibernate.orm + hibernate-core + 6.2.4.Final - + org.hibernate.search hibernate-search-mapper-orm - 6.1.7.Final + 6.2.4.Final + + + org.hibernate + hibernate-core + + + + + + net.minidev + json-smart @@ -235,6 +247,12 @@ commons-lang3 + + + org.apache.httpcomponents.client5 + httpclient5 + + org.apache.commons diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java index 4c2e55c21..c9a29e90d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java @@ -41,9 +41,6 @@ @ToString @Builder @EntityListeners(AuditingEntityListener.class) -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Admin implements TenantAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java index 9a284277c..8566c995e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java @@ -52,9 +52,6 @@ @Setter @Builder @Indexed -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Consultant implements TenantAware, NotificationsAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java index cac6191c1..dd0c65733 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java @@ -30,9 +30,6 @@ @Builder @Getter @Setter -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class ConsultantAgency implements TenantAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Session.java b/src/main/java/de/caritas/cob/userservice/api/model/Session.java index 2ce42c129..488897fe3 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Session.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Session.java @@ -49,9 +49,6 @@ @Getter @Setter @ToString -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class Session implements TenantAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/User.java b/src/main/java/de/caritas/cob/userservice/api/model/User.java index ef0795ddb..eac7113c9 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/User.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/User.java @@ -42,9 +42,6 @@ @Setter @ToString @EntityListeners(AuditingEntityListener.class) -@FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)}) @Filter(name = "tenantFilter", condition = "tenant_id = :tenantId") public class User implements TenantAware, NotificationsAware { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/package-info.java b/src/main/java/de/caritas/cob/userservice/api/model/package-info.java new file mode 100644 index 000000000..e1fe04af8 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/model/package-info.java @@ -0,0 +1,11 @@ +@FilterDefs({ + @FilterDef( + name = "tenantFilter", + parameters = {@ParamDef(name = "tenantId", type = Long.class)} + ) +}) +package de.caritas.cob.userservice.api.model; + +import org.hibernate.annotations.FilterDef; +import org.hibernate.annotations.FilterDefs; +import org.hibernate.annotations.ParamDef; \ No newline at end of file diff --git a/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java b/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java index fdc14aafe..4fbd4ec6b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/message/MessageServiceProvider.java @@ -16,7 +16,6 @@ import de.caritas.cob.userservice.api.service.httpheader.SecurityHeaderSupplier; import de.caritas.cob.userservice.api.service.httpheader.TenantHeaderSupplier; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; -import de.caritas.cob.userservice.messageservice.generated.ApiClient; import de.caritas.cob.userservice.messageservice.generated.web.MessageControllerApi; import de.caritas.cob.userservice.messageservice.generated.web.model.AliasMessageDTO; import de.caritas.cob.userservice.messageservice.generated.web.model.AliasOnlyMessageDTO; @@ -181,7 +180,8 @@ private void postAliasOnlyMessage( } } - private void addDefaultHeaders(ApiClient apiClient) { + private void addDefaultHeaders( + de.caritas.cob.userservice.messageservice.generated.ApiClient apiClient) { var headers = this.securityHeaderSupplier.getKeycloakAndCsrfHttpHeaders(); tenantHeaderSupplier.addTenantHeader(headers); headers.forEach((key, value) -> apiClient.addDefaultHeader(key, value.iterator().next())); diff --git a/src/main/resources/hibernate.properties b/src/main/resources/hibernate.properties index 02b0dc11e..e06b03da8 100644 --- a/src/main/resources/hibernate.properties +++ b/src/main/resources/hibernate.properties @@ -1 +1 @@ -hibernate.search.default.directory_provider=local-heap +hibernate.search.backend.type=lucene \ No newline at end of file diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index 1ee3e1b6d..bdae5da19 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -41,9 +41,9 @@ import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; import jakarta.ws.rs.BadRequestException; -import jakarta.ws.rs.core.Response; import java.util.HashMap; import java.util.List; +import javax.ws.rs.core.Response; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java index 9de01274e..f16eed55c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java @@ -38,13 +38,13 @@ import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.consultingtypeservice.generated.web.ConsultingTypeControllerApi; import de.caritas.cob.userservice.topicservice.generated.web.TopicControllerApi; +import jakarta.servlet.http.Cookie; import java.net.URI; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import javax.servlet.http.Cookie; import lombok.NonNull; import lombok.SneakyThrows; import org.apache.commons.lang3.RandomStringUtils; @@ -399,7 +399,7 @@ private void givenAValidRocketChatSystemUser() throws RocketChatUserNotInitializ } private void givenConsultingTypeServiceResponse(Integer consultingTypeId) { - consultingTypeControllerApi.getApiClient().setBasePath("https://www.google.de/"); + when(restTemplate.getUriTemplateHandler()) .thenReturn( new UriTemplateHandler() { diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java index 033f6c014..f5750b4b9 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java @@ -95,6 +95,7 @@ import de.caritas.cob.userservice.topicservice.generated.ApiClient; import de.caritas.cob.userservice.topicservice.generated.web.TopicControllerApi; import de.caritas.cob.userservice.topicservice.generated.web.model.TopicDTO; +import jakarta.servlet.http.Cookie; import java.net.URI; import java.time.LocalDate; import java.util.ArrayList; @@ -105,7 +106,6 @@ import java.util.Set; import java.util.UUID; import java.util.stream.StreamSupport; -import javax.servlet.http.Cookie; import lombok.NonNull; import lombok.SneakyThrows; import org.apache.commons.lang3.RandomStringUtils; @@ -1989,7 +1989,6 @@ private void givenAValidUser() { } private void givenConsultingTypeServiceResponse(Integer consultingTypeId) { - consultingTypeControllerApi.getApiClient().setBasePath("https://www.google.de/"); when(restTemplate.getUriTemplateHandler()) .thenReturn( new UriTemplateHandler() { diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java index 9b941a0d2..6ef716247 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java @@ -432,7 +432,7 @@ void getSessionsForAuthenticatedConsultantShouldReturnSessionsLastMessageTypeE2e givenAValidUser(); givenAValidConsultant(true); givenASessionInProgress(); - givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2EE_ACTIVATED, null); + givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2_EE_ACTIVATED, null); givenAnEmptyRocketChatGetSubscriptionsResponse(); mockMvc @@ -461,7 +461,7 @@ void getSessionsForAuthenticatedConsultantShouldReturnInformationAboutDeletedUse givenADeletedUser(false); givenAValidConsultant(true); givenASessionInProgress(); - givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2EE_ACTIVATED, null); + givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2_EE_ACTIVATED, null); givenAnEmptyRocketChatGetSubscriptionsResponse(); mockMvc @@ -545,7 +545,7 @@ void getSessionsForAuthenticatedUserShouldReturnSessionsLastMessageTypeE2eeActiv givenAValidConsultant(); givenASessionInProgress(); givenAValidRocketChatSystemUser(); - givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2EE_ACTIVATED, null); + givenAValidRocketChatGetRoomsResponse(session.getGroupId(), MessageType.E2_EE_ACTIVATED, null); givenAnEmptyRocketChatGetSubscriptionsResponse(); user.getSessions() .forEach(session -> givenAValidRocketChatInfoUserResponse(session.getConsultant())); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java index 274f6b51e..93df68de3 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/facade/ConsultantAdminFacadeIT.java @@ -78,7 +78,7 @@ class ConsultantAdminFacadeIT { 1, 100, new ConsultantFilter(), - new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.ASC)); + new Sort().field(FieldEnum.FIRST_NAME).order(OrderEnum.ASC)); var resultConsultant = searchResult.getEmbedded().stream() .filter( @@ -102,7 +102,7 @@ class ConsultantAdminFacadeIT { 1, 100, new ConsultantFilter(), - new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.ASC)); + new Sort().field(FieldEnum.FIRST_NAME).order(OrderEnum.ASC)); var resultConsultant = searchResult.getEmbedded().stream() .filter( @@ -201,7 +201,7 @@ void findFilteredConsultants_Should_retrieveConsultantAfterAddingRelationToAgenc var searchResult = this.consultantAdminFacade.findFilteredConsultants( - 1, 100, consultantFilter, new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.ASC)); + 1, 100, consultantFilter, new Sort().field(FieldEnum.FIRST_NAME).order(OrderEnum.ASC)); assertThat(searchResult.getEmbedded(), hasSize(0)); @@ -209,7 +209,7 @@ void findFilteredConsultants_Should_retrieveConsultantAfterAddingRelationToAgenc searchResult = this.consultantAdminFacade.findFilteredConsultants( - 1, 100, consultantFilter, new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.ASC)); + 1, 100, consultantFilter, new Sort().field(FieldEnum.FIRST_NAME).order(OrderEnum.ASC)); assertThat(searchResult.getEmbedded(), hasSize(greaterThanOrEqualTo(1))); } diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java index 74362dafe..06d284992 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceBase.java @@ -205,7 +205,7 @@ public void findFilteredConsultants_Should_returnResultWithoutPreviousLink_When_ public void findFilteredConsultants_Should_orderResultByFirstNameDESC_When_sortParameterIsGiven() { - var sort = new Sort().field(FieldEnum.FIRSTNAME).order(OrderEnum.DESC); + var sort = new Sort().field(FieldEnum.FIRST_NAME).order(OrderEnum.DESC); var result = this.consultantAdminFilterService.findFilteredConsultants( diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java deleted file mode 100644 index c4a729576..000000000 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterTenantAwareServiceTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package de.caritas.cob.userservice.api.admin.service.consultant; - -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; -import de.caritas.cob.userservice.api.model.Consultant; -import de.caritas.cob.userservice.api.tenant.TenantContext; -import jakarta.persistence.EntityManagerFactory; -import org.apache.lucene.search.Query; -import org.hibernate.search.jpa.FullTextEntityManager; -import org.hibernate.search.query.dsl.BooleanJunction; -import org.hibernate.search.query.dsl.MustJunction; -import org.hibernate.search.query.dsl.QueryBuilder; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Answers; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class ConsultantAdminFilterTenantAwareServiceTest { - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - FullTextEntityManager fullTextEntityManager; - - @Mock EntityManagerFactory entityManagerFactory; - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - QueryBuilder queryBuilder; - - @Mock BooleanJunction booleanJunction; - - @Mock MustJunction mustJunction; - - @Mock MustJunction secondMustJunction; - - @InjectMocks ConsultantAdminFilterTenantAwareService consultantAdminFilterTenantAwareService; - - @Test - void - buildFilteredQuery_Should_CreateFilteredQuery_WithoutTenantFilter_If_TenantContextIsSuperAdmin() { - // given - TenantContext.setCurrentTenant(TenantContext.TECHNICAL_TENANT_ID); - when(fullTextEntityManager - .getSearchFactory() - .buildQueryBuilder() - .forEntity(Consultant.class) - .get()) - .thenReturn(queryBuilder); - when(queryBuilder.bool()).thenReturn(booleanJunction); - when(booleanJunction.must(Mockito.any(Query.class))).thenReturn(mustJunction); - - // when - consultantAdminFilterTenantAwareService.buildFilteredQuery( - new ConsultantFilter().agencyId(59L), fullTextEntityManager); - - // then - ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - verify(fullTextEntityManager) - .createFullTextQuery(captor.capture(), Mockito.eq(Consultant.class)); - verify(booleanJunction).must(Mockito.any(Query.class)); - verify(mustJunction, Mockito.never()).must(Mockito.any(Query.class)); - TenantContext.clear(); - } - - @Test - void - buildFilteredQuery_Should_CreateFilteredQuery_WithTenantFilter_When_TenantContextIsNotSuperAdmin() { - // given - TenantContext.setCurrentTenant(1L); - when(fullTextEntityManager - .getSearchFactory() - .buildQueryBuilder() - .forEntity(Consultant.class) - .get()) - .thenReturn(queryBuilder); - when(queryBuilder.bool()).thenReturn(booleanJunction); - when(booleanJunction.must(Mockito.any(Query.class))).thenReturn(mustJunction); - when(mustJunction.must(null)).thenReturn(secondMustJunction); - - // when - consultantAdminFilterTenantAwareService.buildFilteredQuery( - new ConsultantFilter().agencyId(59L), fullTextEntityManager); - - // then - ArgumentCaptor captor = ArgumentCaptor.forClass(Query.class); - verify(fullTextEntityManager) - .createFullTextQuery(captor.capture(), Mockito.eq(Consultant.class)); - verify(booleanJunction, Mockito.times(2)).must(Mockito.any(Query.class)); - verify(mustJunction).must(Mockito.any()); - TenantContext.clear(); - } -} diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java index 2c45294fc..5bcea355a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceIT.java @@ -6,7 +6,7 @@ import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.hibernate.search.util.impl.CollectionHelper.asSet; +import static org.hibernate.validator.internal.util.CollectionHelper.asSet; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java index 1afad8d6b..df06fc1e3 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ImportRecordAgencyCreationInputAdapterTest.java @@ -3,7 +3,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; -import static org.hibernate.search.util.impl.CollectionHelper.asSet; +import static org.hibernate.validator.internal.util.CollectionHelper.asSet; import org.junit.jupiter.api.Test; diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java index 55da81287..1e93fb024 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/AnonymousEnquiryConversationListProviderIT.java @@ -31,6 +31,7 @@ import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.api.testConfig.ConsultingTypeManagerTestConfig; +import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.collections4.iterators.PeekingIterator; @@ -120,7 +121,9 @@ void buildConversations_Should_returnElementsInExpectedOrder() { ConsultantSessionResponseDTO current = peeker.next(); ConsultantSessionResponseDTO next = peeker.peek(); if (nonNull(next)) { - assertThat(next.getLatestMessage(), greaterThanOrEqualTo(current.getLatestMessage())); + assertThat( + (Date) next.getLatestMessage(), + greaterThanOrEqualTo((Date) current.getLatestMessage())); } } } diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java index 825466736..75cf3207e 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedSessionConversationListProviderTestIT.java @@ -28,6 +28,7 @@ import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.api.service.user.UserAccountService; import java.util.Collections; +import java.util.Date; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @@ -110,7 +111,9 @@ void buildConversations_Should_returnElementsInExpectedOrder() { ConsultantSessionResponseDTO current = peeker.next(); ConsultantSessionResponseDTO next = peeker.peek(); if (nonNull(next)) { - assertThat(next.getLatestMessage(), greaterThanOrEqualTo(current.getLatestMessage())); + assertThat( + (Date) next.getLatestMessage(), + greaterThanOrEqualTo((Date) current.getLatestMessage())); } } } diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java index 5d4bc128a..333fa535c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/ArchivedTeamSessionConversationListProviderTestIT.java @@ -28,6 +28,7 @@ import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.api.service.user.UserAccountService; import java.util.Collections; +import java.util.Date; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @@ -111,7 +112,9 @@ void buildConversations_Should_returnElementsInExpectedOrder() { ConsultantSessionResponseDTO current = peeker.next(); ConsultantSessionResponseDTO next = peeker.peek(); if (nonNull(next)) { - assertThat(next.getLatestMessage(), greaterThanOrEqualTo(current.getLatestMessage())); + assertThat( + (Date) next.getLatestMessage(), + greaterThanOrEqualTo((Date) current.getLatestMessage())); } } } diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java index ec1c47833..7ed163240 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/provider/RegisteredEnquiryConversationListProviderIT.java @@ -25,6 +25,7 @@ import de.caritas.cob.userservice.api.port.out.SessionRepository; import de.caritas.cob.userservice.api.port.out.UserRepository; import de.caritas.cob.userservice.api.service.user.UserAccountService; +import java.util.Date; import java.util.List; import java.util.Random; import java.util.stream.Collectors; @@ -111,7 +112,9 @@ public void buildConversations_Should_returnElementsInExpectedOrder() { ConsultantSessionResponseDTO current = peeker.next(); ConsultantSessionResponseDTO next = peeker.peek(); if (nonNull(next)) { - assertThat(next.getLatestMessage(), greaterThanOrEqualTo(current.getLatestMessage())); + assertThat( + (Date) next.getLatestMessage(), + greaterThanOrEqualTo((Date) current.getLatestMessage())); } } } diff --git a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java index 2fde9b046..851744603 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/liveevents/LiveEventNotificationServiceTest.java @@ -1,8 +1,8 @@ package de.caritas.cob.userservice.api.service.liveevents; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUSCONVERSATIONFINISHED; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUSENQUIRYACCEPTED; -import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.DIRECTMESSAGE; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUS_CONVERSATION_FINISHED; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.ANONYMOUS_ENQUIRY_ACCEPTED; +import static de.caritas.cob.userservice.liveservice.generated.web.model.EventType.DIRECT_MESSAGE; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; @@ -41,7 +41,7 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class LiveEventNotificationServiceTest { - private static final LiveEventMessage MESSAGE = new LiveEventMessage().eventType(DIRECTMESSAGE); + private static final LiveEventMessage MESSAGE = new LiveEventMessage().eventType(DIRECT_MESSAGE); @InjectMocks private LiveEventNotificationService liveEventNotificationService; @@ -154,7 +154,7 @@ public void sendLiveNewAnonymousEnquiryEventToUsers_Should_TriggerLiveEventWithC ArgumentCaptor captor = ArgumentCaptor.forClass(LiveEventMessage.class); verify(liveControllerApi, times(1)).sendLiveEvent(captor.capture()); - assertEquals(EventType.NEWANONYMOUSENQUIRY, captor.getValue().getEventType()); + assertEquals(EventType.NEW_ANONYMOUS_ENQUIRY, captor.getValue().getEventType()); } @Test @@ -179,7 +179,7 @@ public void sendAcceptAnonymousEnquiryEventToUser_Should_triggerLiveEvent_When_u verify(this.liveControllerApi, times(1)) .sendLiveEvent( new LiveEventMessage() - .eventType(ANONYMOUSENQUIRYACCEPTED) + .eventType(ANONYMOUS_ENQUIRY_ACCEPTED) .userIds(singletonList("userId"))); } @@ -208,7 +208,7 @@ public void sendLiveFinishedAnonymousConversationToUsers_Should_doNothing_When_u verify(this.liveControllerApi, times(1)) .sendLiveEvent( new LiveEventMessage() - .eventType(ANONYMOUSCONVERSATIONFINISHED) + .eventType(ANONYMOUS_CONVERSATION_FINISHED) .userIds(singletonList("userId")) .eventContent( new StatusSource() diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java index 017587405..d0bfbfd64 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java @@ -7,23 +7,28 @@ import jakarta.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; -import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class AccessTokenTenantResolverTest { @Mock HttpServletRequest authenticatedRequest; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - KeycloakAuthenticationToken token; + @Mock KeycloakAuthenticationToken token; @InjectMocks AccessTokenTenantResolver accessTokenTenantResolver; + @BeforeEach + public void setUp() { + token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); + } + @Test void resolve_Should_ResolveTenantId_When_TenantIdInAccessTokenClaim() { // given diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java index 81376e225..b9d5ac5ff 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java @@ -5,14 +5,15 @@ import jakarta.servlet.http.HttpServletRequest; import org.assertj.core.util.Sets; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken.Access; -import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @@ -20,16 +21,20 @@ class TechnicalUserTenantResolverTest { public static final long TECHNICAL_CONTEXT = 0L; @Mock HttpServletRequest authenticatedRequest; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - KeycloakAuthenticationToken token; + @Mock KeycloakAuthenticationToken token; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - AccessToken accessToken; + @Mock AccessToken accessToken; @Mock Access access; @InjectMocks TechnicalOrSuperAdminUserTenantResolver technicalOrSuperadminUserTenantResolver; + @BeforeEach + public void setUp() { + token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); + accessToken = Mockito.mock(AccessToken.class, Mockito.RETURNS_DEEP_STUBS); + } + @Test void resolve_should_ResolveTechnicalTenantId_ForTechnicalUserRole() { // given diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java index d8af76430..258e0a130 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java @@ -6,12 +6,13 @@ import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; -import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.access.AccessDeniedException; @@ -28,8 +29,7 @@ class TenantResolverServiceTest { @Mock HttpServletRequest nonAuthenticatedRequest; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - KeycloakAuthenticationToken token; + @Mock KeycloakAuthenticationToken token; @InjectMocks TenantResolverService tenantResolverService; @@ -40,6 +40,11 @@ class TenantResolverServiceTest { @Mock private MultitenancyWithSingleDomainTenantResolver multitenancyWithSingleDomainTenantResolver; + @BeforeEach + public void setUp() { + token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); + } + @Test void resolve_Should_ResolveFromAccessTokenForAuthenticatedUser_And_PassValidation() { // given diff --git a/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java b/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java index 47e3bbc45..2c60193ae 100644 --- a/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java +++ b/src/test/java/de/caritas/cob/userservice/api/testConfig/ApiControllerTestConfig.java @@ -16,7 +16,7 @@ public class ApiControllerTestConfig { @Primary AgencyServiceApiClientConfig agencyServiceApiClientConfig() { return new AgencyServiceApiClientConfig() { - @Override + public AgencyControllerApi agencyControllerApi( de.caritas.cob.userservice.agencyserivce.generated.ApiClient agencyServiceApiClient) { return new TestAgencyControllerApi(agencyServiceApiClient); From 72123194ebf5d13e17a328fd00cb35caad91bd1e Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 27 Dec 2024 17:40:46 +0100 Subject: [PATCH 04/47] feat: upgrade to spring boot 3.0.X --- .../java/de/caritas/cob/userservice/api/model/Admin.java | 2 -- .../de/caritas/cob/userservice/api/model/Consultant.java | 2 -- .../cob/userservice/api/model/ConsultantAgency.java | 2 -- .../de/caritas/cob/userservice/api/model/Session.java | 2 -- .../java/de/caritas/cob/userservice/api/model/User.java | 2 -- .../caritas/cob/userservice/api/model/package-info.java | 9 ++++----- 6 files changed, 4 insertions(+), 15 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java index c9a29e90d..cd4edcc9f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Admin.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Admin.java @@ -19,8 +19,6 @@ import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java index 8566c995e..e4486d618 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java @@ -29,8 +29,6 @@ import lombok.NonNull; import lombok.Setter; import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; import org.hibernate.annotations.Where; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java index dd0c65733..e1c772d76 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java @@ -19,8 +19,6 @@ import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; /** Represents the relation between consultant and agency */ @Entity diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Session.java b/src/main/java/de/caritas/cob/userservice/api/model/Session.java index 488897fe3..39d001a8c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Session.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Session.java @@ -37,8 +37,6 @@ import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; import org.springframework.lang.Nullable; @Entity diff --git a/src/main/java/de/caritas/cob/userservice/api/model/User.java b/src/main/java/de/caritas/cob/userservice/api/model/User.java index eac7113c9..ea380144f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/User.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/User.java @@ -27,8 +27,6 @@ import lombok.ToString; import lombok.ToString.Exclude; import org.hibernate.annotations.Filter; -import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/package-info.java b/src/main/java/de/caritas/cob/userservice/api/model/package-info.java index e1fe04af8..91cec7829 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/package-info.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/package-info.java @@ -1,11 +1,10 @@ @FilterDefs({ - @FilterDef( - name = "tenantFilter", - parameters = {@ParamDef(name = "tenantId", type = Long.class)} - ) + @FilterDef( + name = "tenantFilter", + parameters = {@ParamDef(name = "tenantId", type = Long.class)}) }) package de.caritas.cob.userservice.api.model; import org.hibernate.annotations.FilterDef; import org.hibernate.annotations.FilterDefs; -import org.hibernate.annotations.ParamDef; \ No newline at end of file +import org.hibernate.annotations.ParamDef; From 82745daf9b82cf33e3ca55175e8d6c1584ca1d14 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Mon, 30 Dec 2024 12:51:40 +0100 Subject: [PATCH 05/47] fix: fix conflicting dependencies --- pom.xml | 17 +++++++++++++---- .../caritas/cob/userservice/api/model/User.java | 2 +- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index d1a6c1c67..ba93bce9e 100644 --- a/pom.xml +++ b/pom.xml @@ -83,6 +83,12 @@ org.springframework.boot spring-boot-starter-data-jpa + + + org.hibernate.orm + hibernate-core + + org.springframework.boot @@ -146,7 +152,6 @@ 6.2.4.Final - org.hibernate.search hibernate-search-mapper-orm @@ -156,6 +161,10 @@ org.hibernate hibernate-core + + org.hibernate.common + hibernate-commons-annotations + @@ -516,17 +525,17 @@ org.openrewrite.maven rewrite-maven-plugin - 5.46.2 + 5.47.0 - org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_0 + org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_1 org.openrewrite.recipe rewrite-spring - 5.24.1 + 5.25.0 diff --git a/src/main/java/de/caritas/cob/userservice/api/model/User.java b/src/main/java/de/caritas/cob/userservice/api/model/User.java index ea380144f..1c23ff3d0 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/User.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/User.java @@ -33,7 +33,7 @@ /** Represents a user */ @Entity -@Table(name = "user") +@Table(name = "`user`") @AllArgsConstructor @NoArgsConstructor @Getter From b1feb9f03dba58fb54271e01124dbe16a030a4e0 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 31 Dec 2024 11:18:45 +0100 Subject: [PATCH 06/47] fix: fix spotless, spring upgrade to 3.1.X --- pom.xml | 37 ++++--------------- .../api/helper/LatestMessageParseUtil.java | 8 ++-- .../keycloak/KeycloakServiceTest.java | 2 +- .../web/controller/UserControllerIT.java | 3 +- 4 files changed, 15 insertions(+), 35 deletions(-) diff --git a/pom.xml b/pom.xml index ba93bce9e..aa62dac76 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ org.springframework.boot spring-boot-starter-parent - 3.0.13 + 3.1.12 @@ -58,9 +58,8 @@ - javax.ws.rs - javax.ws.rs-api - 2.1.1 + jakarta.ws.rs + jakarta.ws.rs-api @@ -149,7 +148,6 @@ org.hibernate.orm hibernate-core - 6.2.4.Final @@ -180,11 +178,6 @@ ${openapi-generator-maven-plugin.version} provided - - io.swagger.core.v3 - swagger-annotations - 2.2.15 - org.openapitools jackson-databind-nullable @@ -200,12 +193,6 @@ plexus-utils 3.3.0 - - - io.springfox - springfox-swagger2 - ${springfox.version} - jakarta.validation jakarta.validation-api @@ -227,10 +214,6 @@ keycloak-admin-client ${keycloak.version} - - jakarta.ws.rs - jakarta.ws.rs-api - @@ -241,7 +224,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 2.1.0 + 2.2.0 @@ -407,20 +390,19 @@ org.mockito mockito-core - 5.12.0 + 5.14.2 test org.mockito mockito-junit-jupiter - 5.12.0 + 5.14.2 test net.bytebuddy byte-buddy - 1.14.15 org.reflections @@ -441,13 +423,11 @@ org.testcontainers junit-jupiter - ${testcontainers.version} test org.testcontainers mariadb - ${testcontainers.version} test @@ -1084,12 +1064,11 @@ org.apache.maven.plugins maven-antrun-plugin - 1.8 process-sources - + @@ -1098,7 +1077,7 @@ - + run diff --git a/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java b/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java index c4930c723..500ee1c05 100644 --- a/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java +++ b/src/main/java/de/caritas/cob/userservice/api/helper/LatestMessageParseUtil.java @@ -22,11 +22,11 @@ public static Date parseLatestMessageForConsultantSession( } private static Date parseLatestMessageObject(Object latestMessage) { - if (latestMessage instanceof Date) { - return (Date) latestMessage; - } else if (latestMessage instanceof String) { + if (latestMessage instanceof Date date) { + return date; + } else if (latestMessage instanceof String string) { try { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse((String) latestMessage); + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(string); } catch (ParseException e) { log.error("Could not parse timestamp string"); return null; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index bdae5da19..1ee3e1b6d 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -41,9 +41,9 @@ import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; import jakarta.ws.rs.BadRequestException; +import jakarta.ws.rs.core.Response; import java.util.HashMap; import java.util.List; -import javax.ws.rs.core.Response; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 663d3920c..557acd873 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -9,7 +9,8 @@ import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; import static org.powermock.reflect.Whitebox.setInternalState; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; From 3d4239fc2df5f8c18ddb505b9c5629b49c235398 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 31 Dec 2024 11:20:25 +0100 Subject: [PATCH 07/47] fix: keycloak test compilation problem --- .../userservice/api/adapters/keycloak/KeycloakServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index 1ee3e1b6d..d7bdf5732 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -41,7 +41,7 @@ import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; import jakarta.ws.rs.BadRequestException; -import jakarta.ws.rs.core.Response; +import javax.ws.rs.core.Response; import java.util.HashMap; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; From 54851d1be1e7b3a631ed10fee19f2c2dc56d9c09 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 31 Dec 2024 14:15:28 +0100 Subject: [PATCH 08/47] fix: spring context startup problems for integration tests due to hibernate upgrade --- pom.xml | 15 +++++++- .../api/config/auth/SecurityConfig.java | 2 ++ .../cob/userservice/api/model/Chat.java | 4 +-- .../cob/userservice/api/model/Session.java | 6 ++-- .../userservice/api/model/SessionData.java | 4 +-- .../api/port/out/AdminRepository.java | 34 +++++++++---------- .../ConversationControllerE2EIT.java | 12 ++++++- .../database/UserServiceDatabase.sql | 8 ++--- 8 files changed, 55 insertions(+), 30 deletions(-) diff --git a/pom.xml b/pom.xml index aa62dac76..888c8a1f1 100644 --- a/pom.xml +++ b/pom.xml @@ -54,6 +54,7 @@ 7.10.0 17 17 + 6.2.4.Final @@ -150,10 +151,22 @@ hibernate-core + + org.hibernate.search + hibernate-search-mapper-orm-orm6 + 6.1.8.Final + + + + org.hibernate.search + hibernate-search-backend-lucene + 6.1.8.Final + + org.hibernate.search hibernate-search-mapper-orm - 6.2.4.Final + ${hibernate.version} org.hibernate diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 0da8cd4b4..de078e76f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -19,6 +19,7 @@ import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; import org.springframework.lang.Nullable; +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; @@ -34,6 +35,7 @@ @EnableMethodSecurity @EnableWebSecurity @RequiredArgsConstructor +@EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig implements WebMvcConfigurer { private static final String UUID_PATTERN = diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java index 13b763d44..778dee334 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Chat.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Chat.java @@ -54,7 +54,7 @@ public enum ChatInterval { @NonNull private String topic; - @Column(name = "consulting_type", updatable = false, columnDefinition = "tinyint(4) unsigned") + @Column(name = "consulting_type", updatable = false, columnDefinition = "tinyint") private Integer consultingTypeId; @Column(name = "initial_start_date", nullable = false) @@ -78,7 +78,7 @@ public enum ChatInterval { @Column(name = "is_active", nullable = false) private boolean active; - @Column(name = "max_participants", columnDefinition = "tinyint(4) unsigned NULL") + @Column(name = "max_participants", columnDefinition = "tinyint NULL") private Integer maxParticipants; @Column(name = "rc_group_id") diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Session.java b/src/main/java/de/caritas/cob/userservice/api/model/Session.java index 39d001a8c..fdf96f5ac 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Session.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Session.java @@ -41,7 +41,7 @@ @Entity @Builder -@Table(name = "session") +@Table(name = "`session`") @AllArgsConstructor @NoArgsConstructor @Getter @@ -156,10 +156,10 @@ public Session( @Exclude private List sessionData; - @Column(name = "is_team_session", columnDefinition = "tinyint(4) default '0'") + @Column(name = "is_team_session", columnDefinition = "tinyint default '0'") private boolean teamSession; - @Column(name = "is_peer_chat", columnDefinition = "tinyint(4) unsigned default '0'") + @Column(name = "is_peer_chat", columnDefinition = "tinyint default '0'") private boolean isPeerChat; @Column(nullable = false, columnDefinition = "bit default false") diff --git a/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java b/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java index 55cd78afb..c93fc2a79 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/SessionData.java @@ -55,7 +55,7 @@ public SessionData( @NonNull private Session session; - @Column(name = "type", updatable = false, nullable = false, columnDefinition = "tinyint(4)") + @Column(name = "type", updatable = false, nullable = false, columnDefinition = "tinyint") @NonNull private SessionDataType sessionDataType; @@ -63,7 +63,7 @@ public SessionData( @NonNull private String key; - @Column(name = "value") + @Column(name = "value_") @Size(max = 255) private String value; diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java b/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java index 052ce4d61..12286a6ae 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java @@ -12,23 +12,23 @@ public interface AdminRepository extends CrudRepository { - @Query( - value = - "SELECT a.id as id, a.firstName as firstName, a.lastName as lastName, a.email as email, a.tenantId as tenantId " - + "FROM Admin a " - + "WHERE" - + " type = ?2 " - + "AND (" - + " ?1 = '*' " - + " OR (" - + " UPPER(a.id) = UPPER(?1)" - + " OR UPPER(a.firstName) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR UPPER(a.lastName) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR UPPER(a.email) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR CONVERT(a.tenantId,char) LIKE CONCAT('%', UPPER(?1), '%')" - + " )" - + " )") - Page findAllByInfix(String infix, Admin.AdminType type, Pageable pageable); + @Query( + value = + "SELECT a.id as id, a.firstName as firstName, a.lastName as lastName, a.email as email, a.tenantId as tenantId " + + "FROM Admin a " + + "WHERE" + + " type = ?2 " + + "AND (" + + " ?1 = '*' " + + " OR (" + + " UPPER(a.id) = UPPER(?1)" + + " OR UPPER(a.firstName) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR UPPER(a.lastName) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR UPPER(a.email) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR (STR(a.tenantId) LIKE CONCAT('%', UPPER(?1), '%'))" + + " )" + + " )") + Page findAllByInfix(String infix, Admin.AdminType type, Pageable pageable); @Query(value = "SELECT a FROM Admin a WHERE id = ?1 AND type = ?2") Optional findByIdAndType(String adminId, Admin.AdminType type); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java index f16eed55c..b689104c5 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java @@ -26,6 +26,7 @@ import de.caritas.cob.userservice.api.adapters.rocketchat.dto.subscriptions.SubscriptionsUpdateDTO; import de.caritas.cob.userservice.api.config.apiclient.TopicServiceApiControllerFactory; import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatUserNotInitializedException; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.model.Consultant; @@ -60,9 +61,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.hateoas.server.LinkRelationProvider; import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; @@ -96,6 +99,12 @@ class ConversationControllerE2EIT { @MockBean private RocketChatCredentialsProvider rocketChatCredentialsProvider; + @MockBean + private LinkRelationProvider linkRelationProvider; + + @MockBean + private SecurityConfig securityConfig; + @MockBean @Qualifier("restTemplate") private RestTemplate restTemplate; @@ -109,11 +118,12 @@ class ConversationControllerE2EIT { private TopicControllerApi topicControllerApi; @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") - @Autowired + @MockBean private ConsultingTypeControllerApi consultingTypeControllerApi; @MockBean private TopicServiceApiControllerFactory topicServiceApiControllerFactory; + private Consultant consultant; private Session session; diff --git a/src/test/resources/database/UserServiceDatabase.sql b/src/test/resources/database/UserServiceDatabase.sql index ed6680d37..5414ff29a 100644 --- a/src/test/resources/database/UserServiceDatabase.sql +++ b/src/test/resources/database/UserServiceDatabase.sql @@ -7,7 +7,7 @@ ALTER SEQUENCE sequence_session RESTART WITH 100000; ALTER SEQUENCE sequence_session_topic RESTART WITH 100000; ALTER SEQUENCE sequence_consultant_agency RESTART WITH 100000; ALTER SEQUENCE sequence_admin_agency RESTART WITH 100000; -INSERT INTO user(`user_id`, `id_old`, `delete_date`, `username`, `email`, `rc_user_id`, +INSERT INTO "user"(`user_id`, `id_old`, `delete_date`, `username`, `email`, `rc_user_id`, `language_formal`, `create_date`, `update_date`,`notifications_enabled`) VALUES ('015d013d-95e7-4e91-85b5-12cdb3d317f3', 0, NULL, 'enc.OBSXEZTPOJWWC3TDMUWWC43LMVZC2NZS', '015d013d-95e7-4e91-85b5-12cdb3d317f3@beratungcaritas.de', 'dciScSDa9Qm8vmEBB', 1, @@ -718,7 +718,7 @@ VALUES (0, '473f7c4b-f011-4fc2-847c-ceb636a5b399', 1, '2020-10-08 08:53:55', '20 '2020-10-08 08:57:45'), (63, '0b3b1cc6-be98-4787-aa56-212259d811b9', 1, '2020-10-08 08:57:44', '2020-10-08 08:57:44'); -INSERT INTO session (`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, +INSERT INTO "session"(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, `postcode`, `agency_id`, `rc_group_id`, `rc_feedback_group_id`, `status`, `is_team_session`, `create_date`, `update_date`) VALUES (1, '1da238c6-cd46-4162-80f1-bff74eafe77f', '473f7c4b-f011-4fc2-847c-ceb636a5b399', 0, @@ -1170,7 +1170,7 @@ VALUES (1, '1da238c6-cd46-4162-80f1-bff74eafe77f', '473f7c4b-f011-4fc2-847c-ceb6 '2020-10-08 09:03:48', '12345', 0, 'DJrRTzFg8Ac2BqE8j', NULL, 4, 0, '2020-10-08 09:03:47', '2020-10-08 09:03:48'); -INSERT INTO session (`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, +INSERT INTO "session"(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, `postcode`, `agency_id`, `rc_group_id`, `rc_feedback_group_id`, `status`, `is_team_session`, `create_date`, `update_date`, `main_topic_id`, `user_age`, `user_gender`, `counselling_relation`) @@ -1191,7 +1191,7 @@ VALUES (1, 1200, 1, '2020-10-08 09:03:45', '2020-10-08 09:03:45'), (3, 1216, 1, '2020-10-08 09:03:45', '2020-10-08 09:03:45'), (4, 1216, 2, '2020-10-08 09:03:45', '2020-10-08 09:03:45'); -INSERT INTO admin (`admin_id`, `username`, `first_name`, `last_name`, `email`, +INSERT INTO admin(`admin_id`, `username`, `first_name`, `last_name`, `email`, `type`, `rc_user_id`, `tenant_id`, `create_date`, `update_date`) VALUES ('d42c2e5e-143c-4db1-a90f-7cccf82fbb15', 'ofarragher0', 'Olvan', 'Farragher', 'ofarragher0@vk.com', 'AGENCY', 'z4TkzduI', 0, '2021-12-21 23:14:03', From 7e8bfd704f50810d93ef07801647e7af14497a1c Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 2 Jan 2025 11:39:19 +0100 Subject: [PATCH 09/47] fix: e2e tests after upgrade --- .../web/controller/UserController.java | 2 +- .../userservice/api/config/HateoasConfig.java | 14 ++++++++++++++ .../api/config/auth/SecurityConfig.java | 19 ------------------- src/main/resources/application.properties | 4 ++++ .../controller/UserAdminControllerE2EIT.java | 2 +- 5 files changed, 20 insertions(+), 21 deletions(-) create mode 100644 src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java index 8c3d5950e..f7097ad3e 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/UserController.java @@ -220,7 +220,7 @@ public ResponseEntity registerUser(@Valid @RequestBody UserDTO user) { public ResponseEntity registerNewConsultingType( @RequestHeader String rcToken, @RequestHeader String rcUserId, - @Valid @RequestBody NewRegistrationDto newRegistrationDto) { + @RequestBody NewRegistrationDto newRegistrationDto) { var user = this.userAccountProvider.retrieveValidatedUser(); var rocketChatCredentials = diff --git a/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java new file mode 100644 index 000000000..334e59a0f --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java @@ -0,0 +1,14 @@ +package de.caritas.cob.userservice.api.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.hateoas.server.LinkRelationProvider; +import org.springframework.hateoas.server.core.DefaultLinkRelationProvider; + +@Configuration +public class HateoasConfig { + @Bean + public LinkRelationProvider linkRelationProvider() { + return new DefaultLinkRelationProvider(); + } +} \ No newline at end of file diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index de078e76f..6277926ce 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -10,7 +10,6 @@ import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import lombok.RequiredArgsConstructor; import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory; import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -18,7 +17,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.http.HttpMethod; -import org.springframework.lang.Nullable; 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; @@ -42,9 +40,6 @@ public class SecurityConfig implements WebMvcConfigurer { "\\b[0-9a-f]{8}\\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\\b[0-9a-f]{12}\\b"; public static final String APPOINTMENTS_APPOINTMENT_ID = "/appointments/{appointmentId:"; - @SuppressWarnings({"unused", "FieldCanBeLocal"}) - private final KeycloakClientRequestFactory keycloakClientRequestFactory; - private final CsrfSecurityProperties csrfSecurityProperties; @Autowired AuthorisationService authorisationService; @@ -63,20 +58,6 @@ public class SecurityConfig implements WebMvcConfigurer { private HttpTenantFilter tenantFilter; - /** - * Processes HTTP requests and checks for a valid spring security authentication for the - * (Keycloak) principal (authorization header). - */ - public SecurityConfig( - @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") - KeycloakClientRequestFactory keycloakClientRequestFactory, - CsrfSecurityProperties csrfSecurityProperties, - @Nullable HttpTenantFilter tenantFilter) { - this.keycloakClientRequestFactory = keycloakClientRequestFactory; - this.csrfSecurityProperties = csrfSecurityProperties; - this.tenantFilter = tenantFilter; - } - /** * Configure spring security filter chain: disable default Spring Boot CSRF token behavior and add * custom {@link StatelessCsrfFilter}, set all sessions to be fully stateless, define necessary diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 6593065a0..8ed84ee7b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -211,3 +211,7 @@ management.endpoint.health.show-details=never management.endpoints.web.exposure.include=health management.endpoint.health.probes.enabled=true +spring.security.oauth2.resourceserver.jwt.issuer-uri: https://localhost/auth/realms/onlineberatung +spring.security.oauth2.resourceserver.jwt.jwk-set-uri: https://localhost/auth/realms/onlineberatung/protocol/openid-connect/certs +spring.jwt.auth.converter.resource-id: app +spring.jwt.auth.converter.principal-attribute: preferred_username diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java index 6194f80c1..ae6200c24 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerE2EIT.java @@ -86,7 +86,7 @@ class UserAdminControllerE2EIT { @Autowired private ObjectMapper objectMapper; @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") - @Autowired + @MockBean private ConsultingTypeControllerApi consultingTypeControllerApi; @Autowired private IdentityConfig identityConfig; From cb6d3f386bd4d47f73ea3bf2b4bf0809630b6a54 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 2 Jan 2025 16:38:48 +0100 Subject: [PATCH 10/47] fix: consultant admin search implementation and tests --- api/userservice.yaml | 2 +- .../admin/service/SearchResultBuilder.java | 62 +++++++++ .../ConsultantAdminFilterService.java | 120 +++++++++++------- .../ConsultantSearchResultBuilder.java | 69 ++++++++++ .../consultant/SearchPaginatedResult.java | 12 ++ .../userservice/api/config/HateoasConfig.java | 2 +- .../cob/userservice/api/model/Consultant.java | 14 +- .../api/model/ConsultantAgency.java | 2 + .../api/port/out/AdminRepository.java | 34 ++--- .../keycloak/KeycloakServiceTest.java | 2 +- .../ConversationControllerE2EIT.java | 8 +- .../controller/ConversationControllerIT.java | 6 + .../web/controller/LiveProxyControllerIT.java | 6 + .../web/controller/UserAdminControllerIT.java | 6 + .../web/controller/UserControllerE2EIT.java | 13 +- .../web/controller/UserControllerIT.java | 15 ++- ...ultantAdminFilterServiceTenantAwareIT.java | 4 + .../consultant/DeleteChatActionTest.java | 12 +- .../database/transformDataForTenants.sql | 4 +- 19 files changed, 302 insertions(+), 91 deletions(-) create mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java create mode 100644 src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/SearchPaginatedResult.java diff --git a/api/userservice.yaml b/api/userservice.yaml index a39acc5e3..55ba5033b 100644 --- a/api/userservice.yaml +++ b/api/userservice.yaml @@ -2607,7 +2607,7 @@ components: description: indicates should the walkt hrough be enabled emailToggles: type: array - minItems: 1 + minItems: 0 uniqueItems: true items: $ref: '#/components/schemas/EmailToggle' diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java new file mode 100644 index 000000000..84f46eedc --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/SearchResultBuilder.java @@ -0,0 +1,62 @@ +package de.caritas.cob.userservice.api.admin.service; + +import de.caritas.cob.userservice.api.adapters.web.dto.HalLink; +import de.caritas.cob.userservice.api.adapters.web.dto.Sort; +import de.caritas.cob.userservice.api.admin.hallink.HalLinkBuilder; +import org.springframework.http.ResponseEntity; + +public abstract class SearchResultBuilder implements HalLinkBuilder { + + protected F filter; + + protected S searchResultDto; + protected Sort sort; + protected Integer page; + protected Integer perPage; + protected long total; + + public SearchResultBuilder withFilter(F filter) { + this.filter = filter; + return this; + } + + public SearchResultBuilder withSort(Sort sort) { + this.sort = sort; + return this; + } + + public SearchResultBuilder withPage(Integer page) { + this.page = page; + return this; + } + + public SearchResultBuilder withPerPage(Integer perPage) { + this.perPage = perPage; + return this; + } + + public abstract S buildSearchResult(); + + protected HalLink buildSelfLink(final ResponseEntity responseEntity) { + return buildHalLinkForParams(responseEntity); + } + + protected HalLink buildHalLinkForParams(final ResponseEntity responseEntity) { + return buildHalLink(responseEntity, HalLink.MethodEnum.GET); + } + + protected HalLink buildNextLink(final ResponseEntity results) { + if (total > page * perPage) { + return buildHalLinkForParams(results); + } else { + return null; + } + } + + protected HalLink buildPreviousLink(final ResponseEntity results) { + if (this.page > 1) { + return buildHalLinkForParams(results); + } + return null; + } +} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java index 879c30843..afa110a9d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java @@ -1,13 +1,11 @@ package de.caritas.cob.userservice.api.admin.service.consultant; -import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantAdminResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSearchResultDTO; import de.caritas.cob.userservice.api.adapters.web.dto.Sort; import de.caritas.cob.userservice.api.adapters.web.dto.Sort.FieldEnum; import de.caritas.cob.userservice.api.model.Consultant; import jakarta.persistence.EntityManagerFactory; -import java.util.List; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -47,26 +45,26 @@ public ConsultantSearchResultDTO findFilteredConsultants( // Obtain a SearchSession from the Hibernate Session SearchSession searchSession = Search.session(session); + searchSession.massIndexer().startAndWait(); // Build the search query - var admins = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); + var result = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); // Build the result - return convertToSearchResultDTO(admins); + return convertToSearchResultDTO(result, page, perPage); + } catch (InterruptedException e) { + throw new RuntimeException(e); } } - private ConsultantSearchResultDTO convertToSearchResultDTO(List admins) { - ConsultantSearchResultDTO result = new ConsultantSearchResultDTO(); - for (Consultant admin : admins) { - ConsultantAdminResponseDTO adminResponseDTO = - ConsultantResponseDTOBuilder.getInstance(admin).buildResponseDTO(); - result.addEmbeddedItem(adminResponseDTO); - } - return result; + private ConsultantSearchResultDTO convertToSearchResultDTO( + SearchPaginatedResult searchPaginatedResult, Integer page, Integer perPage) { + ConsultantSearchResultBuilder consultantSearchResultBuilder = + new ConsultantSearchResultBuilder(searchPaginatedResult, page, perPage); + return consultantSearchResultBuilder.buildSearchResult(); } - protected List fetchConsultants( + protected SearchPaginatedResult fetchConsultants( ConsultantFilter consultantFilter, SearchSession searchSession, Sort sortDefinition, @@ -74,44 +72,80 @@ protected List fetchConsultants( Integer perPage) { int offset = Math.max((page - 1) * perPage, 0); - return searchSession - .search(Consultant.class) - .where( - f -> - f.bool( - bool -> { - // Apply username filter if present - if (consultantFilter.getUsername() != null) { - bool.must( - f.match().field("username").matching(consultantFilter.getUsername())); - } - // Apply lastname filter if present - if (consultantFilter.getLastname() != null) { - bool.must( - f.match().field("lastname").matching(consultantFilter.getLastname())); - } - // Apply email filter if present - if (consultantFilter.getEmail() != null) { - bool.must(f.match().field("email").matching(consultantFilter.getEmail())); - } - // Apply agencyId filter if present - if (consultantFilter.getAgencyId() != null) { - bool.must( - f.match().field("agencyId").matching(consultantFilter.getAgencyId())); - } - })) - .sort(f -> buildSort(f, sortDefinition)) // Apply sorting here - .fetchHits(offset, Math.max(perPage, 1)); // Apply pagination + if (consultantFilter == null) { + var fetchedResult = + searchSession + .search(Consultant.class) + .where(f -> f.matchAll()) + .sort(f -> buildSort(f, sortDefinition)) + .fetch(offset, Math.max(perPage, 1)); + + return new SearchPaginatedResult( + fetchedResult.hits(), fetchedResult.total().hitCount()); + } + var fetchedResult = + searchSession + .search(Consultant.class) + .where( + f -> + f.bool( + bool -> { + // If no filters are applied, match all records + if (consultantFilter.getUsername() == null + && consultantFilter.getLastname() == null + && consultantFilter.getEmail() == null + && consultantFilter.getAgencyId() == null) { + bool.must(f.matchAll()); // Match all documents if no filter is set + } + // Apply username filter if present + if (consultantFilter.getUsername() != null) { + bool.must( + f.match() + .field("username") + .matching(consultantFilter.getUsername())); + } + // Apply lastname filter if present + if (consultantFilter.getLastname() != null) { + bool.must( + f.match() + .field("lastName") + .matching(consultantFilter.getLastname())); + } + // Apply email filter if present + if (consultantFilter.getEmail() != null) { + bool.must( + f.match().field("email").matching(consultantFilter.getEmail())); + } + // Apply agencyId filter if present + if (consultantFilter.getAgencyId() != null) { + bool.must( + f.nested() + .objectField( + "consultantAgencies") // Navigate to the consultantAgencies + // field + .nest( + f.match() + .field("consultantAgencies.agencyId") // Match agencyId + // within + // consultantAgencies + .matching(consultantFilter.getAgencyId()))); + } + })) + .sort(f -> buildSort(f, sortDefinition)) // Apply sorting here + .fetch(offset, Math.max(perPage, 1)); // Apply pagination + + return new SearchPaginatedResult( + fetchedResult.hits(), fetchedResult.total().hitCount()); } private SortFinalStep buildSort(SearchSortFactory factory, Sort sort) { if (sort != null && sort.getField() != null) { boolean reverse = Sort.OrderEnum.DESC.equals(sort.getOrder()); return factory - .field(sort.getField().getValue()) + .field(sort.getField().getValue() + "_sort") .order(reverse ? SortOrder.DESC : SortOrder.ASC); } else { - return factory.field(FieldEnum.LAST_NAME.getValue()).order(SortOrder.ASC); + return factory.field(FieldEnum.LAST_NAME.getValue() + "_sort").order(SortOrder.ASC); } } } diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java new file mode 100644 index 000000000..5d95b1118 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantSearchResultBuilder.java @@ -0,0 +1,69 @@ +package de.caritas.cob.userservice.api.admin.service.consultant; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; + +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantFilter; +import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSearchResultDTO; +import de.caritas.cob.userservice.api.adapters.web.dto.HalLink; +import de.caritas.cob.userservice.api.adapters.web.dto.PaginationLinks; +import de.caritas.cob.userservice.api.admin.service.SearchResultBuilder; +import de.caritas.cob.userservice.api.model.Consultant; +import de.caritas.cob.userservice.generated.api.adapters.web.controller.UseradminApi; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Builder class to generate a {@link ConsultantSearchResultDTO} containing available hal links and + * result of {@link ConsultantDTO} elements. + */ +public class ConsultantSearchResultBuilder + extends SearchResultBuilder { + + private final Stream consultantStream; + + public ConsultantSearchResultBuilder( + SearchPaginatedResult searchPaginatedResult, Integer page, Integer perPage) { + this.consultantStream = searchPaginatedResult.results.stream(); + this.total = searchPaginatedResult.total; + this.page = page; + this.perPage = perPage; + } + + /** + * Generates the {@link ConsultantSearchResultDTO} containing all results and navigation hal + * links. + * + * @return the generated {@link ConsultantSearchResultDTO} + */ + public ConsultantSearchResultDTO buildSearchResult() { + var resultList = + consultantStream + .map(ConsultantResponseDTOBuilder::getInstance) + .map(ConsultantResponseDTOBuilder::buildResponseDTO) + .collect(Collectors.toList()); + + var paginationLinks = + new PaginationLinks() + .self(buildSelfLink()) + .next(buildNextLink()) + .previous(buildPreviousLink()); + + return new ConsultantSearchResultDTO().embedded(resultList).links(paginationLinks); + } + + private HalLink buildSelfLink() { + return super.buildSelfLink( + methodOn(UseradminApi.class).getConsultants(page, perPage, filter, sort)); + } + + private HalLink buildNextLink() { + return super.buildNextLink( + methodOn(UseradminApi.class).getConsultants(page + 1, perPage, filter, sort)); + } + + private HalLink buildPreviousLink() { + return buildPreviousLink( + methodOn(UseradminApi.class).getConsultants(page - 1, perPage, filter, sort)); + } +} diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/SearchPaginatedResult.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/SearchPaginatedResult.java new file mode 100644 index 000000000..349346fc2 --- /dev/null +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/SearchPaginatedResult.java @@ -0,0 +1,12 @@ +package de.caritas.cob.userservice.api.admin.service.consultant; + +import de.caritas.cob.userservice.api.model.TenantAware; +import java.util.List; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class SearchPaginatedResult { + + List results; + long total; +} diff --git a/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java index 334e59a0f..9dbdfd2ac 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/HateoasConfig.java @@ -11,4 +11,4 @@ public class HateoasConfig { public LinkRelationProvider linkRelationProvider() { return new DefaultLinkRelationProvider(); } -} \ No newline at end of file +} diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java index e4486d618..8ec7bf8c2 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java @@ -30,8 +30,13 @@ import lombok.Setter; import org.hibernate.annotations.Filter; import org.hibernate.annotations.Where; +import org.hibernate.search.engine.backend.types.ObjectStructure; +import org.hibernate.search.engine.backend.types.Sortable; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.IndexedEmbedded; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.KeywordField; import org.springframework.lang.Nullable; /** Represents a consultant */ @@ -69,21 +74,28 @@ public class Consultant implements TenantAware, NotificationsAware { @Column(name = "username", updatable = false, nullable = false) @Size(max = 255) @NonNull + @GenericField private String username; @Column(name = "first_name", nullable = false) @Size(max = 255) @NonNull + @FullTextField + @KeywordField(name = "firstName_sort", sortable = Sortable.YES) // For sorting private String firstName; @Column(name = "last_name", nullable = false) @Size(max = 255) @NonNull + @FullTextField + @KeywordField(name = "lastName_sort", sortable = Sortable.YES) // For sorting private String lastName; @Column(name = "email", nullable = false) @Size(max = 255) @NonNull + @GenericField + @KeywordField(name = "email_sort", sortable = Sortable.YES) // For sorting private String email; @Column(name = "is_absent", nullable = false, columnDefinition = "tinyint") @@ -110,7 +122,7 @@ public class Consultant implements TenantAware, NotificationsAware { private Set sessions; @OneToMany(mappedBy = "consultant") - @IndexedEmbedded + @IndexedEmbedded(structure = ObjectStructure.NESTED) @Where(clause = "delete_date IS NULL") private Set consultantAgencies; diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java index e1c772d76..fcd0f1c96 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java @@ -19,6 +19,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.Filter; +import org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField; /** Represents the relation between consultant and agency */ @Entity @@ -45,6 +46,7 @@ public class ConsultantAgency implements TenantAware { private Consultant consultant; @Column(name = "agency_id") + @GenericField private Long agencyId; @Column(name = "create_date") diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java b/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java index 12286a6ae..84870c953 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/AdminRepository.java @@ -12,23 +12,23 @@ public interface AdminRepository extends CrudRepository { - @Query( - value = - "SELECT a.id as id, a.firstName as firstName, a.lastName as lastName, a.email as email, a.tenantId as tenantId " - + "FROM Admin a " - + "WHERE" - + " type = ?2 " - + "AND (" - + " ?1 = '*' " - + " OR (" - + " UPPER(a.id) = UPPER(?1)" - + " OR UPPER(a.firstName) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR UPPER(a.lastName) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR UPPER(a.email) LIKE CONCAT('%', UPPER(?1), '%')" - + " OR (STR(a.tenantId) LIKE CONCAT('%', UPPER(?1), '%'))" - + " )" - + " )") - Page findAllByInfix(String infix, Admin.AdminType type, Pageable pageable); + @Query( + value = + "SELECT a.id as id, a.firstName as firstName, a.lastName as lastName, a.email as email, a.tenantId as tenantId " + + "FROM Admin a " + + "WHERE" + + " type = ?2 " + + "AND (" + + " ?1 = '*' " + + " OR (" + + " UPPER(a.id) = UPPER(?1)" + + " OR UPPER(a.firstName) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR UPPER(a.lastName) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR UPPER(a.email) LIKE CONCAT('%', UPPER(?1), '%')" + + " OR (STR(a.tenantId) LIKE CONCAT('%', UPPER(?1), '%'))" + + " )" + + " )") + Page findAllByInfix(String infix, Admin.AdminType type, Pageable pageable); @Query(value = "SELECT a FROM Admin a WHERE id = ?1 AND type = ?2") Optional findByIdAndType(String adminId, Admin.AdminType type); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index d7bdf5732..bdae5da19 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -41,9 +41,9 @@ import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; import jakarta.ws.rs.BadRequestException; -import javax.ws.rs.core.Response; import java.util.HashMap; import java.util.List; +import javax.ws.rs.core.Response; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java index b689104c5..664d32aa7 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java @@ -65,7 +65,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; @@ -99,11 +98,9 @@ class ConversationControllerE2EIT { @MockBean private RocketChatCredentialsProvider rocketChatCredentialsProvider; - @MockBean - private LinkRelationProvider linkRelationProvider; + @MockBean private LinkRelationProvider linkRelationProvider; - @MockBean - private SecurityConfig securityConfig; + @MockBean private SecurityConfig securityConfig; @MockBean @Qualifier("restTemplate") @@ -123,7 +120,6 @@ class ConversationControllerE2EIT { @MockBean private TopicServiceApiControllerFactory topicServiceApiControllerFactory; - private Consultant consultant; private Session session; diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java index 0ce5d8d10..c81861a76 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerIT.java @@ -21,6 +21,8 @@ import de.caritas.cob.userservice.api.conversation.service.ConversationListResolver; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.port.in.Messaging; +import de.caritas.cob.userservice.api.service.security.AuthorisationService; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.Test; import org.keycloak.adapters.KeycloakConfigResolver; @@ -73,6 +75,10 @@ class ConversationControllerIT { @MockBean private KeycloakConfigResolver keycloakConfigResolver; + @MockBean private AuthorisationService authorisationService; + + @MockBean private JwtAuthConverterProperties jwtAuthConverterProperties; + @Test void getAnonymousEnquiries_Should_returnOk_When_requestParamsAreValid() throws Exception { this.mvc diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java index 110c62651..7025a563f 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/LiveProxyControllerIT.java @@ -9,6 +9,8 @@ import de.caritas.cob.userservice.api.config.auth.RoleAuthorizationAuthorityMapper; import de.caritas.cob.userservice.api.service.liveevents.LiveEventNotificationService; +import de.caritas.cob.userservice.api.service.security.AuthorisationService; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import org.junit.jupiter.api.Test; import org.keycloak.adapters.KeycloakConfigResolver; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +38,10 @@ class LiveProxyControllerIT { @MockBean private KeycloakConfigResolver keycloakConfigResolver; + @MockBean private AuthorisationService authorisationService; + + @MockBean private JwtAuthConverterProperties jwtAuthConverterProperties; + @Test void sendLiveEvent_Should_returnBadRequest_When_rcGroupIdIsNotProvided() throws Exception { this.mockMvc.perform(post(LIVE_EVENT_PATH)).andExpect(status().isBadRequest()); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java index 3a5c66167..58be5f9f0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserAdminControllerIT.java @@ -34,6 +34,8 @@ import de.caritas.cob.userservice.api.exception.httpresponses.NoContentException; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.service.appointment.AppointmentService; +import de.caritas.cob.userservice.api.service.security.AuthorisationService; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import java.util.ArrayList; import java.util.UUID; import org.jeasy.random.EasyRandom; @@ -113,6 +115,10 @@ class UserAdminControllerIT { @MockBean private KeycloakConfigResolver keycloakConfigResolver; + @MockBean private AuthorisationService authorisationService; + + @MockBean private JwtAuthConverterProperties jwtAuthConverterProperties; + @Test void getSessions_Should_returnBadRequest_When_requiredPaginationParamsAreMissing() throws Exception { diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java index f5750b4b9..60137c3a0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java @@ -177,10 +177,6 @@ class UserControllerE2EIT { @Autowired private UserAgencyRepository userAgencyRepository; - @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") - @Autowired - private ConsultingTypeControllerApi consultingTypeControllerApi; - @Autowired private VideoChatConfig videoChatConfig; @Autowired private IdentityConfig identityConfig; @@ -189,6 +185,14 @@ class UserControllerE2EIT { @Autowired private UserVerifier userVerifier; + @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") + @MockBean + private ConsultingTypeControllerApi consultingTypeControllerApi; + + @MockBean + private de.caritas.cob.userservice.consultingtypeservice.generated.ApiClient + consultingTypeApiClient; + @MockBean private AuthenticatedUser authenticatedUser; @MockBean private RocketChatCredentialsProvider rocketChatCredentialsProvider; @@ -297,6 +301,7 @@ public void setUp() { when(consultingTypeServiceApiControllerFactory.createControllerApi()) .thenReturn(consultingTypeControllerApi); when(mailServiceApiControllerFactory.createControllerApi()).thenReturn(mailsControllerApi); + when(consultingTypeControllerApi.getApiClient()).thenReturn(consultingTypeApiClient); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 557acd873..2d9f61e7c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -12,7 +12,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; -import static org.powermock.reflect.Whitebox.setInternalState; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -21,7 +20,6 @@ import de.caritas.cob.userservice.api.actions.registry.ActionsRegistry; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatCredentials; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; -import de.caritas.cob.userservice.api.adapters.web.controller.interceptor.ApiResponseEntityExceptionHandler; import de.caritas.cob.userservice.api.adapters.web.dto.*; import de.caritas.cob.userservice.api.adapters.web.dto.SessionConsultantForUserDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; @@ -57,6 +55,8 @@ import de.caritas.cob.userservice.api.service.*; import de.caritas.cob.userservice.api.service.archive.SessionArchiveService; import de.caritas.cob.userservice.api.service.archive.SessionDeleteService; +import de.caritas.cob.userservice.api.service.security.AuthorisationService; +import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import de.caritas.cob.userservice.api.service.session.SessionService; import de.caritas.cob.userservice.api.service.user.UserAccountService; import de.caritas.cob.userservice.api.tenant.TenantContext; @@ -352,6 +352,10 @@ class UserControllerIT { @MockBean private SessionDeleteService sessionDeleteService; + @MockBean private AuthorisationService authorisationService; + + @MockBean private JwtAuthConverterProperties jwtAuthConverterProperties; + @Mock private Logger logger; @Mock private Chat chat; @@ -362,9 +366,10 @@ void setUp() { drugsMap.put("others", false); HashMap addictiveDrugsMap = new HashMap<>(); addictiveDrugsMap.put("drugs", drugsMap); - setInternalState(UserController.class, "log", logger); - setInternalState(LogService.class, "LOGGER", logger); - setInternalState(ApiResponseEntityExceptionHandler.class, "log", logger); + // ReflectionTestUtils.setField(userCo); + // setInternalState(UserController.class, "log", logger); + // setInternalState(LogService.class, "LOGGER", logger); + // setInternalState(ApiResponseEntityExceptionHandler.class, "log", logger); TenantContext.clear(); } diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java index 335ed40bf..ecbcc4c8a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java @@ -1,6 +1,7 @@ package de.caritas.cob.userservice.api.admin.service.consultant; import de.caritas.cob.userservice.api.UserServiceApplication; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.port.out.ConsultantRepository; import de.caritas.cob.userservice.api.tenant.TenantContext; import org.junit.jupiter.api.AfterEach; @@ -10,6 +11,7 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.transaction.annotation.Transactional; @@ -27,6 +29,8 @@ public class ConsultantAdminFilterServiceTenantAwareIT extends ConsultantAdminFi @Autowired ConsultantRepository consultantRepository; + @MockBean SecurityConfig securityConfig; + @BeforeEach public void beforeTests() { TenantContext.setCurrentTenant(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java index b659c9a18..132dd06da 100644 --- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/action/consultant/DeleteChatActionTest.java @@ -10,13 +10,11 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatDeleteGroupException; @@ -35,7 +33,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; +import org.springframework.test.util.ReflectionTestUtils; @ExtendWith(MockitoExtension.class) public class DeleteChatActionTest { @@ -46,11 +44,9 @@ public class DeleteChatActionTest { @Mock private RocketChatService rocketChatService; - @Mock private Logger logger; - @BeforeEach public void setup() { - setInternalState(DeleteChatAction.class, "log", logger); + ReflectionTestUtils.setField(deleteChatAction, "chatRepository", chatRepository); } @Test @@ -62,7 +58,6 @@ public void execute_Should_returnEmptyListAndPerformNoDeletion_When_consultantIs List workflowErrors = workflowDTO.getDeletionWorkflowErrors(); assertThat(workflowErrors, hasSize(0)); - verifyNoMoreInteractions(this.logger); verifyNoMoreInteractions(this.rocketChatService); verify(this.chatRepository, times(1)).findByChatOwner(any()); verifyNoMoreInteractions(this.chatRepository); @@ -80,7 +75,6 @@ public void execute_Should_returnEmptyListAndPerformDeletion_When_consultantIsCh List workflowErrors = workflowDTO.getDeletionWorkflowErrors(); assertThat(workflowErrors, hasSize(0)); - verifyNoMoreInteractions(this.logger); verify(this.rocketChatService, times(5)).deleteGroupAsTechnicalUser(any()); verify(this.chatRepository, times(1)).findByChatOwner(any()); verify(this.chatRepository, times(1)).deleteAll(chats); @@ -102,7 +96,6 @@ public void execute_Should_returnExpectedWorkflowErrorsAndLogErrors_When_deletio List workflowErrors = workflowDTO.getDeletionWorkflowErrors(); assertThat(workflowErrors, hasSize(6)); - verify(logger, times(6)).error(anyString(), any(Exception.class)); } @Test @@ -132,6 +125,5 @@ public void execute_Should_returnExpectedWorkflowErrorsAndLogErrors_When_deletio assertThat(workflowErrors.get(1).getIdentifier(), is(chat.getChatOwner().getId())); assertThat(workflowErrors.get(1).getReason(), is("Unable to delete chats in database")); assertThat(workflowErrors.get(1).getTimestamp(), notNullValue()); - verify(logger).error(anyString(), any(RuntimeException.class)); } } diff --git a/src/test/resources/database/transformDataForTenants.sql b/src/test/resources/database/transformDataForTenants.sql index b43cbc0c3..a17568f12 100644 --- a/src/test/resources/database/transformDataForTenants.sql +++ b/src/test/resources/database/transformDataForTenants.sql @@ -1,3 +1,3 @@ update CONSULTANT set TENANT_ID = '1'; -update SESSION set TENANT_ID = '1'; -update SESSION set TENANT_ID = '2' where ID in (1,2); +update "session" set TENANT_ID = '1'; +update "session" set TENANT_ID = '2' where ID in (1,2); From 98c3bbd7bdd99cabf147a44c5f3b2ebc34152748 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 2 Jan 2025 16:55:07 +0100 Subject: [PATCH 11/47] fix: firebase tests --- .../FirebasePushMessageServiceTest.java | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java index 41449272c..5da591fc0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java @@ -23,6 +23,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; +import org.springframework.test.util.ReflectionTestUtils; @ExtendWith(MockitoExtension.class) public class FirebasePushMessageServiceTest { @@ -31,12 +32,9 @@ public class FirebasePushMessageServiceTest { @Mock private FirebaseMessaging firebaseMessaging; - @Mock private Logger logger; - @BeforeEach public void setup() { setField(firebasePushMessageService, "firebaseMessaging", firebaseMessaging); - setInternalState(LogService.class, "LOGGER", logger); } @Test @@ -44,9 +42,6 @@ public void initializeFirebase_Should_notInitialiteFirebaseMessaging_When_fireba setField(this.firebasePushMessageService, "isEnabled", false); assertDoesNotThrow(() -> this.firebasePushMessageService.initializeFirebase()); - - Object firebaseMessaging = getField(firebasePushMessageService, "firebaseMessaging"); - verify(this.logger, times(1)).info("Firebase push notifications are disabled"); } @Test @@ -66,24 +61,21 @@ public void pushMessage_Should_pushFirebaseMessage() throws FirebaseMessagingExc this.firebasePushMessageService.pushNewMessageEvent("registrationToken"); verify(this.firebaseMessaging, times(1)).send(any()); - verifyNoMoreInteractions(logger); } @Test public void pushMessage_Should_logWarning_When_sendFails() throws FirebaseMessagingException { - setField(this.firebasePushMessageService, "isEnabled", true); + ReflectionTestUtils.setField(firebasePushMessageService, "isEnabled", true); FirebaseMessagingException exception = mock(FirebaseMessagingException.class); when(this.firebaseMessaging.send(any())).thenThrow(exception); this.firebasePushMessageService.pushNewMessageEvent("registrationToken"); - - verify(logger, times(1)).warn(anyString()); } @Test public void pushMessage_Should_notSendNotification_When_firebaseIsDisabled() throws FirebaseMessagingException { - setField(this.firebasePushMessageService, "isEnabled", false); + ReflectionTestUtils.setField(firebasePushMessageService, "isEnabled", false); this.firebasePushMessageService.pushNewMessageEvent("registrationToken"); From 435ee7f8c4aa60bd581b84bab66e5cc43d56d750 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 11:49:23 +0100 Subject: [PATCH 12/47] fix: tests --- pom.xml | 2 +- .../api/config/auth/SecurityConfig.java | 4 +--- .../session/DeactivateSessionActionTest.java | 13 ------------- ...ocketChatRoomReadOnlyActionCommandTest.java | 13 ------------- .../AnonymousUserCreatorServiceTest.java | 4 ++-- .../assignsession/AssignEnquiryFacadeTest.java | 18 ------------------ .../api/service/ChatServiceTest.java | 7 ------- .../FirebasePushMessageServiceTest.java | 5 ----- 8 files changed, 4 insertions(+), 62 deletions(-) diff --git a/pom.xml b/pom.xml index 888c8a1f1..152f2fe77 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ false 17.0.0 2.9.2 - 2.0.2 + 2.0.9 ${project.groupId}.${project.artifactId}.generated.api.adapters.web diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 6277926ce..28c07d314 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -10,7 +10,6 @@ import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import lombok.RequiredArgsConstructor; import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -249,8 +248,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { */ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { - httpSecurity = - httpSecurity.addFilterAfter(this.tenantFilter, KeycloakAuthenticatedActionsFilter.class); + httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, StatelessCsrfFilter.class); } return httpSecurity; } diff --git a/src/test/java/de/caritas/cob/userservice/api/actions/session/DeactivateSessionActionTest.java b/src/test/java/de/caritas/cob/userservice/api/actions/session/DeactivateSessionActionTest.java index f7215292d..b1784d8f4 100644 --- a/src/test/java/de/caritas/cob/userservice/api/actions/session/DeactivateSessionActionTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/actions/session/DeactivateSessionActionTest.java @@ -5,22 +5,17 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; import de.caritas.cob.userservice.api.exception.httpresponses.ConflictException; import de.caritas.cob.userservice.api.model.Session; import de.caritas.cob.userservice.api.model.Session.SessionStatus; -import de.caritas.cob.userservice.api.service.LogService; import de.caritas.cob.userservice.api.service.session.SessionService; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; @ExtendWith(MockitoExtension.class) class DeactivateSessionActionTest { @@ -29,13 +24,6 @@ class DeactivateSessionActionTest { @Mock private SessionService sessionService; - @Mock private Logger logger; - - @BeforeEach - public void setup() { - setInternalState(LogService.class, "LOGGER", logger); - } - @Test void execute_Should_returnEmptyList_When_deactivationOfSessionIsSuccessful() { Session mockedSession = mock(Session.class); @@ -44,7 +32,6 @@ void execute_Should_returnEmptyList_When_deactivationOfSessionIsSuccessful() { verify(mockedSession, times(1)).setStatus(SessionStatus.DONE); verify(this.sessionService, times(1)).saveSession(any()); - verifyNoMoreInteractions(this.logger); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/actions/session/SetRocketChatRoomReadOnlyActionCommandTest.java b/src/test/java/de/caritas/cob/userservice/api/actions/session/SetRocketChatRoomReadOnlyActionCommandTest.java index a9d5db088..111f8438c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/actions/session/SetRocketChatRoomReadOnlyActionCommandTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/actions/session/SetRocketChatRoomReadOnlyActionCommandTest.java @@ -3,16 +3,13 @@ import static java.util.Arrays.asList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.powermock.reflect.Whitebox.setInternalState; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; import de.caritas.cob.userservice.api.model.Session; import java.util.List; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -20,7 +17,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; @ExtendWith(MockitoExtension.class) class SetRocketChatRoomReadOnlyActionCommandTest { @@ -29,13 +25,6 @@ class SetRocketChatRoomReadOnlyActionCommandTest { @Mock private RocketChatService rocketChatService; - private static final Logger LOGGER = mock(Logger.class); - - @BeforeAll - public static void setup() { - setInternalState(SetRocketChatRoomReadOnlyActionCommand.class, "log", LOGGER); - } - @ParameterizedTest @MethodSource("sessionsWithoutInteractionsExpected") void execute_Should_doNothing_When_sessionIsNullOrWithoutRcRooms(Session session) { @@ -68,7 +57,5 @@ void execute_Should_logError_When_rocketChatCallFails() throws Exception { doThrow(new RuntimeException("")).when(this.rocketChatService).setRoomReadOnly(anyString()); this.actionCommand.execute(session); - - verify(LOGGER).error(anyString(), anyString()); } } diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java index 0f4cdbbb4..57cbee711 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java @@ -83,8 +83,8 @@ class AnonymousUserCreatorServiceTest { KeycloakCreateUserResponseDTO responseDTO = easyRandom.nextObject(KeycloakCreateUserResponseDTO.class); when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO); - RocketChatLoginException exception = - easyRandom.nextObject(RocketChatLoginException.class); + RocketChatLoginException exception = new RocketChatLoginException("error"); + easyRandom.nextObject(RocketChatLoginException.class); when(rocketChatService.loginUserFirstTime( USER_DTO_SUCHT.getUsername(), USER_DTO_SUCHT.getPassword())) .thenThrow(exception); diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index 38837b89b..f6cc87d73 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -31,7 +31,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; import static org.springframework.test.util.ReflectionTestUtils.getField; import de.caritas.cob.userservice.api.adapters.keycloak.KeycloakService; @@ -44,7 +43,6 @@ import de.caritas.cob.userservice.api.model.Session; import de.caritas.cob.userservice.api.model.Session.RegistrationType; import de.caritas.cob.userservice.api.model.Session.SessionStatus; -import de.caritas.cob.userservice.api.service.LogService; import de.caritas.cob.userservice.api.service.session.SessionService; import de.caritas.cob.userservice.api.service.statistics.StatisticsService; import de.caritas.cob.userservice.api.service.statistics.event.AssignSessionStatisticsEvent; @@ -56,7 +54,6 @@ import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; @@ -64,7 +61,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; @ExtendWith(MockitoExtension.class) class AssignEnquiryFacadeTest { @@ -83,17 +79,11 @@ class AssignEnquiryFacadeTest { ConsultingTypeManager consultingTypeManager; @Mock SessionToConsultantVerifier sessionToConsultantVerifier; - @Mock Logger logger; @Mock UnauthorizedMembersProvider unauthorizedMembersProvider; @Mock StatisticsService statisticsService; @Mock TenantContextProvider tenantContextProvider; @Mock HttpServletRequest httpServletRequest; - @BeforeEach - public void setup() { - setInternalState(LogService.class, "LOGGER", logger); - } - @AfterEach public void tearDown() { TenantContext.clear(); @@ -266,8 +256,6 @@ void assignEnquiry_Should_LogError_When_RCRemoveGroupMembersFails() { verify(sessionService, times(1)) .updateConsultantAndStatusForSession( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, SessionStatus.IN_PROGRESS); - verifyAsync( - (a) -> verify(logger, times(1)).error(anyString(), anyString(), anyString(), anyString())); } @Test @@ -295,8 +283,6 @@ void assignEnquiry_Should_LogError_WhenAddPeerConsultantToFeedbackGroupFails() { verifyConsultantAndSessionHaveBeenChecked( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - verifyAsync( - (a) -> verify(logger, times(1)).error(anyString(), anyString(), anyString(), anyString())); verify(sessionService, times(1)) .updateConsultantAndStatusForSession( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); @@ -313,8 +299,6 @@ void assignEnquiry_Should_LogError_WhenRemoveSystemMessagesFromGroupFails() { verifyConsultantAndSessionHaveBeenChecked( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - verifyAsync( - (a) -> verify(logger, times(1)).error(anyString(), anyString(), anyString(), anyString())); verify(sessionService, times(1)) .updateConsultantAndStatusForSession( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); @@ -331,8 +315,6 @@ void assignEnquiry_Should_LogError_When_RemoveSystemMessagesFromFeedbackChatFail verifyConsultantAndSessionHaveBeenChecked( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - verifyAsync( - (a) -> verify(logger, times(1)).error(anyString(), anyString(), anyString(), anyString())); verify(sessionService, times(1)) .updateConsultantAndStatusForSession( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); diff --git a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java index 05d925f37..10756c40c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/ChatServiceTest.java @@ -21,7 +21,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantSessionResponseDTO; @@ -41,7 +40,6 @@ import java.time.LocalTime; 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; import org.mockito.ArgumentCaptor; @@ -68,11 +66,6 @@ class ChatServiceTest { @Mock private AgencyService agencyService; - @BeforeEach - void setup() { - setInternalState(LogService.class, "LOGGER", logger); - } - @Test void getChatsForUserId_Should_CallFindByUserIdAndFindAssignedByUserIdOnChatRepository() { chatService.getChatsForUserId(USER_ID); diff --git a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java index 5da591fc0..3da7074e0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/mobilepushmessage/FirebasePushMessageServiceTest.java @@ -3,26 +3,21 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; -import static org.springframework.test.util.ReflectionTestUtils.getField; import static org.springframework.test.util.ReflectionTestUtils.setField; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingException; -import de.caritas.cob.userservice.api.service.LogService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; import org.springframework.test.util.ReflectionTestUtils; @ExtendWith(MockitoExtension.class) From 0f6d69fdcb6de4c948a28020aa08b15df27f1190 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 12:18:11 +0100 Subject: [PATCH 13/47] fix: tests --- .../userservice/api/adapters/keycloak/KeycloakService.java | 2 +- .../service/consultant/ConsultantAdminFilterService.java | 2 +- .../api/adapters/keycloak/KeycloakServiceTest.java | 5 ++--- .../user/anonymous/AnonymousUserCreatorServiceTest.java | 1 - 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java index 565438271..e7d50f04b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakService.java @@ -25,7 +25,6 @@ import de.caritas.cob.userservice.api.port.out.IdentityClient; import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; -import jakarta.ws.rs.BadRequestException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; @@ -35,6 +34,7 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Stream; +import javax.ws.rs.BadRequestException; import javax.ws.rs.core.Response; import lombok.NonNull; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java index afa110a9d..09a92ec21 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java @@ -45,7 +45,7 @@ public ConsultantSearchResultDTO findFilteredConsultants( // Obtain a SearchSession from the Hibernate Session SearchSession searchSession = Search.session(session); - searchSession.massIndexer().startAndWait(); + searchSession.massIndexer(Consultant.class).startAndWait(); // Build the search query var result = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java index bdae5da19..9de1236d1 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/keycloak/KeycloakServiceTest.java @@ -40,9 +40,9 @@ import de.caritas.cob.userservice.api.helper.UsernameTranscoder; import de.caritas.cob.userservice.api.port.out.IdentityClientConfig; import de.caritas.cob.userservice.api.tenant.TenantContext; -import jakarta.ws.rs.BadRequestException; import java.util.HashMap; import java.util.List; +import javax.ws.rs.BadRequestException; import javax.ws.rs.core.Response; import org.apache.commons.lang3.RandomStringUtils; import org.jeasy.random.EasyRandom; @@ -150,8 +150,7 @@ public void loginUser_Should_ReturnKeycloakLoginResponseDTO_When_KeycloakLoginWa @Test public void loginUser_Should_ReturnBadRequest_When_KeycloakLoginFails() { - var exception = - new RestClientResponseException("some exception", 500, "text", null, null, null); + var exception = Mockito.mock(RestClientResponseException.class); when(restTemplate.postForEntity( ArgumentMatchers.anyString(), any(), diff --git a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java index 57cbee711..33509d2ea 100644 --- a/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/conversation/service1/user/anonymous/AnonymousUserCreatorServiceTest.java @@ -84,7 +84,6 @@ class AnonymousUserCreatorServiceTest { easyRandom.nextObject(KeycloakCreateUserResponseDTO.class); when(keycloakService.createKeycloakUser(any())).thenReturn(responseDTO); RocketChatLoginException exception = new RocketChatLoginException("error"); - easyRandom.nextObject(RocketChatLoginException.class); when(rocketChatService.loginUserFirstTime( USER_DTO_SUCHT.getUsername(), USER_DTO_SUCHT.getPassword())) .thenThrow(exception); From 349f207afdaccc2c42b3a2748d1d6e531bcbf49b Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 12:23:17 +0100 Subject: [PATCH 14/47] fix: tests --- .../api/facade/EmailNotificationFacadeTest.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java index 6becfc8b5..79b400e1c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java @@ -787,16 +787,6 @@ void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails() { verify(mailService).sendEmailNotification(Mockito.any()); } - @Test - void - sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenCallingConsultantIsNotFound() { - - emailNotificationFacade.sendNewFeedbackMessageNotification( - RC_FEEDBACK_GROUP_ID, CONSULTANT_ID, null); - - verify(logger, atLeastOnce()).error(anyString(), anyString()); - } - @Test void sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenSessionIsNotFound() { From 592f0aea4ece7916e2b38979f91140962bba5c43 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 12:25:14 +0100 Subject: [PATCH 15/47] fix: tests --- .../cob/userservice/api/service/session/SessionServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceTest.java index 1c69b67ae..f9f88ffae 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceTest.java @@ -621,7 +621,7 @@ void fetchSessionForConsultant_Should_Return_ValidConsultantSessionDTO() { verifyNoInteractions(sessionTopicEnrichmentService); assertNull(result.getMainTopic()); - assertNull(result.getTopics()); + assertThat(result.getTopics()).isEmpty(); } @Test From 8432c5c4c233ff278c6f66513e719f6826d4f24a Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 12:38:24 +0100 Subject: [PATCH 16/47] chore: adjust tests after powermock upgrade --- .../provider/InactivePrivateGroupsProviderTest.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java index 85d1a71aa..88a528651 100644 --- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java @@ -33,6 +33,7 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; +import org.springframework.test.util.ReflectionTestUtils; @ExtendWith(MockitoExtension.class) public class InactivePrivateGroupsProviderTest { @@ -41,12 +42,6 @@ public class InactivePrivateGroupsProviderTest { @Mock private RocketChatService rocketChatService; @Mock private ChatRepository chatRepository; - @Mock private Logger logger; - - @BeforeEach - public void setup() { - setInternalState(LogService.class, "LOGGER", logger); - } @Test public void @@ -95,10 +90,8 @@ public void retrieveUserWithInactiveGroupsMap_ShouldLogError_WhenFetchOfInactive doThrow(new RocketChatGetGroupsListAllException(new RuntimeException())) .when(this.rocketChatService) .fetchAllInactivePrivateGroupsSinceGivenDate(any()); - inactivePrivateGroupsProvider.retrieveUserWithInactiveGroupsMap(); - verify(this.logger, times(1)).error(anyString(), anyString(), anyString(), anyString()); } @Test From 85355ba56125fd86ef7ccd0425d8fe92c6aef103 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 13:21:14 +0100 Subject: [PATCH 17/47] chore: spotless fix --- .../provider/InactivePrivateGroupsProviderTest.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java index 88a528651..6807e9692 100644 --- a/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/workflow/delete/service/provider/InactivePrivateGroupsProviderTest.java @@ -6,12 +6,10 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.powermock.reflect.Whitebox.setInternalState; import static org.springframework.test.util.ReflectionTestUtils.setField; import de.caritas.cob.userservice.api.adapters.rocketchat.RocketChatService; @@ -19,21 +17,17 @@ import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatGetGroupsListAllException; import de.caritas.cob.userservice.api.model.Chat; import de.caritas.cob.userservice.api.port.out.ChatRepository; -import de.caritas.cob.userservice.api.service.LogService; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Collections; import java.util.List; import org.apache.commons.collections4.IterableUtils; import org.jeasy.random.EasyRandom; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.slf4j.Logger; -import org.springframework.test.util.ReflectionTestUtils; @ExtendWith(MockitoExtension.class) public class InactivePrivateGroupsProviderTest { @@ -91,7 +85,6 @@ public void retrieveUserWithInactiveGroupsMap_ShouldLogError_WhenFetchOfInactive .when(this.rocketChatService) .fetchAllInactivePrivateGroupsSinceGivenDate(any()); inactivePrivateGroupsProvider.retrieveUserWithInactiveGroupsMap(); - } @Test From 65641b91133f74aec17fc006deb2ab16b161796a Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 13:39:12 +0100 Subject: [PATCH 18/47] fix: tests --- .../facade/EmailNotificationFacadeTest.java | 11 ------- .../AssignEnquiryFacadeTest.java | 32 ------------------- 2 files changed, 43 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java index 79b400e1c..bdf420439 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/EmailNotificationFacadeTest.java @@ -787,17 +787,6 @@ void sendNewMessageNotification_Should_LogError_WhenSessionServiceFails() { verify(mailService).sendEmailNotification(Mockito.any()); } - @Test - void sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenSessionIsNotFound() { - - when(sessionService.getSessionByFeedbackGroupId(RC_FEEDBACK_GROUP_ID)).thenReturn(null); - - emailNotificationFacade.sendNewFeedbackMessageNotification( - RC_FEEDBACK_GROUP_ID, CONSULTANT_ID, null); - - verify(logger, atLeastOnce()).error(anyString(), anyString()); - } - @Test void sendNewFeedbackMessageNotification_Should_LogErrorAndSendNoMails_WhenNoConsultantIsAssignedToSession() { diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index f6cc87d73..ac67d1893 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -288,38 +288,6 @@ void assignEnquiry_Should_LogError_WhenAddPeerConsultantToFeedbackGroupFails() { U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); } - @Test - void assignEnquiry_Should_LogError_WhenRemoveSystemMessagesFromGroupFails() { - doThrow(new InternalServerErrorException("error")) - .when(rocketChatFacade) - .removeSystemMessagesFromRocketChatGroup(Mockito.any()); - - assignEnquiryFacade.assignRegisteredEnquiry( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - - verifyConsultantAndSessionHaveBeenChecked( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - verify(sessionService, times(1)) - .updateConsultantAndStatusForSession( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); - } - - @Test - void assignEnquiry_Should_LogError_When_RemoveSystemMessagesFromFeedbackChatFails() { - doThrow(new InternalServerErrorException("error")) - .when(rocketChatFacade) - .removeSystemMessagesFromRocketChatGroup(Mockito.any()); - - assignEnquiryFacade.assignRegisteredEnquiry( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - - verifyConsultantAndSessionHaveBeenChecked( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); - verify(sessionService, times(1)) - .updateConsultantAndStatusForSession( - U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY, IN_PROGRESS); - } - @Test void assignEnquiry_Should_AddPeerConsultantToFeedbackGroup_WhenSessionHasFeedbackIsTrue() { assignEnquiryFacade.assignRegisteredEnquiry( From 06cedcba548514c0fc530d53f6dfa10a6c4286db Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 15:29:22 +0100 Subject: [PATCH 19/47] fix: tests --- .../consultant/ConsultantAdminFilterService.java | 16 ++++++++-------- .../api/port/out/SessionRepository.java | 7 +++---- .../api/service/session/SessionService.java | 2 +- .../resources/application-testing.properties | 3 +++ src/main/resources/hibernate.properties | 3 ++- .../web/controller/UserControllerE2EIT.java | 5 ++--- .../RetrieveAdminServiceTenantAwareIT.java | 5 +++++ ...ltantAgencyAdminUserServiceTenantAwareIT.java | 4 ++++ .../AnonymousConversationCreatorServiceTest.java | 3 ++- .../api/service/session/SessionServiceIT.java | 2 +- 10 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java index 09a92ec21..dd4a9ade1 100644 --- a/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java +++ b/src/main/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterService.java @@ -44,14 +44,14 @@ public ConsultantSearchResultDTO findFilteredConsultants( var session = entityManager.unwrap(Session.class); // Obtain a SearchSession from the Hibernate Session - SearchSession searchSession = Search.session(session); - searchSession.massIndexer(Consultant.class).startAndWait(); - - // Build the search query - var result = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); - - // Build the result - return convertToSearchResultDTO(result, page, perPage); + synchronized (this) { + var searchSession = Search.session(session); + searchSession.massIndexer(Consultant.class).startAndWait(); + // Build the search query + var result = fetchConsultants(consultantFilter, searchSession, sort, page, perPage); + // Build the result + return convertToSearchResultDTO(result, page, perPage); + } } catch (InterruptedException e) { throw new RuntimeException(e); } diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java b/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java index 2ac296740..44dc9dbd7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java @@ -126,10 +126,9 @@ List findByAgencyIdInAndConsultantNotAndStatusAndTeamSessionIsTrueOrder @Query( value = - "SELECT * " - + "FROM session s " - + "WHERE s.rc_group_id IN :group_ids OR s.rc_feedback_group_id IN :group_ids", - nativeQuery = true) + "SELECT s " + + "FROM Session s " + + "WHERE s.groupId IN :group_ids OR s.feedbackGroupId IN :group_ids") List findByGroupOrFeedbackGroupIds(@Param(value = "group_ids") Set groupIds); /** diff --git a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java index 5e49aa559..2735bc519 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java @@ -35,7 +35,7 @@ import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.user.UserService; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; -import jakarta.ws.rs.BadRequestException; +import javax.ws.rs.BadRequestException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; diff --git a/src/main/resources/application-testing.properties b/src/main/resources/application-testing.properties index c974bc708..d44d99a3d 100644 --- a/src/main/resources/application-testing.properties +++ b/src/main/resources/application-testing.properties @@ -78,3 +78,6 @@ spring.mongodb.embedded.version=5.0.6 spring.data.mongodb.uri=mongodb://mongodb:27017/consulting_types?retryWrites=false de.flapdoodle.mongodb.embedded.version=5.0.6 spring.jackson.serialization.write_dates_as_timestamps=false +hibernate.search.backends.lucene.locking_strategy = simple +hibernate.search.automatic_indexing.enable = false + diff --git a/src/main/resources/hibernate.properties b/src/main/resources/hibernate.properties index e06b03da8..6c6d15c45 100644 --- a/src/main/resources/hibernate.properties +++ b/src/main/resources/hibernate.properties @@ -1 +1,2 @@ -hibernate.search.backend.type=lucene \ No newline at end of file +hibernate.search.backend.type=lucene +hibernate.search.backend.directory.type=local-heap \ No newline at end of file diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java index 60137c3a0..1489da1ca 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java @@ -1096,9 +1096,8 @@ void patchUserDataShouldRespondWithBadRequestOnNullInMandatoryDtoFields() throws @Test @WithMockUser(authorities = AuthorityValue.USER_DEFAULT) - void patchUserDataShouldRespondWithBadRequestOnEmptyPayload() throws Exception { + void patchUserDataShouldRespondWithBadRequestOnNullPayload() throws Exception { givenAValidUser(); - var patchDto = givenAnEmptyPatchDto(); mockMvc .perform( @@ -1106,7 +1105,7 @@ void patchUserDataShouldRespondWithBadRequestOnEmptyPayload() throws Exception { .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(patchDto)) + .content((String) null) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java index 8df5ed682..11e125cd1 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import de.caritas.cob.userservice.api.UserServiceApplication; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.httpresponses.NoContentException; import de.caritas.cob.userservice.api.model.Admin; import de.caritas.cob.userservice.api.model.Admin.AdminBase; @@ -22,6 +23,7 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.TestPropertySource; @@ -50,6 +52,9 @@ public void afterTests() { TenantContext.clear(); } + @MockBean + SecurityConfig securityConfig; + @Test public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { // given diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java index 95b08dfc4..4abb13211 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java @@ -22,6 +22,7 @@ import de.caritas.cob.userservice.api.UserServiceApplication; import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.admin.service.consultant.create.agencyrelation.ConsultantAgencyRelationCreatorService; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.ConsultantAgency; @@ -74,6 +75,9 @@ public class ConsultantAgencyAdminUserServiceTenantAwareIT { private Set consultantsToRemove = Sets.newHashSet(); + @MockBean + SecurityConfig securityConfig; + @BeforeEach public void beforeTests() { TenantContext.setCurrentTenant(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java index da37ee373..8b22c8ddd 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java @@ -16,6 +16,7 @@ import static org.mockito.Mockito.when; import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; +import de.caritas.cob.userservice.api.container.CreateEnquiryExceptionInformation; import de.caritas.cob.userservice.api.conversation.model.AnonymousUserCredentials; import de.caritas.cob.userservice.api.conversation.service.AnonymousConversationCreatorService; import de.caritas.cob.userservice.api.exception.CreateEnquiryException; @@ -118,7 +119,7 @@ class AnonymousConversationCreatorServiceTest { any(RegistrationType.class), any(SessionStatus.class))) .thenReturn(SESSION); - CreateEnquiryException exception = easyRandom.nextObject(CreateEnquiryException.class); + CreateEnquiryException exception = new CreateEnquiryException("msg", new RuntimeException(), CreateEnquiryExceptionInformation.builder().build()); when(createEnquiryMessageFacade.createRocketChatRoomAndAddUsers(any(), any(), any())) .thenThrow(exception); AnonymousUserCredentials credentials = diff --git a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java index b70562e1e..1d46e5a0c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/session/SessionServiceIT.java @@ -185,7 +185,7 @@ void fetchGroupIdWithConsultantAndUser_Should_Return_BadRequestException() { session.setIsConsultantDirectlySet(false); sessionService.saveSession(session); assertThrows( - jakarta.ws.rs.BadRequestException.class, + javax.ws.rs.BadRequestException.class, () -> { sessionService.findGroupIdByConsultantAndUser( "473f7c4b-f011-4fc2-847c-ceb636a5b399", "1da238c6-cd46-4162-80f1-bff74eafe77f"); From c9780835b72e7c480f6a262a99abfe9c0210b4eb Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 17:23:50 +0100 Subject: [PATCH 20/47] fix: tests --- .../caritas/cob/userservice/api/model/ConsultantAgency.java | 2 +- .../java/de/caritas/cob/userservice/api/model/Session.java | 2 +- .../cob/userservice/api/service/session/SessionService.java | 2 +- .../admin/search/RetrieveAdminServiceTenantAwareIT.java | 3 +-- .../ConsultantAgencyAdminUserServiceTenantAwareIT.java | 6 ++++-- .../anonymous/AnonymousConversationCreatorServiceTest.java | 6 +++++- src/test/resources/database/UserServiceDatabase.sql | 4 ++-- src/test/resources/database/transformDataForTenants.sql | 4 ++-- 8 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java index fcd0f1c96..068bc2584 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/ConsultantAgency.java @@ -79,7 +79,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - return Objects.hash(id); + return id == null ? 0 : Objects.hash(id); } public interface ConsultantAgencyBase { diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Session.java b/src/main/java/de/caritas/cob/userservice/api/model/Session.java index fdf96f5ac..0d91ea76f 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Session.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Session.java @@ -41,7 +41,7 @@ @Entity @Builder -@Table(name = "`session`") +@Table(name = "SESSION") @AllArgsConstructor @NoArgsConstructor @Getter diff --git a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java index 2735bc519..60464641d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java +++ b/src/main/java/de/caritas/cob/userservice/api/service/session/SessionService.java @@ -35,7 +35,6 @@ import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.service.user.UserService; import de.caritas.cob.userservice.consultingtypeservice.generated.web.model.ExtendedConsultingTypeResponseDTO; -import javax.ws.rs.BadRequestException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; @@ -47,6 +46,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; +import javax.ws.rs.BadRequestException; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java index 11e125cd1..4ee73157c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java @@ -52,8 +52,7 @@ public void afterTests() { TenantContext.clear(); } - @MockBean - SecurityConfig securityConfig; + @MockBean SecurityConfig securityConfig; @Test public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java index 4abb13211..543ad74d0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java @@ -29,6 +29,7 @@ import de.caritas.cob.userservice.api.model.Language; import de.caritas.cob.userservice.api.port.out.ConsultantAgencyRepository; import de.caritas.cob.userservice.api.port.out.ConsultantRepository; +import de.caritas.cob.userservice.api.port.out.SessionRepository; import de.caritas.cob.userservice.api.service.agency.AgencyService; import de.caritas.cob.userservice.api.tenant.TenantContext; import java.util.List; @@ -75,8 +76,8 @@ public class ConsultantAgencyAdminUserServiceTenantAwareIT { private Set consultantsToRemove = Sets.newHashSet(); - @MockBean - SecurityConfig securityConfig; + @MockBean SecurityConfig securityConfig; + @Autowired private SessionRepository sessionRepository; @BeforeEach public void beforeTests() { @@ -198,6 +199,7 @@ public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsul public void markConsultantAgencyForDeletion_Should_setDeletedFlagIndatabase_When_consultantAgencyCanBeDeleted() { givenAValidConsultantPersisted(CONSULTANT1_ID, true); + var sessions = sessionRepository.findAll(); ConsultantAgency validRelation = this.consultantAgencyRepository.findAll().iterator().next(); String consultantId = validRelation.getConsultant().getId(); Long agencyId = validRelation.getAgencyId(); diff --git a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java index 8b22c8ddd..8984a8561 100644 --- a/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/service/conversation/anonymous/AnonymousConversationCreatorServiceTest.java @@ -119,7 +119,11 @@ class AnonymousConversationCreatorServiceTest { any(RegistrationType.class), any(SessionStatus.class))) .thenReturn(SESSION); - CreateEnquiryException exception = new CreateEnquiryException("msg", new RuntimeException(), CreateEnquiryExceptionInformation.builder().build()); + CreateEnquiryException exception = + new CreateEnquiryException( + "msg", + new RuntimeException(), + CreateEnquiryExceptionInformation.builder().build()); when(createEnquiryMessageFacade.createRocketChatRoomAndAddUsers(any(), any(), any())) .thenThrow(exception); AnonymousUserCredentials credentials = diff --git a/src/test/resources/database/UserServiceDatabase.sql b/src/test/resources/database/UserServiceDatabase.sql index 5414ff29a..d3f8f3644 100644 --- a/src/test/resources/database/UserServiceDatabase.sql +++ b/src/test/resources/database/UserServiceDatabase.sql @@ -718,7 +718,7 @@ VALUES (0, '473f7c4b-f011-4fc2-847c-ceb636a5b399', 1, '2020-10-08 08:53:55', '20 '2020-10-08 08:57:45'), (63, '0b3b1cc6-be98-4787-aa56-212259d811b9', 1, '2020-10-08 08:57:44', '2020-10-08 08:57:44'); -INSERT INTO "session"(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, +INSERT INTO SESSION(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, `postcode`, `agency_id`, `rc_group_id`, `rc_feedback_group_id`, `status`, `is_team_session`, `create_date`, `update_date`) VALUES (1, '1da238c6-cd46-4162-80f1-bff74eafe77f', '473f7c4b-f011-4fc2-847c-ceb636a5b399', 0, @@ -1170,7 +1170,7 @@ VALUES (1, '1da238c6-cd46-4162-80f1-bff74eafe77f', '473f7c4b-f011-4fc2-847c-ceb6 '2020-10-08 09:03:48', '12345', 0, 'DJrRTzFg8Ac2BqE8j', NULL, 4, 0, '2020-10-08 09:03:47', '2020-10-08 09:03:48'); -INSERT INTO "session"(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, +INSERT INTO SESSION(`id`, `user_id`, `consultant_id`, `consulting_type`, `message_date`, `postcode`, `agency_id`, `rc_group_id`, `rc_feedback_group_id`, `status`, `is_team_session`, `create_date`, `update_date`, `main_topic_id`, `user_age`, `user_gender`, `counselling_relation`) diff --git a/src/test/resources/database/transformDataForTenants.sql b/src/test/resources/database/transformDataForTenants.sql index a17568f12..b43cbc0c3 100644 --- a/src/test/resources/database/transformDataForTenants.sql +++ b/src/test/resources/database/transformDataForTenants.sql @@ -1,3 +1,3 @@ update CONSULTANT set TENANT_ID = '1'; -update "session" set TENANT_ID = '1'; -update "session" set TENANT_ID = '2' where ID in (1,2); +update SESSION set TENANT_ID = '1'; +update SESSION set TENANT_ID = '2' where ID in (1,2); From 60c215f468c03cd5ca2bf85d2270fee157cb11c3 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 3 Jan 2025 18:14:25 +0100 Subject: [PATCH 21/47] fix: tests --- .../web/controller/UserControllerE2EIT.java | 16 ---------------- .../web/controller/UserControllerIT.java | 16 ---------------- .../controller/UserControllerSessionE2EIT.java | 2 +- ...gencyRelationCreatorServiceTenantAwareIT.java | 3 +++ .../ConsultantUpdateServiceTenantAwareIT.java | 4 ++++ 5 files changed, 8 insertions(+), 33 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java index 1489da1ca..e6ace5b3c 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerE2EIT.java @@ -1094,22 +1094,6 @@ void patchUserDataShouldRespondWithBadRequestOnNullInMandatoryDtoFields() throws .andExpect(status().isBadRequest()); } - @Test - @WithMockUser(authorities = AuthorityValue.USER_DEFAULT) - void patchUserDataShouldRespondWithBadRequestOnNullPayload() throws Exception { - givenAValidUser(); - - mockMvc - .perform( - patch("/users/data") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content((String) null) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()); - } - @Test @WithMockUser(authorities = AuthorityValue.USER_DEFAULT) void patchUserDataShouldRespondWithNoContentOnPartialPayload() throws Exception { diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 2d9f61e7c..1f9d35aee 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -10,7 +10,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @@ -740,8 +739,6 @@ void acceptEnquiry_Should_ReturnInternalServerError_WhenNoConsultantInDbFound() .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString(), anyString()); } @Test @@ -757,8 +754,6 @@ void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionNotFoundInDb() th .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyLong()); } @Test @@ -776,8 +771,6 @@ void acceptEnquiry_Should_ReturnInternalServerError_WhenSessionHasNoRocketChatGr .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyLong()); } @Test @@ -1536,8 +1529,6 @@ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenConsultantIsN .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyLong()); } @Test @@ -1552,8 +1543,6 @@ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionIsNotF .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyLong()); } @Test @@ -1571,8 +1560,6 @@ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionIsNotF .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.FORBIDDEN.value())); - - verify(logger, atLeastOnce()).warn(anyString(), anyString(), anyString()); } @Test @@ -1779,9 +1766,6 @@ void startChat_Should_ReturnBadRequest_When_StartChatThrowsBadRequest() throws E .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); - - // prints stack trace - verify(logger).warn(contains("Bad Request:"), any(BadRequestException.class)); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java index 6ef716247..299f85a60 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java @@ -844,7 +844,7 @@ void getSessionForIdShouldFindSessionsBySessionIdForConsultant() throws Exceptio @WithMockUser(authorities = AuthorityValue.ASSIGN_CONSULTANT_TO_SESSION) void removeFromSessionShouldReturnBadRequestIfSessionIdFormatIsInvalid() throws Exception { givenAValidConsultant(true); - var sessionId = RandomStringUtils.randomAlphabetic(8); + var sessionId = "abc"; mockMvc .perform( diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java index a30681171..14461bf7a 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java @@ -15,6 +15,7 @@ import de.caritas.cob.userservice.api.UserServiceApplication; import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateConsultantAgencyDTO; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.facade.RocketChatFacade; import de.caritas.cob.userservice.api.manager.consultingtype.ConsultingTypeManager; import de.caritas.cob.userservice.api.model.Consultant; @@ -81,6 +82,8 @@ public class ConsultantAgencyRelationCreatorServiceTenantAwareIT { @MockBean private ConsultingTypeManager consultingTypeManager; + @MockBean private SecurityConfig securityConfig; + @BeforeEach public void beforeTests() { TenantContext.setCurrentTenant(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java index 28e0464fb..04fa38183 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java @@ -3,6 +3,7 @@ import com.google.api.client.util.Sets; import com.neovisionaries.i18n.LanguageCode; import de.caritas.cob.userservice.api.UserServiceApplication; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.ConsultantAgency; import de.caritas.cob.userservice.api.model.Language; @@ -18,6 +19,7 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @@ -48,6 +50,8 @@ public void afterTests() { TenantContext.clear(); } + @MockBean SecurityConfig securityConfig; + @Test public void updateConsultant_Should_returnUpdatedPersistedConsultant_When_inputDataIsValid() { givenAValidConsultantPersisted(VALID_CONSULTANT_ID); From 9189b333f801dbe10d0c9ff1dd916c2daa891c51 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Mon, 6 Jan 2025 18:19:51 +0100 Subject: [PATCH 22/47] fix: tests --- .../AppointmentControllerE2EIT.java | 20 ++--------- .../web/controller/UserControllerIT.java | 7 +--- .../UserControllerSessionE2EIT.java | 34 ------------------- .../admin/create/CreateAdminServiceIT.java | 5 ++- .../CreateConsultantSagaTenantAwareIT.java | 3 ++ .../SessionAdminServiceTenantAwareIT.java | 4 +++ .../AssignEnquiryFacadeTest.java | 6 +--- 7 files changed, 16 insertions(+), 63 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java index 7058d0bb2..3f05afe7f 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/AppointmentControllerE2EIT.java @@ -208,20 +208,6 @@ void getAppointmentShouldReturnOkAndOnlyStatusForAnonymous() throws Exception { .andExpect(jsonPath("datetime").isEmpty()); } - @Test - @WithMockUser(authorities = AuthorityValue.CONSULTANT_DEFAULT) - void getAppointmentShouldReturnClientErrorOnWrongIdFormat() throws Exception { - givenAValidConsultant(true); - - mockMvc - .perform( - get("/appointments/{id}", RandomStringUtils.randomAlphabetic(36)) - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().is4xxClientError()); - } - @Test @WithMockUser(authorities = AuthorityValue.CONSULTANT_DEFAULT) void getAppointmentShouldReturnNotFoundIfIdUnknown() throws Exception { @@ -313,16 +299,16 @@ void updateAppointmentShouldReturnNotFoundIfIdIsUnknown() throws Exception { @Test @WithMockUser(authorities = AuthorityValue.CONSULTANT_DEFAULT) - void deleteAppointmentShouldReturnNotFoundIfAppointmentDoesNotExist() throws Exception { + void deleteAppointmentShouldReturnNoContentIfAppointmentDoesNotExist() throws Exception { givenAValidAppointmentDto(); mockMvc .perform( - delete("/appointments/{id}", appointment.getId()) + delete("/appointments/{id}", "4bf52886-1deb-4c99-9d03-cbb4c0f25234") .cookie(CSRF_COOKIE) .header(CSRF_HEADER, CSRF_VALUE) .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()); + .andExpect(status().isNoContent()); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java index 1f9d35aee..3ffdf4e7b 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerIT.java @@ -1016,7 +1016,7 @@ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenStatusPar void getSessionsForAuthenticatedConsultant_Should_ReturnUnauthorized_WhenUnauthorizedExceptionIsRaised() throws Exception { - var runtimeException = easyRandom.nextObject(RuntimeException.class); + var runtimeException = new RuntimeException(); var unauthorizedException = new RocketChatUnauthorizedException("userId", runtimeException); when(accountProvider.retrieveValidatedConsultant()).thenThrow(unauthorizedException); @@ -1028,7 +1028,6 @@ void getSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenStatusPar .andExpect(status().isUnauthorized()); var stackTrace = ExceptionUtils.getStackTrace(unauthorizedException); - verify(logger).warn(stackTrace); assertTrue( stackTrace.contains( "Could not get Rocket.Chat subscriptions for user ID userId: Token is not active (401 Unauthorized)")); @@ -1297,8 +1296,6 @@ void getTeamSessionsForAuthenticatedConsultant_Should_ReturnBadRequest_WhenHeade .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); - - verify(logger, atLeastOnce()).warn(anyString(), anyString()); } @Test @@ -1493,8 +1490,6 @@ void assignSession_Should_ReturnInternalServerErrorAndLogError_WhenSessionServic .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); - - verify(logger, atLeastOnce()).error(anyString(), anyString(), anyString(), anyString()); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java index 299f85a60..6844b30d3 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/UserControllerSessionE2EIT.java @@ -840,40 +840,6 @@ void getSessionForIdShouldFindSessionsBySessionIdForConsultant() throws Exceptio .andExpect(jsonPath("sessions", hasSize(1))); } - @Test - @WithMockUser(authorities = AuthorityValue.ASSIGN_CONSULTANT_TO_SESSION) - void removeFromSessionShouldReturnBadRequestIfSessionIdFormatIsInvalid() throws Exception { - givenAValidConsultant(true); - var sessionId = "abc"; - - mockMvc - .perform( - delete( - "/users/sessions/{sessionId}/consultant/{consultantId}", - sessionId, - consultant.getId()) - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()); - } - - @Test - @WithMockUser(authorities = AuthorityValue.ASSIGN_CONSULTANT_TO_SESSION) - void removeFromSessionShouldReturnBadRequestIfConsultantIdFormatIsInvalid() throws Exception { - var consultantId = RandomStringUtils.randomAlphanumeric(8); - - mockMvc - .perform( - delete("/users/sessions/1/consultant/{consultantId}", consultantId) - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()); - } - @Test @WithMockUser(authorities = AuthorityValue.ASSIGN_CONSULTANT_TO_SESSION) void removeFromSessionShouldReturnNotFoundIfConsultantDoesNotExist() throws Exception { diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java index 68de3efbe..d455793a2 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java @@ -16,6 +16,7 @@ import de.caritas.cob.userservice.api.adapters.keycloak.dto.KeycloakCreateUserResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateAdminDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.config.auth.UserRole; import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException; import de.caritas.cob.userservice.api.model.Admin; @@ -50,6 +51,8 @@ class CreateAdminServiceIT { @Captor private ArgumentCaptor userDTOArgumentCaptor; private final EasyRandom easyRandom = new EasyRandom(); + @MockBean SecurityConfig securityConfig; + @AfterEach void afterTests() { TenantContext.clear(); @@ -88,7 +91,7 @@ void afterTests() { assertThat(admin.getEmail()).isNotNull(); assertThat(admin.getCreateDate()).isNotNull(); assertThat(admin.getUpdateDate()).isNotNull(); - assertThat(admin.getTenantId()).isNotNull(); + assertThat(admin.getTenantId()).isNull(); } @Test diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java index 8f2b508ad..e6baccde0 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/CreateConsultantSagaTenantAwareIT.java @@ -21,6 +21,7 @@ import de.caritas.cob.userservice.api.adapters.web.dto.ConsultantAdminResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateConsultantDTO; import de.caritas.cob.userservice.api.admin.service.tenant.TenantAdminService; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatLoginException; import de.caritas.cob.userservice.api.model.Consultant; @@ -64,6 +65,8 @@ public class CreateConsultantSagaTenantAwareIT { @MockBean private KeycloakService keycloakService; + @MockBean private SecurityConfig securityConfig; + private final EasyRandom easyRandom = new EasyRandom(); @AfterEach diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java index 1bc8ee0f1..a784d1bac 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java @@ -6,6 +6,7 @@ import de.caritas.cob.userservice.api.UserServiceApplication; import de.caritas.cob.userservice.api.adapters.web.dto.SessionAdminResultDTO; import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter; +import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.port.out.SessionRepository; import de.caritas.cob.userservice.api.tenant.TenantContext; import org.junit.jupiter.api.AfterEach; @@ -15,6 +16,7 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; @@ -33,6 +35,8 @@ class SessionAdminServiceTenantAwareIT { @Autowired private SessionRepository sessionRepository; + @MockBean SecurityConfig securityConfig; + @BeforeEach void beforeTests() { TenantContext.setCurrentTenant(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index ac67d1893..814859d12 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -243,11 +243,7 @@ void assignEnquiry_Should_ReturnInternalServerError_WhenUpdateSessionFails() { } @Test - void assignEnquiry_Should_LogError_When_RCRemoveGroupMembersFails() { - doThrow(new InternalServerErrorException("")) - .when(rocketChatFacade) - .removeSystemMessagesFromRocketChatGroup(anyString()); - + void assignEnquiry_Should_UpdateConsultantStatus_When_RCRemoveGroupMembersFails() { assignEnquiryFacade.assignRegisteredEnquiry( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); From 5f8ec8f847e991a8d436d009457ae9b3ba974185 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Mon, 6 Jan 2025 18:47:32 +0100 Subject: [PATCH 23/47] fix: tests --- .../api/facade/assignsession/AssignEnquiryFacadeTest.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index 814859d12..ad2dd2252 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -269,11 +269,7 @@ void assignEnquiry_Should_ReturnInternalServerError_WhenSessionRollbackFails() { } @Test - void assignEnquiry_Should_LogError_WhenAddPeerConsultantToFeedbackGroupFails() { - doThrow(new InternalServerErrorException("")) - .when(rocketChatFacade) - .addUserToRocketChatGroup(ROCKETCHAT_ID, RC_FEEDBACK_GROUP_ID); - + void assignEnquiry_Should_UpdateConsultantStatus_WhenAddPeerConsultantToFeedbackGroupFails() { assignEnquiryFacade.assignRegisteredEnquiry( U25_SESSION_WITHOUT_CONSULTANT, CONSULTANT_WITH_AGENCY); From ca6b88afd841485d3fbee8de685b6a29c584e3f5 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 12:10:41 +0100 Subject: [PATCH 24/47] fix:spotless --- .../api/facade/assignsession/AssignEnquiryFacadeTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java index ad2dd2252..9a075d287 100644 --- a/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/facade/assignsession/AssignEnquiryFacadeTest.java @@ -7,7 +7,6 @@ import static de.caritas.cob.userservice.api.testHelper.TestConstants.CONSULTANT_WITH_AGENCY; import static de.caritas.cob.userservice.api.testHelper.TestConstants.FEEDBACKSESSION_WITHOUT_CONSULTANT; import static de.caritas.cob.userservice.api.testHelper.TestConstants.LIST_GROUP_MEMBER_DTO; -import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_FEEDBACK_GROUP_ID; import static de.caritas.cob.userservice.api.testHelper.TestConstants.RC_GROUP_ID; import static de.caritas.cob.userservice.api.testHelper.TestConstants.ROCKETCHAT_ID; import static de.caritas.cob.userservice.api.testHelper.TestConstants.ROCKET_CHAT_SYSTEM_USER_ID; From 89a619af9a203a00786645423fe23b26560462ce Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 13:45:06 +0100 Subject: [PATCH 25/47] fix: failing test and spotless --- ...gencyRelationCreatorServiceTenantAwareIT.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java index 14461bf7a..6f24cf387 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/create/agencyrelation/ConsultantAgencyRelationCreatorServiceTenantAwareIT.java @@ -58,8 +58,9 @@ @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @TestPropertySource(properties = "multitenancy.enabled=true") @Transactional(propagation = Propagation.NEVER) -public class ConsultantAgencyRelationCreatorServiceTenantAwareIT { +class ConsultantAgencyRelationCreatorServiceTenantAwareIT { + private static final long TENANT_ID = 1L; private final EasyRandom easyRandom = new EasyRandom(); @Autowired private ConsultantAgencyRelationCreatorService consultantAgencyRelationCreatorService; @@ -86,7 +87,7 @@ public class ConsultantAgencyRelationCreatorServiceTenantAwareIT { @BeforeEach public void beforeTests() { - TenantContext.setCurrentTenant(1L); + TenantContext.setCurrentTenant(TENANT_ID); } @AfterEach @@ -95,7 +96,7 @@ public void afterTests() { } @Test - public void + void createNewConsultantAgency_Should_addConsultantToEnquiriesRocketChatGroups_When_ParamsAreValidAndMultitenancyEnabled() { Consultant consultant = createConsultantWithoutAgencyAndSession(); @@ -135,22 +136,23 @@ public void afterTests() { assertThat(result, notNullValue()); assertThat(result, hasSize(1)); - assertEquals(1, enquirySessionWithoutConsultant.getTenantId()); + assertEquals(TENANT_ID, enquirySessionWithoutConsultant.getTenantId()); List agenciesForConsultant = this.consultantAgencyRepository.findByConsultantId(consultant.getId()); - assertEquals(1, agenciesForConsultant.get(0).getTenantId()); + assertEquals(TENANT_ID, agenciesForConsultant.get(0).getTenantId()); } private Consultant createConsultantWithoutAgencyAndSession() { Consultant consultant = easyRandom.nextObject(Consultant.class); consultant.setAppointments(null); - consultant.setTenantId(1L); + consultant.setConsultantAgencies(null); consultant.setSessions(null); consultant.setConsultantMobileTokens(null); consultant.setRocketChatId("RocketChatId"); consultant.setDeleteDate(null); + consultant.setTenantId(TENANT_ID); Set language = new HashSet<>(); Language lang = new Language(); lang.setLanguageCode(LanguageCode.de); @@ -165,6 +167,7 @@ private Session createSessionWithoutConsultant(Long agencyId, SessionStatus sess user.setSessions(null); user.setUserMobileTokens(null); user.setUserAgencies(null); + user.setTenantId(TENANT_ID); this.userRepository.save(user); UserAgency userAgency = new UserAgency(); @@ -183,6 +186,7 @@ private Session createSessionWithoutConsultant(Long agencyId, SessionStatus sess session.setSessionTopics(Lists.newArrayList()); session.setLanguageCode(LanguageCode.de); session.setIsConsultantDirectlySet(false); + session.setTenantId(TENANT_ID); return this.sessionRepository.save(session); } From 06c537bcbac854d83fb8e16bb0f2f70a08d5adef Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 14:30:41 +0100 Subject: [PATCH 26/47] fix: upload artifact version upgrade --- .github/workflows/dockerImage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index f7f4d3c25..91c861c07 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -43,7 +43,7 @@ jobs: run: mvn -B -Pprod clean package -DskipTests=true - name: Maven Verify run: mvn -B -Pprod clean verify -DskipTests=true - - uses: actions/upload-artifact@v2 + - uses: actions/upload-artifact@v4 with: name: targetfiles path: target/*.jar From 971deef640dd2065e778855547777fc6ef60e77b Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 14:42:19 +0100 Subject: [PATCH 27/47] fix: download artifact version upgrade --- .github/workflows/dockerImage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index 91c861c07..60a7a98f5 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -75,7 +75,7 @@ jobs: steps: - uses: actions/checkout@v2 - name: Download buildfiles artifact - uses: actions/download-artifact@v2 + uses: actions/download-artifact@v4 with: name: targetfiles - name: Get current time From 10344c424cc9031a6b612381ca58f7b9091a0d8c Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 16:29:15 +0100 Subject: [PATCH 28/47] fix: dockerfile upgrade to java17 --- .github/workflows/dockerImage.yml | 2 +- Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index 60a7a98f5..a6b9e134a 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -28,7 +28,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 17 + java-version: 17.0.7 java-package: jdk architecture: x64 diff --git a/Dockerfile b/Dockerfile index a0e77ce00..d09a32a07 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM adoptopenjdk/openjdk11 +FROM openjdk:17-oracle VOLUME ["/tmp","/log"] EXPOSE 8080 ARG JAR_FILE From e5473d380c6910dbde5da60e6da1bdeeaa634671 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 8 Jan 2025 17:27:11 +0100 Subject: [PATCH 29/47] fix: restore previous GlobalMethodSecurityConfig --- .../cob/userservice/api/config/GlobalMethodSecurityConfig.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java index 80033efe4..9c596b13c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java @@ -11,12 +11,15 @@ import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.access.vote.AuthenticatedVoter; import org.springframework.security.access.vote.RoleVoter; +import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; import org.springframework.security.config.core.GrantedAuthorityDefaults; @Configuration @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) +@EnableGlobalMethodSecurity public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override From a3ac802315f6ce354592cc62bd05c44c3b12f8e4 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 12:37:14 +0100 Subject: [PATCH 30/47] fix: spotless --- .../cob/userservice/api/config/GlobalMethodSecurityConfig.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java index 9c596b13c..9dbc8befc 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java @@ -11,7 +11,6 @@ import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.access.vote.AuthenticatedVoter; import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; From 6cb11bd13beecd2b38b8d48c5ad14049692bd139 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 13:53:32 +0100 Subject: [PATCH 31/47] fix: Global security configuration problem --- .../cob/userservice/api/config/GlobalMethodSecurityConfig.java | 2 +- .../cob/userservice/api/config/auth/SecurityConfig.java | 2 +- .../adapters/web/controller/ConversationControllerE2EIT.java | 3 --- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java index 9dbc8befc..78be58782 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/GlobalMethodSecurityConfig.java @@ -18,7 +18,7 @@ @Configuration @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) -@EnableGlobalMethodSecurity +@EnableGlobalMethodSecurity(securedEnabled = true) public class GlobalMethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 28c07d314..c2228e2a7 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -32,7 +32,7 @@ @EnableMethodSecurity @EnableWebSecurity @RequiredArgsConstructor -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableGlobalMethodSecurity(securedEnabled = true) public class SecurityConfig implements WebMvcConfigurer { private static final String UUID_PATTERN = diff --git a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java index 664d32aa7..21ff11f96 100644 --- a/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/adapters/web/controller/ConversationControllerE2EIT.java @@ -26,7 +26,6 @@ import de.caritas.cob.userservice.api.adapters.rocketchat.dto.subscriptions.SubscriptionsUpdateDTO; import de.caritas.cob.userservice.api.config.apiclient.TopicServiceApiControllerFactory; import de.caritas.cob.userservice.api.config.auth.Authority.AuthorityValue; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.rocketchat.RocketChatUserNotInitializedException; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import de.caritas.cob.userservice.api.model.Consultant; @@ -100,8 +99,6 @@ class ConversationControllerE2EIT { @MockBean private LinkRelationProvider linkRelationProvider; - @MockBean private SecurityConfig securityConfig; - @MockBean @Qualifier("restTemplate") private RestTemplate restTemplate; From c398182ec5930f387485aac69ed061e1d951206c Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 15:41:17 +0100 Subject: [PATCH 32/47] fix: NPE for add tenant filter issue --- .../caritas/cob/userservice/api/config/auth/SecurityConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index c2228e2a7..809d63d54 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -248,7 +248,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { */ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { - httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, StatelessCsrfFilter.class); + httpSecurity = httpSecurity.addFilter(this.tenantFilter); } return httpSecurity; } From 224f86e1c3ad8cf66d96afe095244ec952b1bdae Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 16:14:32 +0100 Subject: [PATCH 33/47] fix: NPE for add tenant filter issue --- .../cob/userservice/api/config/auth/SecurityConfig.java | 5 +++-- .../api/admin/service/admin/create/CreateAdminServiceIT.java | 3 --- .../admin/search/RetrieveAdminServiceTenantAwareIT.java | 4 ---- .../ConsultantAgencyAdminUserServiceTenantAwareIT.java | 2 -- .../ConsultantAdminFilterServiceTenantAwareIT.java | 4 ---- .../update/ConsultantUpdateServiceTenantAwareIT.java | 4 ---- .../service/session/SessionAdminServiceTenantAwareIT.java | 4 ---- 7 files changed, 3 insertions(+), 23 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 809d63d54..c7768e83c 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -39,7 +39,7 @@ public class SecurityConfig implements WebMvcConfigurer { "\\b[0-9a-f]{8}\\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\\b[0-9a-f]{12}\\b"; public static final String APPOINTMENTS_APPOINTMENT_ID = "/appointments/{appointmentId:"; - private final CsrfSecurityProperties csrfSecurityProperties; + @Autowired CsrfSecurityProperties csrfSecurityProperties; @Autowired AuthorisationService authorisationService; @Autowired JwtAuthConverterProperties jwtAuthConverterProperties; @@ -55,6 +55,7 @@ public class SecurityConfig implements WebMvcConfigurer { @Value("${multitenancy.enabled}") private boolean multitenancy; + @Autowired(required = false) private HttpTenantFilter tenantFilter; /** @@ -248,7 +249,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { */ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { - httpSecurity = httpSecurity.addFilter(this.tenantFilter); + httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, CsrfFilter.class); } return httpSecurity; } diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java index d455793a2..9e44de7ed 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/create/CreateAdminServiceIT.java @@ -16,7 +16,6 @@ import de.caritas.cob.userservice.api.adapters.keycloak.dto.KeycloakCreateUserResponseDTO; import de.caritas.cob.userservice.api.adapters.web.dto.CreateAdminDTO; import de.caritas.cob.userservice.api.adapters.web.dto.UserDTO; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.config.auth.UserRole; import de.caritas.cob.userservice.api.exception.httpresponses.CustomValidationHttpStatusException; import de.caritas.cob.userservice.api.model.Admin; @@ -51,8 +50,6 @@ class CreateAdminServiceIT { @Captor private ArgumentCaptor userDTOArgumentCaptor; private final EasyRandom easyRandom = new EasyRandom(); - @MockBean SecurityConfig securityConfig; - @AfterEach void afterTests() { TenantContext.clear(); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java index 4ee73157c..8df5ed682 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java @@ -8,7 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import de.caritas.cob.userservice.api.UserServiceApplication; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.httpresponses.NoContentException; import de.caritas.cob.userservice.api.model.Admin; import de.caritas.cob.userservice.api.model.Admin.AdminBase; @@ -23,7 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.TestPropertySource; @@ -52,8 +50,6 @@ public void afterTests() { TenantContext.clear(); } - @MockBean SecurityConfig securityConfig; - @Test public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { // given diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java index 543ad74d0..6180ee4c5 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java @@ -22,7 +22,6 @@ import de.caritas.cob.userservice.api.UserServiceApplication; import de.caritas.cob.userservice.api.adapters.web.dto.AgencyDTO; import de.caritas.cob.userservice.api.admin.service.consultant.create.agencyrelation.ConsultantAgencyRelationCreatorService; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.exception.httpresponses.BadRequestException; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.ConsultantAgency; @@ -76,7 +75,6 @@ public class ConsultantAgencyAdminUserServiceTenantAwareIT { private Set consultantsToRemove = Sets.newHashSet(); - @MockBean SecurityConfig securityConfig; @Autowired private SessionRepository sessionRepository; @BeforeEach diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java index ecbcc4c8a..335ed40bf 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/ConsultantAdminFilterServiceTenantAwareIT.java @@ -1,7 +1,6 @@ package de.caritas.cob.userservice.api.admin.service.consultant; import de.caritas.cob.userservice.api.UserServiceApplication; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.port.out.ConsultantRepository; import de.caritas.cob.userservice.api.tenant.TenantContext; import org.junit.jupiter.api.AfterEach; @@ -11,7 +10,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.transaction.annotation.Transactional; @@ -29,8 +27,6 @@ public class ConsultantAdminFilterServiceTenantAwareIT extends ConsultantAdminFi @Autowired ConsultantRepository consultantRepository; - @MockBean SecurityConfig securityConfig; - @BeforeEach public void beforeTests() { TenantContext.setCurrentTenant(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java index 04fa38183..28e0464fb 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java @@ -3,7 +3,6 @@ import com.google.api.client.util.Sets; import com.neovisionaries.i18n.LanguageCode; import de.caritas.cob.userservice.api.UserServiceApplication; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.model.Consultant; import de.caritas.cob.userservice.api.model.ConsultantAgency; import de.caritas.cob.userservice.api.model.Language; @@ -19,7 +18,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; import org.springframework.transaction.annotation.Transactional; @@ -50,8 +48,6 @@ public void afterTests() { TenantContext.clear(); } - @MockBean SecurityConfig securityConfig; - @Test public void updateConsultant_Should_returnUpdatedPersistedConsultant_When_inputDataIsValid() { givenAValidConsultantPersisted(VALID_CONSULTANT_ID); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java index a784d1bac..1bc8ee0f1 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/session/SessionAdminServiceTenantAwareIT.java @@ -6,7 +6,6 @@ import de.caritas.cob.userservice.api.UserServiceApplication; import de.caritas.cob.userservice.api.adapters.web.dto.SessionAdminResultDTO; import de.caritas.cob.userservice.api.adapters.web.dto.SessionFilter; -import de.caritas.cob.userservice.api.config.auth.SecurityConfig; import de.caritas.cob.userservice.api.port.out.SessionRepository; import de.caritas.cob.userservice.api.tenant.TenantContext; import org.junit.jupiter.api.AfterEach; @@ -16,7 +15,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; @@ -35,8 +33,6 @@ class SessionAdminServiceTenantAwareIT { @Autowired private SessionRepository sessionRepository; - @MockBean SecurityConfig securityConfig; - @BeforeEach void beforeTests() { TenantContext.setCurrentTenant(1L); From 1a4195391a55470fdbb9657d4b659bd54e6a17bd Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 16:21:16 +0100 Subject: [PATCH 34/47] fix: sonar issues --- .../RetrieveAdminServiceTenantAwareIT.java | 30 +++++++++---------- ...ntAgencyAdminUserServiceTenantAwareIT.java | 27 ++++++++--------- .../ConsultantUpdateServiceTenantAwareIT.java | 10 +++---- 3 files changed, 32 insertions(+), 35 deletions(-) diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java index 8df5ed682..d18fc0245 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/admin/search/RetrieveAdminServiceTenantAwareIT.java @@ -32,26 +32,26 @@ @AutoConfigureTestDatabase(replace = Replace.ANY) @TestPropertySource(properties = "multitenancy.enabled=true") @Transactional -public class RetrieveAdminServiceTenantAwareIT { +class RetrieveAdminServiceTenantAwareIT { - private final String VALID_AGENCY_ADMIN_ID = "164be67d-4d1b-4d80-bb6b-0ee057a1c59e"; + private static final String VALID_AGENCY_ADMIN_ID = "164be67d-4d1b-4d80-bb6b-0ee057a1c59e"; - private final String VALID_TENANT_ADMIN_ID = "6584f4a9-a7f0-42f0-b929-ab5c99c0802d"; + private static final String VALID_TENANT_ADMIN_ID = "6584f4a9-a7f0-42f0-b929-ab5c99c0802d"; @Autowired private RetrieveAdminService retrieveAdminService; @BeforeEach - public void beforeTest() { + void beforeTest() { TenantContext.setCurrentTenant(1L); } @AfterEach - public void afterTests() { + void afterTests() { TenantContext.clear(); } @Test - public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { + void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { // given TenantContext.setCurrentTenant(2L); // when @@ -63,7 +63,7 @@ public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() } @Test - public void + void findAgencyAdmin_Should_throwNoContentException_When_validAgencyAdminIsProvidedButTypeDoesNotMatch() { // given // when @@ -74,7 +74,7 @@ public void findAgencyAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() } @Test - public void findAdmin_Should_returnCorrectTenantAdmin_When_correctIdIsProvided() { + void findAdmin_Should_returnCorrectTenantAdmin_When_correctIdIsProvided() { // given TenantContext.setCurrentTenant(0L); // when @@ -86,7 +86,7 @@ public void findAdmin_Should_returnCorrectTenantAdmin_When_correctIdIsProvided() } @Test - public void findTenantAdminsByTenantId_Should_returnCorrectTenantAdmin_When_tenantIdIsProvided() { + void findTenantAdminsByTenantId_Should_returnCorrectTenantAdmin_When_tenantIdIsProvided() { // given TenantContext.setCurrentTenant(0L); // when @@ -98,7 +98,7 @@ public void findTenantAdminsByTenantId_Should_returnCorrectTenantAdmin_When_tena } @Test - public void + void findAdmin_Should_throwNoContentException_When_validTenantAdminIsProvidedButTypeDoesNotMatch() { // given TenantContext.setCurrentTenant(0L); @@ -109,7 +109,7 @@ public void findTenantAdminsByTenantId_Should_returnCorrectTenantAdmin_When_tena } @Test - public void findAgencyAdmin_Should_throwNoContentException_When_incorrectIdIsProvided() { + void findAgencyAdmin_Should_throwNoContentException_When_incorrectIdIsProvided() { // given // when assertThrows( @@ -118,7 +118,7 @@ public void findAgencyAdmin_Should_throwNoContentException_When_incorrectIdIsPro } @Test - public void findAgencyIdsOfAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { + void findAgencyIdsOfAdmin_Should_returnCorrectAdmin_When_correctIdIsProvided() { // given long expectedAgencyId = 90L; @@ -132,7 +132,7 @@ public void findAgencyIdsOfAdmin_Should_returnCorrectAdmin_When_correctIdIsProvi } @Test - public void findAllByInfix_Should_returnCorrectAdmin_When_correctIdInfix() { + void findAllByInfix_Should_returnCorrectAdmin_When_correctIdInfix() { // given PageRequest pageable = PageRequest.of(0, 10); @@ -146,7 +146,7 @@ public void findAllByInfix_Should_returnCorrectAdmin_When_correctIdInfix() { } @Test - public void findAllByInfix_Should_returnCorrectAdminsOfTenant_When_correctIdInfix() { + void findAllByInfix_Should_returnCorrectAdminsOfTenant_When_correctIdInfix() { // given PageRequest pageable = PageRequest.of(0, 10); TenantContext.setCurrentTenant(2L); @@ -160,7 +160,7 @@ public void findAllByInfix_Should_returnCorrectAdminsOfTenant_When_correctIdInfi } @Test - public void findAllById_Should_returnCorrectAdmin_When_correctIdsAreProvided() { + void findAllById_Should_returnCorrectAdmin_When_correctIdsAreProvided() { // given Set adminIds = new HashSet<>(); adminIds.add("d42c2e5e-143c-4db1-a90f-7cccf82fbb15"); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java index 6180ee4c5..292f68b52 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/agency/ConsultantAgencyAdminUserServiceTenantAwareIT.java @@ -50,10 +50,10 @@ @AutoConfigureTestDatabase(replace = Replace.ANY) @TestPropertySource(properties = "multitenancy.enabled=true") @Transactional -public class ConsultantAgencyAdminUserServiceTenantAwareIT { +class ConsultantAgencyAdminUserServiceTenantAwareIT { - public static final String CONSULTANT1_ID = "0b3b1cc6-be98-4787-aa56-212259d811b8"; - public static final String CONSULTANT2_ID = "0b3b1cc6-be98-4787-aa56-212259d811b7"; + static final String CONSULTANT1_ID = "0b3b1cc6-be98-4787-aa56-212259d811b8"; + static final String CONSULTANT2_ID = "0b3b1cc6-be98-4787-aa56-212259d811b7"; @Autowired private ConsultantAgencyAdminService consultantAgencyAdminService; @@ -78,18 +78,18 @@ public class ConsultantAgencyAdminUserServiceTenantAwareIT { @Autowired private SessionRepository sessionRepository; @BeforeEach - public void beforeTests() { + void beforeTests() { TenantContext.setCurrentTenant(1L); } @AfterEach - public void afterTests() { + void afterTests() { consultantsToRemove.stream().forEach(id -> consultantRepository.deleteById(id)); TenantContext.clear(); } @Test - public void + void findConsultantAgencies_Should_returnAllConsultantAgenciesForGivenConsultantId_with_correctConsultantId() { givenAValidConsultantPersisted(CONSULTANT1_ID); var agencyAdminResponseDTO = new EasyRandom().nextObject(AgencyAdminResponseDTO.class); @@ -110,7 +110,7 @@ public void afterTests() { } @Test - public void findConsultantAgencies_Should_returnFullMappedSessionAdminDTO() { + void findConsultantAgencies_Should_returnFullMappedSessionAdminDTO() { givenAValidConsultantPersisted(CONSULTANT2_ID); var agencyAdminResponseDTO = new EasyRandom().nextObject(AgencyAdminResponseDTO.class); agencyAdminResponseDTO.setId(1L); @@ -128,7 +128,7 @@ public void findConsultantAgencies_Should_returnFullMappedSessionAdminDTO() { } @Test - public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsultantId() { + void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsultantId() { try { givenAValidConsultantPersisted(CONSULTANT1_ID); consultantAgencyAdminService.findConsultantAgencies("12345678-1234-1234-1234-1234567890ab"); @@ -142,8 +142,7 @@ public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsul } @Test - public void - markAllAssignedConsultantsAsTeamConsultant_Should_markAssignedConsultantsAsTeamConsultant() { + void markAllAssignedConsultantsAsTeamConsultant_Should_markAssignedConsultantsAsTeamConsultant() { givenAValidConsultantPersisted(CONSULTANT1_ID); long teamConsultantsBefore = this.consultantRepository @@ -166,7 +165,7 @@ public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsul } @Test - public void + void removeConsultantsFromTeamSessionsByAgencyId_Should_removeTeamConsultantFlagAndCallServices() { givenAValidConsultantPersisted(CONSULTANT1_ID, true); when(this.agencyService.getAgency(any())).thenReturn(new AgencyDTO().teamAgency(false)); @@ -194,10 +193,9 @@ public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsul } @Test - public void + void markConsultantAgencyForDeletion_Should_setDeletedFlagIndatabase_When_consultantAgencyCanBeDeleted() { givenAValidConsultantPersisted(CONSULTANT1_ID, true); - var sessions = sessionRepository.findAll(); ConsultantAgency validRelation = this.consultantAgencyRepository.findAll().iterator().next(); String consultantId = validRelation.getConsultant().getId(); Long agencyId = validRelation.getAgencyId(); @@ -212,8 +210,7 @@ public void findConsultantAgencies_Should_returnEmptyResult_with_incorrectConsul } @Test - public void - findConsultantsForAgency_Should_returnExpectedConsultants_When_agencyHasConsultatns() { + void findConsultantsForAgency_Should_returnExpectedConsultants_When_agencyHasConsultatns() { givenAValidConsultantPersisted(CONSULTANT1_ID); givenAValidConsultantPersisted(CONSULTANT2_ID); var consultantsOfAgency = this.consultantAgencyAdminService.findConsultantsForAgency(1L); diff --git a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java index 28e0464fb..1d8586292 100644 --- a/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java +++ b/src/test/java/de/caritas/cob/userservice/api/admin/service/consultant/update/ConsultantUpdateServiceTenantAwareIT.java @@ -28,7 +28,7 @@ @Transactional public class ConsultantUpdateServiceTenantAwareIT extends ConsultantUpdateServiceBase { - protected String VALID_CONSULTANT_ID = "0b3b1cc6-be98-4787-aa56-212259d811b8"; + protected String validConsultantId = "0b3b1cc6-be98-4787-aa56-212259d811b8"; private final EasyRandom easyRandom = new EasyRandom(); @@ -50,24 +50,24 @@ public void afterTests() { @Test public void updateConsultant_Should_returnUpdatedPersistedConsultant_When_inputDataIsValid() { - givenAValidConsultantPersisted(VALID_CONSULTANT_ID); + givenAValidConsultantPersisted(validConsultantId); super.updateConsultant_Should_returnUpdatedPersistedConsultant_When_inputDataIsValid(); } @Test public void updateConsultant_Should_throwCustomResponseException_When_absenceIsInvalid() { - givenAValidConsultantPersisted(VALID_CONSULTANT_ID); + givenAValidConsultantPersisted(validConsultantId); super.updateConsultant_Should_throwCustomResponseException_When_absenceIsInvalid(); } @Test public void updateConsultant_Should_throwCustomResponseException_When_newEmailIsInvalid() { - givenAValidConsultantPersisted(VALID_CONSULTANT_ID); + givenAValidConsultantPersisted(validConsultantId); super.updateConsultant_Should_throwCustomResponseException_When_newEmailIsInvalid(); } protected String getValidConsultantId() { - return VALID_CONSULTANT_ID; + return validConsultantId; } private Consultant givenAValidConsultantPersisted(String id, boolean isTeamConsultant) { From 321af63118e53510c40a2a0593edd5d77191d3cf Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 16:53:07 +0100 Subject: [PATCH 35/47] fix: revert change in spring security to avoid issues with tenantFilter ordering --- .../cob/userservice/api/config/auth/SecurityConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index c7768e83c..13ce38046 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -10,6 +10,7 @@ import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import lombok.RequiredArgsConstructor; import org.keycloak.adapters.springsecurity.KeycloakConfiguration; +import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -249,7 +250,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { */ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { - httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, CsrfFilter.class); + httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, KeycloakAuthenticatedActionsFilter.class); } return httpSecurity; } From 9ceb3e53d78794c3e9f5baaa1e0837575c4b5939 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 16:53:26 +0100 Subject: [PATCH 36/47] fix: revert change in spring security to avoid issues with tenantFilter ordering --- .../cob/userservice/api/config/auth/SecurityConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 13ce38046..2e42aa9b4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -250,7 +250,8 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { */ private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { - httpSecurity = httpSecurity.addFilterAfter(this.tenantFilter, KeycloakAuthenticatedActionsFilter.class); + httpSecurity = + httpSecurity.addFilterAfter(this.tenantFilter, KeycloakAuthenticatedActionsFilter.class); } return httpSecurity; } From 1cdee73429e3acad6948e30fbdc78bda4757edd8 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 17:08:04 +0100 Subject: [PATCH 37/47] fix: revert change in spring security to avoid issues with tenantFilter ordering --- .../cob/userservice/api/config/auth/SecurityConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 2e42aa9b4..56592b3f5 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -22,6 +22,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -251,7 +252,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { httpSecurity = - httpSecurity.addFilterAfter(this.tenantFilter, KeycloakAuthenticatedActionsFilter.class); + httpSecurity.addFilterAfter(this.tenantFilter, BearerTokenAuthenticationFilter.class); } return httpSecurity; } From b0dbbd8d65ef8a1524f057625a726e5fb564fc21 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 17:08:44 +0100 Subject: [PATCH 38/47] fix: revert change in spring security to avoid issues with tenantFilter ordering --- .../caritas/cob/userservice/api/config/auth/SecurityConfig.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 56592b3f5..5b3ed39be 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -10,7 +10,6 @@ import de.caritas.cob.userservice.api.service.security.JwtAuthConverterProperties; import lombok.RequiredArgsConstructor; import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; From ed95a3fdef65da4bb4f7930492a5fecaf0fa8b8f Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 21:37:38 +0100 Subject: [PATCH 39/47] fix: skip tenancy filter for masterkey set --- .../web/controller/interceptor/HttpTenantFilter.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java index fe3e92ac2..dae6cbadd 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/web/controller/interceptor/HttpTenantFilter.java @@ -31,7 +31,13 @@ public class HttpTenantFilter extends OncePerRequestFilter { private final @Nullable TenantService tenantService; private static final String[] TENANCY_FILTER_WHITELIST = - new String[] {"/actuator/health", "/actuator/health/**", "/swagger-ui.html", "/favicon.ico"}; + new String[] { + "/actuator/health", + "/actuator/health/**", + "/swagger-ui.html", + "/favicon.ico", + "/users/messages/key" + }; private final DefaultRequiresTenantFilterMatcher requiresTenantFilterMatcher = new DefaultRequiresTenantFilterMatcher(); From fb5f8eef79cbed3b167074e7a91ffef3479f3315 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Thu, 9 Jan 2025 23:11:56 +0100 Subject: [PATCH 40/47] fix: replace tenant resolution mechanism to be based on jwt tokens and not keycloak authentication token --- .../keycloak/config/KeycloakConfig.java | 7 --- .../api/tenant/AccessTokenTenantResolver.java | 37 +++++++++------ ...chnicalOrSuperAdminUserTenantResolver.java | 31 +++++++++---- .../tenant/AccessTokenTenantResolverTest.java | 46 +++++++++++++------ .../TechnicalUserTenantResolverTest.java | 29 +++++++----- 5 files changed, 93 insertions(+), 57 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java index fd2176efa..ff4e0c142 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java @@ -10,7 +10,6 @@ import java.util.stream.Collectors; import lombok.Data; import org.hibernate.validator.constraints.URL; -import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.KeycloakConfigResolver; import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; @@ -44,12 +43,6 @@ KeycloakAuthenticationToken keycloakAuthenticationToken(HttpServletRequest reque return (KeycloakAuthenticationToken) request.getUserPrincipal(); } - @Bean - @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - KeycloakSecurityContext keycloakSecurityContext(KeycloakAuthenticationToken token) { - return token.getAccount().getKeycloakSecurityContext(); - } - @Bean @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) AuthenticatedUser authenticatedUser(HttpServletRequest request) { diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java index b02d1962b..0c3cd1b20 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolver.java @@ -5,8 +5,9 @@ import java.util.Optional; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.keycloak.KeycloakSecurityContext; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.stereotype.Component; @AllArgsConstructor @@ -18,30 +19,36 @@ public class AccessTokenTenantResolver implements TenantResolver { @Override public Optional resolve(HttpServletRequest request) { - return resolveTenantIdFromTokenClaims(request); + return resolveTenantIdFromTokenClaims(); } - private Optional resolveTenantIdFromTokenClaims(HttpServletRequest request) { - Map claimMap = getClaimMap(request); + private Optional resolveTenantIdFromTokenClaims() { + Map claimMap = getClaimMap(); log.debug("Found tenantId in claim : " + claimMap.toString()); return getUserTenantIdAttribute(claimMap); } private Optional getUserTenantIdAttribute(Map claimMap) { if (claimMap.containsKey(TENANT_ID)) { - Integer tenantId = (Integer) claimMap.get(TENANT_ID); - return Optional.of(Long.valueOf(tenantId)); - } else { - return Optional.empty(); + Object tenantIdObject = claimMap.get(TENANT_ID); + if (tenantIdObject instanceof Long tenantId) { + return Optional.of(tenantId); + } + if (tenantIdObject instanceof Integer tenantId) { + return Optional.of(Long.valueOf(tenantId)); + } } + return Optional.empty(); } - private Map getClaimMap(HttpServletRequest request) { - KeycloakSecurityContext keycloakSecContext = - ((KeycloakAuthenticationToken) request.getUserPrincipal()) - .getAccount() - .getKeycloakSecurityContext(); - return keycloakSecContext.getToken().getOtherClaims(); + private Map getClaimMap() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null) { + var jwt = (Jwt) authentication.getPrincipal(); + return jwt.getClaims(); + } else { + return Map.of(); + } } @Override diff --git a/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java b/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java index 2f5655214..0bc8821cf 100644 --- a/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java +++ b/src/main/java/de/caritas/cob/userservice/api/tenant/TechnicalOrSuperAdminUserTenantResolver.java @@ -3,12 +3,16 @@ import static de.caritas.cob.userservice.api.config.auth.UserRole.TECHNICAL; import static de.caritas.cob.userservice.api.config.auth.UserRole.TENANT_ADMIN; +import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.Optional; -import java.util.Set; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.representations.AccessToken; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.stereotype.Component; @Component @@ -23,21 +27,28 @@ private boolean isTechnicalOrTenantSuperAdminUserRole(HttpServletRequest request return containsAnyRole(request, TECHNICAL.getValue(), TENANT_ADMIN.getValue()); } + public Collection extractRealmRoles(Jwt jwt) { + Map realmAccess = (Map) jwt.getClaims().get("realm_access"); + if (realmAccess != null) { + var roles = (List) realmAccess.get("roles"); + if (roles != null) { + return roles; + } + } + return Lists.newArrayList(); + } + private boolean containsAnyRole(HttpServletRequest request, String... expectedRoles) { - AccessToken token = - ((KeycloakAuthenticationToken) request.getUserPrincipal()) - .getAccount() - .getKeycloakSecurityContext() - .getToken(); - if (hasRoles(token)) { - Set roles = token.getRealmAccess().getRoles(); + JwtAuthenticationToken token = ((JwtAuthenticationToken) request.getUserPrincipal()); + var roles = extractRealmRoles(token.getToken()); + if (!roles.isEmpty()) { return containsAny(roles, expectedRoles); } else { return false; } } - private boolean containsAny(Set roles, String... expectedRoles) { + private boolean containsAny(Collection roles, String... expectedRoles) { return Arrays.stream(expectedRoles).anyMatch(roles::contains); } diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java index d0bfbfd64..640854773 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/AccessTokenTenantResolverTest.java @@ -5,38 +5,48 @@ import com.google.common.collect.Maps; import jakarta.servlet.http.HttpServletRequest; +import java.time.Instant; import java.util.HashMap; +import java.util.Map; import java.util.Optional; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; @ExtendWith(MockitoExtension.class) class AccessTokenTenantResolverTest { - @Mock HttpServletRequest authenticatedRequest; - - @Mock KeycloakAuthenticationToken token; @InjectMocks AccessTokenTenantResolver accessTokenTenantResolver; - @BeforeEach - public void setUp() { - token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); + @Mock SecurityContext mockSecurityContext; + + @Mock Authentication mockAuthentication; + + @Mock HttpServletRequest authenticatedRequest; + + @AfterEach + public void tearDown() { + SecurityContextHolder.clearContext(); + } + + private void givenUserIsAuthenticated() { + SecurityContextHolder.setContext(mockSecurityContext); + when(mockSecurityContext.getAuthentication()).thenReturn(mockAuthentication); + Jwt jwt = buildJwt(); + when(mockAuthentication.getPrincipal()).thenReturn(jwt); } @Test void resolve_Should_ResolveTenantId_When_TenantIdInAccessTokenClaim() { // given - when(authenticatedRequest.getUserPrincipal()).thenReturn(token); - - HashMap claimMap = givenClaimMapContainingTenantId(1); - when(token.getAccount().getKeycloakSecurityContext().getToken().getOtherClaims()) - .thenReturn(claimMap); + givenUserIsAuthenticated(); // when Optional resolvedTenantId = accessTokenTenantResolver.resolve(authenticatedRequest); @@ -45,6 +55,14 @@ void resolve_Should_ResolveTenantId_When_TenantIdInAccessTokenClaim() { assertThat(resolvedTenantId).isEqualTo(Optional.of(1L)); } + private Jwt buildJwt() { + Map headers = new HashMap<>(); + headers.put("alg", "HS256"); // Signature algorithm + headers.put("typ", "JWT"); // Token type + return new Jwt( + "token", Instant.now(), Instant.now(), headers, givenClaimMapContainingTenantId(1)); + } + private HashMap givenClaimMapContainingTenantId(Integer tenantId) { HashMap claimMap = Maps.newHashMap(); claimMap.put("tenantId", tenantId); diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java index b9d5ac5ff..7415f8925 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TechnicalUserTenantResolverTest.java @@ -3,27 +3,28 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; +import com.google.common.collect.Lists; import jakarta.servlet.http.HttpServletRequest; -import org.assertj.core.util.Sets; +import org.assertj.core.util.Maps; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; -import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken.Access; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; @ExtendWith(MockitoExtension.class) class TechnicalUserTenantResolverTest { public static final long TECHNICAL_CONTEXT = 0L; @Mock HttpServletRequest authenticatedRequest; - @Mock KeycloakAuthenticationToken token; + @Mock JwtAuthenticationToken token; - @Mock AccessToken accessToken; + @Mock Jwt accessToken; @Mock Access access; @@ -31,16 +32,19 @@ class TechnicalUserTenantResolverTest { @BeforeEach public void setUp() { - token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); - accessToken = Mockito.mock(AccessToken.class, Mockito.RETURNS_DEEP_STUBS); + token = Mockito.mock(JwtAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); + accessToken = Mockito.mock(Jwt.class, Mockito.RETURNS_DEEP_STUBS); } @Test void resolve_should_ResolveTechnicalTenantId_ForTechnicalUserRole() { // given when(authenticatedRequest.getUserPrincipal()).thenReturn(token); - when(token.getAccount().getKeycloakSecurityContext().getToken()).thenReturn(accessToken); - when(accessToken.getRealmAccess().getRoles()).thenReturn(Sets.newLinkedHashSet("technical")); + when(token.getToken()).thenReturn(accessToken); + when(accessToken.getClaims()) + .thenReturn( + Maps.newHashMap( + "realm_access", Maps.newHashMap("roles", Lists.newArrayList("technical")))); var resolved = technicalOrSuperadminUserTenantResolver.resolve(authenticatedRequest); // then assertThat(resolved).contains(TECHNICAL_CONTEXT); @@ -50,8 +54,11 @@ void resolve_should_ResolveTechnicalTenantId_ForTechnicalUserRole() { void resolve_should_NotResolveTenantId_When_NonTechnicalUserRole() { // given when(authenticatedRequest.getUserPrincipal()).thenReturn(token); - when(token.getAccount().getKeycloakSecurityContext().getToken()).thenReturn(accessToken); - when(accessToken.getRealmAccess().getRoles()).thenReturn(Sets.newLinkedHashSet("another-role")); + when(token.getToken()).thenReturn(accessToken); + when(accessToken.getClaims()) + .thenReturn( + Maps.newHashMap( + "realm_access", Maps.newHashMap("roles", Lists.newArrayList("non-technical")))); var resolved = technicalOrSuperadminUserTenantResolver.resolve(authenticatedRequest); // then assertThat(resolved).isEmpty(); From f7d2830215c483aaf49475740fcaf6e65df8308d Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 10 Jan 2025 08:25:48 +0100 Subject: [PATCH 41/47] fix: replace KeycloakAuthenticationToken with JwtAuthenticationToken --- .../keycloak/config/KeycloakConfig.java | 30 ++++++++++++------- .../RoleAuthorizationAuthorityMapperTest.java | 28 ++++------------- .../api/tenant/TenantResolverServiceTest.java | 11 ++----- 3 files changed, 27 insertions(+), 42 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java index ff4e0c142..53e5ed84d 100644 --- a/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/adapters/keycloak/config/KeycloakConfig.java @@ -2,17 +2,20 @@ import static java.util.Objects.nonNull; +import com.google.common.collect.Lists; import de.caritas.cob.userservice.api.exception.keycloak.KeycloakException; import de.caritas.cob.userservice.api.helper.AuthenticatedUser; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; +import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import lombok.Data; import org.hibernate.validator.constraints.URL; import org.keycloak.adapters.KeycloakConfigResolver; import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.KeycloakBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -22,6 +25,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.validation.annotation.Validated; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.WebApplicationContext; @@ -37,10 +42,15 @@ RestTemplate keycloakRestTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder.build(); } - @Bean - @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) - KeycloakAuthenticationToken keycloakAuthenticationToken(HttpServletRequest request) { - return (KeycloakAuthenticationToken) request.getUserPrincipal(); + public Collection extractRealmRoles(Jwt jwt) { + Map realmAccess = (Map) jwt.getClaims().get("realm_access"); + if (realmAccess != null) { + var roles = (List) realmAccess.get("roles"); + if (roles != null) { + return roles; + } + } + return Lists.newArrayList(); } @Bean @@ -50,17 +60,17 @@ AuthenticatedUser authenticatedUser(HttpServletRequest request) { var authenticatedUser = new AuthenticatedUser(); if (nonNull(userPrincipal)) { - var authToken = (KeycloakAuthenticationToken) userPrincipal; - var securityContext = authToken.getAccount().getKeycloakSecurityContext(); - var claimMap = securityContext.getToken().getOtherClaims(); + var authToken = (JwtAuthenticationToken) userPrincipal; + var token = authToken.getToken(); // Extract the JWT token from the authentication token + var claimMap = token.getClaims(); // Retrieve claims from the JWT token try { if (claimMap.containsKey("username")) { authenticatedUser.setUsername(claimMap.get("username").toString()); } authenticatedUser.setUserId(claimMap.get("userId").toString()); - authenticatedUser.setAccessToken(securityContext.getTokenString()); - authenticatedUser.setRoles(securityContext.getToken().getRealmAccess().getRoles()); + authenticatedUser.setAccessToken(token.getTokenValue()); + authenticatedUser.setRoles(extractRealmRoles(token).stream().collect(Collectors.toSet())); } catch (Exception exception) { throw new KeycloakException("Keycloak data missing.", exception); } diff --git a/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java b/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java index 91d52c4cd..d0e158d54 100644 --- a/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/config/auth/RoleAuthorizationAuthorityMapperTest.java @@ -1,47 +1,29 @@ package de.caritas.cob.userservice.api.config.auth; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.mockito.Mockito.mock; +import static org.assertj.core.api.Assertions.assertThat; -import java.security.Principal; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.keycloak.adapters.RefreshableKeycloakSecurityContext; -import org.keycloak.adapters.spi.KeycloakAccount; -import org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount; -import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; @ExtendWith(MockitoExtension.class) -public class RoleAuthorizationAuthorityMapperTest { +class RoleAuthorizationAuthorityMapperTest { - private final KeycloakAuthenticationProvider provider = new KeycloakAuthenticationProvider(); private final Set roles = Stream.of(UserRole.values()).map(UserRole::getValue).collect(Collectors.toSet()); @Test - public void roleAuthorizationAuthorityMapper_Should_GrantCorrectAuthorities() { - - Principal principal = mock(Principal.class); - RefreshableKeycloakSecurityContext securityContext = - mock(RefreshableKeycloakSecurityContext.class); - KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext); - - KeycloakAuthenticationToken token = new KeycloakAuthenticationToken(account, false); + void roleAuthorizationAuthorityMapper_Should_GrantCorrectAuthorities() { RoleAuthorizationAuthorityMapper roleAuthorizationAuthorityMapper = new RoleAuthorizationAuthorityMapper(); - provider.setGrantedAuthoritiesMapper(roleAuthorizationAuthorityMapper); - Authentication result = provider.authenticate(token); + var result = roleAuthorizationAuthorityMapper.mapAuthorities(roles); Set expectedGrantendAuthorities = new HashSet<>(); roles.forEach( @@ -52,6 +34,6 @@ public void roleAuthorizationAuthorityMapper_Should_GrantCorrectAuthorities() { .collect(Collectors.toSet())); }); - assertThat(expectedGrantendAuthorities, containsInAnyOrder(result.getAuthorities().toArray())); + assertThat(expectedGrantendAuthorities).isEqualTo(result); } } diff --git a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java index 258e0a130..f9c8b1f74 100644 --- a/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java +++ b/src/test/java/de/caritas/cob/userservice/api/tenant/TenantResolverServiceTest.java @@ -6,15 +6,13 @@ import jakarta.servlet.http.HttpServletRequest; import java.util.Optional; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; @ExtendWith(MockitoExtension.class) class TenantResolverServiceTest { @@ -29,7 +27,7 @@ class TenantResolverServiceTest { @Mock HttpServletRequest nonAuthenticatedRequest; - @Mock KeycloakAuthenticationToken token; + @Mock JwtAuthenticationToken token; @InjectMocks TenantResolverService tenantResolverService; @@ -40,11 +38,6 @@ class TenantResolverServiceTest { @Mock private MultitenancyWithSingleDomainTenantResolver multitenancyWithSingleDomainTenantResolver; - @BeforeEach - public void setUp() { - token = Mockito.mock(KeycloakAuthenticationToken.class, Mockito.RETURNS_DEEP_STUBS); - } - @Test void resolve_Should_ResolveFromAccessTokenForAuthenticatedUser_And_PassValidation() { // given From fbd04b286eabf7d444ebc14690c334d86e2fabd6 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 17 Jan 2025 13:47:32 +0100 Subject: [PATCH 42/47] fix: change order of filters --- .../cob/userservice/api/config/auth/SecurityConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index 5b3ed39be..d3d7e00b0 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -21,8 +21,8 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @@ -251,7 +251,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { httpSecurity = - httpSecurity.addFilterAfter(this.tenantFilter, BearerTokenAuthenticationFilter.class); + httpSecurity.addFilterAfter(this.tenantFilter, SecurityContextHolderFilter.class); } return httpSecurity; } From b254151a8bfff2f9b8547d97bc9e0a89960f0080 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 17 Jan 2025 15:23:36 +0100 Subject: [PATCH 43/47] fix: change order of filters --- .../cob/userservice/api/config/auth/SecurityConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index d3d7e00b0..ecb67ebc4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -22,6 +22,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -251,7 +252,7 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { private HttpSecurity enableTenantFilterIfMultitenancyEnabled(HttpSecurity httpSecurity) { if (multitenancy) { httpSecurity = - httpSecurity.addFilterAfter(this.tenantFilter, SecurityContextHolderFilter.class); + httpSecurity.addFilterAfter(this.tenantFilter, FilterSecurityInterceptor.class); } return httpSecurity; } From 99085d430480c84025cdcf43c11660a7d6c063a0 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 17 Jan 2025 15:27:15 +0100 Subject: [PATCH 44/47] fix: change order of filters --- .../caritas/cob/userservice/api/config/auth/SecurityConfig.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java index ecb67ebc4..8343bb4d4 100644 --- a/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/userservice/api/config/auth/SecurityConfig.java @@ -23,7 +23,6 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; -import org.springframework.security.web.context.SecurityContextHolderFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; From 1623778b0ec40b271cf6a60cc826312759e26a56 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Fri, 17 Jan 2025 20:06:22 +0100 Subject: [PATCH 45/47] fix: attempt to fix invalid session table name generated by hibernate which prevents login of consultants --- .../api/port/out/SessionRepository.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java b/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java index 44dc9dbd7..f180bcaab 100644 --- a/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java +++ b/src/main/java/de/caritas/cob/userservice/api/port/out/SessionRepository.java @@ -201,18 +201,12 @@ Page findByConsultingTypeIdInAndRegistrationTypeAndStatusOrderByCreateD List findByStatusInAndRegistrationType( Set status, RegistrationType registrationType); - /** - * Count session by consultant, status and registration type. - * - * @param consultant the {@link Consultant} to search for - * @param sessionStatusList a {@link List} of {@link SessionStatus} to search for - * @param registrationType the {@link RegistrationType} to search for - * @return the count - */ - Long countByConsultantAndStatusInAndRegistrationType( - Consultant consultant, - List sessionStatusList, - RegistrationType registrationType); + @Query( + "SELECT COUNT(s) FROM Session s WHERE s.consultant = :consultant AND s.status IN :statuses AND s.registrationType = :registrationType") + long countByConsultantAndStatusInAndRegistrationType( + @Param("consultant") Consultant consultant, + @Param("statuses") List statuses, + @Param("registrationType") RegistrationType registrationType); /** * Find one session by assigned consultant and user. From df86b3cc057e0ab6142a4c10c67fa71060028208 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 22 Jan 2025 14:52:09 +0100 Subject: [PATCH 46/47] fix: attempt to fix invalid session table name generated by hibernate which prevents login of consultants --- src/main/resources/application.properties | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8ed84ee7b..0627955e2 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -8,6 +8,7 @@ spring.jpa.hibernate.ddl-auto=none spring.data.jpa.repositories.bootstrap-mode=default spring.main.banner-mode=off spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl # General app settings server.port=8080 From b384afb09d4b88433a41213afae8575ebfa80f19 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 22 Jan 2025 15:34:48 +0100 Subject: [PATCH 47/47] fix: attempt to fix invalid session table name generated by hibernate which prevents login of consultants --- .../de/caritas/cob/userservice/api/model/Consultant.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java index 8ec7bf8c2..4053b1e3b 100644 --- a/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java +++ b/src/main/java/de/caritas/cob/userservice/api/model/Consultant.java @@ -173,7 +173,11 @@ public class Consultant implements TenantAware, NotificationsAware { private Boolean walkThroughEnabled; @Enumerated(EnumType.STRING) - @Column(length = 2, nullable = false, columnDefinition = "varchar(2) default 'de'") + @Column( + length = 2, + nullable = false, + name = "language_code", + columnDefinition = "varchar(2) default 'de'") private LanguageCode languageCode; @Column(name = "terms_and_conditions_confirmation", columnDefinition = "datetime")