From 84c2914242c26af38fe34f6d3a4208d30bc7ccef Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 6 Nov 2023 11:09:36 +0100 Subject: [PATCH 001/111] fix: config http headers --- pom.xml | 8 ++++---- .../auth/security/DefaultSecurityContext.java | 6 +++++- .../security/OpenIDConnectSecurityContext.java | 16 ++++++++++------ 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index e20d36d4..d954a0ee 100644 --- a/pom.xml +++ b/pom.xml @@ -4,12 +4,12 @@ org.springframework.boot spring-boot-starter-parent - 2.7.13 + 2.7.17 fr.insee.survey platine-management - 1.0.27 + 1.0.30-rc platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI @@ -17,10 +17,10 @@ 1.6.8 3.1.0 2.9.7 - 4.0.0 + 5.0.0 1.0.2 1.15.3 - 20230227 + 20231013 diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index c257101c..4b2de4c8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -31,7 +31,11 @@ protected SecurityFilterChain configure(HttpSecurity http) throws Exception { http.sessionManagement().disable(); http.cors(withDefaults()) .csrf().disable() - .authorizeRequests() + .headers() + .xssProtection().disable() + .frameOptions().sameOrigin().httpStrictTransportSecurity().disable() + .contentSecurityPolicy("default-src 'none'"); + http.authorizeRequests() .antMatchers("/csrf", "/", "/webjars/**", "/swagger-resources/**").permitAll() .antMatchers("/environnement").permitAll()// PublicResources .antMatchers(Constants.API_HEALTHCHECK).permitAll() diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index d6463477..ad8d6adf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -23,10 +23,10 @@ @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled = true) +@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) @ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = "OIDC") @Slf4j -public class OpenIDConnectSecurityContext { +public class OpenIDConnectSecurityContext { @Autowired ApplicationConfig config; @@ -34,10 +34,13 @@ public class OpenIDConnectSecurityContext { @Bean protected SecurityFilterChain configure(HttpSecurity http) throws Exception { http.sessionManagement().disable(); - http.cors(withDefaults()) .csrf().disable() - .authorizeRequests() + .headers() + .xssProtection().disable() + .frameOptions().sameOrigin().httpStrictTransportSecurity().disable() + .contentSecurityPolicy("default-src 'none'"); + http.authorizeRequests() .antMatchers("/csrf", "/", "/webjars/**", "/swagger-resources/**").permitAll() .antMatchers("/environnement").permitAll()//PublicResources .antMatchers(Constants.API_HEALTHCHECK).permitAll() @@ -57,10 +60,11 @@ protected SecurityFilterChain configure(HttpSecurity http) throws Exception { @Bean public UserProvider getUserProvider() { return auth -> { - if ("anonymousUser".equals(auth.getPrincipal())) return null; //init request, or request without authentication + if ("anonymousUser".equals(auth.getPrincipal())) + return null; //init request, or request without authentication final Jwt jwt = (Jwt) auth.getPrincipal(); List tryRoles = jwt.getClaimAsStringList(config.getRoleClaim()); - String tryId=jwt.getClaimAsString(config.getIdClaim()); + String tryId = jwt.getClaimAsString(config.getIdClaim()); return new User(tryId, tryRoles); }; } From 2b5775aad559b7b82972a4d432ae9169d7d0a3fb Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 10 Nov 2023 15:13:03 +0100 Subject: [PATCH 002/111] build: wip: bump to spring boot 3 --- pom.xml | 23 ++-- .../config/ApplicationConfig.java | 15 ++- .../config/LogInterceptor.java | 6 +- .../auth/security/DefaultSecurityContext.java | 81 ++++++++------ .../security/GrantedAuthorityConverter.java | 39 +++++++ .../OpenIDConnectSecurityContext.java | 104 ++++++++++++------ .../security/PublicSecurityFilterChain.java | 51 +++++++++ .../config/auth/user/User.java | 6 +- .../constants/Constants.java | 1 + .../contact/domain/Address.java | 10 +- .../contact/domain/Contact.java | 12 +- .../contact/domain/ContactEvent.java | 25 +---- .../controller/CampaignController.java | 51 ++++----- .../metadata/domain/Campaign.java | 13 +-- .../metadata/domain/CampaignEvent.java | 8 +- .../metadata/domain/Owner.java | 6 +- .../metadata/domain/Partitioning.java | 6 +- .../metadata/domain/Source.java | 2 +- .../metadata/domain/Support.java | 6 +- .../metadata/domain/Survey.java | 10 +- .../metadata/service/CampaignService.java | 15 ++- .../service/impl/CampaignServiceImpl.java | 25 ++--- .../CheckHabilitationController.java | 9 +- .../query/controller/MoogController.java | 44 ++++---- .../service/CheckHabilitationService.java | 2 - .../query/service/MoogService.java | 11 +- .../impl/CheckHabilitationServiceImpl.java | 4 - .../query/service/impl/MoogServiceImpl.java | 28 ++--- .../questioning/domain/EventOrder.java | 5 +- .../questioning/domain/Operator.java | 6 +- .../questioning/domain/OperatorService.java | 13 +-- .../questioning/domain/Questioning.java | 19 +--- .../domain/QuestioningAccreditation.java | 12 +- .../questioning/domain/QuestioningEvent.java | 17 +-- .../questioning/domain/SurveyUnit.java | 14 +-- .../questioning/domain/SurveyUnitAddress.java | 9 +- .../questioning/domain/Upload.java | 3 +- .../dto/QuestioningAccreditationDto.java | 8 +- .../user/domain/SourceAccreditation.java | 9 +- .../user/domain/User.java | 2 +- .../user/domain/UserEvent.java | 10 +- .../user/dto/SourceAccreditationDto.java | 2 - .../util/Dataloader.java | 67 +++-------- .../util/DataloaderPoc.java | 68 +++--------- .../view/domain/View.java | 6 +- .../view/repository/ViewRepository.java | 9 +- src/main/resources/application.properties | 2 + ...acollectionManagementApplicationTests.java | 2 + .../config/DataloaderTest.java | 61 +++------- .../controller/ContactControllerTest.java | 41 ++++--- .../MyQuestioningsControllerTest.java | 24 ++-- src/test/resources/application.properties | 5 +- 52 files changed, 476 insertions(+), 551 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/GrantedAuthorityConverter.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java diff --git a/pom.xml b/pom.xml index d60ae851..aac3ce54 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.17 + 3.1.5 fr.insee.survey @@ -14,9 +14,7 @@ REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI 17 - 1.6.8 3.1.0 - 2.9.7 5.0.0 1.0.2 1.15.3 @@ -58,14 +56,15 @@ org.springdoc - springdoc-openapi-ui - ${springdoc-version} + springdoc-openapi-starter-webmvc-ui + 2.2.0 - org.springdoc - springdoc-openapi-data-rest - ${springdoc-version} + jakarta.ws.rs + jakarta.ws.rs-api + 3.1.0 + org.postgresql postgresql @@ -89,12 +88,7 @@ json ${orgjson-version} - - - com.vladmihalcea - hibernate-types-52 - ${vladmihalcea-version} - + @@ -146,7 +140,6 @@ org.springframework.security spring-security-oauth2-jose - 5.7.2 diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java index da20d6ff..f7c1dee6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java @@ -1,13 +1,12 @@ package fr.insee.survey.datacollectionmanagement.config; -import java.util.List; -import java.util.Optional; - +import lombok.Getter; +import lombok.Setter; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; -import lombok.Getter; -import lombok.Setter; +import java.util.List; +import java.util.Optional; @Configuration @Getter @@ -17,10 +16,10 @@ public class ApplicationConfig { //AUTHENTICATION @Value("${jwt.role-claim}") private String roleClaim; + @Value("${jwt.id-claim}") private String idClaim; - @Value("#{'${fr.insee.datacollectionmanagement.roles.admin.role}'.split(',')}") private List roleAdmin; @@ -41,9 +40,13 @@ public class ApplicationConfig { @Value("${fr.insee.datacollectionmanagement.auth.realm}") private String keycloakRealm; + @Value("${fr.insee.datacollectionmanagement.auth.server-url}") private String keyCloakUrl; @Value("${fr.insee.datacollectionmanagement.api.questioning.url}") private String questioningUrl; + + @Value("#{'${fr.insee.datacollectionmanagement.public.urls}'.split(',')}") + List publicUrls; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java index 2c20c9e9..bb314d5f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java @@ -3,20 +3,18 @@ import fr.insee.survey.datacollectionmanagement.config.auth.user.User; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.logging.log4j.ThreadContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.UUID; @Component diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 4b2de4c8..8a0fc27c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -1,57 +1,74 @@ package fr.insee.survey.datacollectionmanagement.config.auth.security; -import static org.springframework.security.config.Customizer.withDefaults; - -import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.config.auth.user.User; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.Customizer; +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.web.SecurityFilterChain; - -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; -import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; +import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled = false, prePostEnabled = true) +@EnableMethodSecurity @ConditionalOnMissingBean(OpenIDConnectSecurityContext.class) +@AllArgsConstructor public class DefaultSecurityContext { + private final PublicSecurityFilterChain publicSecurityFilterChainConfiguration; + @Autowired ApplicationConfig config; - + /** + * Configure spring security filter chain when no authentication + * @param http Http Security Object + * @return the spring security filter + * @throws Exception + */ @Bean - protected SecurityFilterChain configure(HttpSecurity http) throws Exception { - http.sessionManagement().disable(); - http.cors(withDefaults()) - .csrf().disable() - .headers() - .xssProtection().disable() - .frameOptions().sameOrigin().httpStrictTransportSecurity().disable() - .contentSecurityPolicy("default-src 'none'"); - http.authorizeRequests() - .antMatchers("/csrf", "/", "/webjars/**", "/swagger-resources/**").permitAll() - .antMatchers("/environnement").permitAll()// PublicResources - .antMatchers(Constants.API_HEALTHCHECK).permitAll() - .antMatchers("/actuator/**").permitAll() - .antMatchers("/swagger-ui/*").permitAll() - .antMatchers("/v3/api-docs/swagger-config", "/v3/api-docs").permitAll() - .antMatchers("/openapi.json").permitAll() - .antMatchers(HttpMethod.OPTIONS).permitAll() - .anyRequest().permitAll(); - - return http.build(); + @Order(2) + SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + return http + .securityMatcher("/**") + .csrf(csrfConfig -> csrfConfig.disable()) + .cors(Customizer.withDefaults()) + .headers(headers -> headers + .xssProtection(xssConfig -> xssConfig.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED)) + .contentSecurityPolicy(cspConfig -> cspConfig + .policyDirectives("default-src 'none'") + ) + .referrerPolicy(referrerPolicy -> + referrerPolicy + .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN) + )) + .anonymous(anonymousConfig -> anonymousConfig + .authorities("ROLE_ADMIN")) + .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()) + .build(); + } + @Bean + @Order(1) + SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { + System.out.println(publicUrls()); + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); } - @Bean public UserProvider getUserProvider() { return auth -> new User(); } + private String[] publicUrls(){ + return (String[]) config.getPublicUrls().toArray(); + + } + } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/GrantedAuthorityConverter.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/GrantedAuthorityConverter.java new file mode 100644 index 00000000..87e2b6ff --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/GrantedAuthorityConverter.java @@ -0,0 +1,39 @@ +package fr.insee.survey.datacollectionmanagement.config.auth.security; + +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import lombok.AllArgsConstructor; +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; + +import java.util.*; +import java.util.stream.Collectors; + +@AllArgsConstructor +public class GrantedAuthorityConverter implements Converter> { + + ApplicationConfig applicationConfig; + + @Override + public Collection convert(Jwt jwt) { + Map claims = jwt.getClaims(); + List roles = (List) claims.get(applicationConfig.getRoleClaim()); + List authorizedRoles = new ArrayList<>(); + authorizedRoles.addAll(applicationConfig.getRoleAdmin()); + authorizedRoles.addAll(applicationConfig.getRoleRespondent()); + authorizedRoles.addAll(applicationConfig.getRoleInternalUser()); + authorizedRoles.addAll(applicationConfig.getRoleWebClient()); + + return roles.stream() + .map(role -> { + if (authorizedRoles.contains(role)) { + return new SimpleGrantedAuthority(role); + } + return null; + }) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(ArrayList::new)); + } +} + diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index ad8d6adf..e34a4e78 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -1,60 +1,86 @@ package fr.insee.survey.datacollectionmanagement.config.auth.security; -import static org.springframework.security.config.Customizer.withDefaults; - -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.config.auth.user.User; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; +import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter; -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; -import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; -import lombok.extern.slf4j.Slf4j; +import java.util.Collection; +import java.util.List; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) @ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = "OIDC") @Slf4j +@AllArgsConstructor public class OpenIDConnectSecurityContext { + + private final PublicSecurityFilterChain publicSecurityFilterChainConfiguration; + @Autowired ApplicationConfig config; @Bean + @Order(2) protected SecurityFilterChain configure(HttpSecurity http) throws Exception { - http.sessionManagement().disable(); - http.cors(withDefaults()) - .csrf().disable() - .headers() - .xssProtection().disable() - .frameOptions().sameOrigin().httpStrictTransportSecurity().disable() - .contentSecurityPolicy("default-src 'none'"); - http.authorizeRequests() - .antMatchers("/csrf", "/", "/webjars/**", "/swagger-resources/**").permitAll() - .antMatchers("/environnement").permitAll()//PublicResources - .antMatchers(Constants.API_HEALTHCHECK).permitAll() - .antMatchers("/actuator/**").permitAll() - .antMatchers("/swagger-ui/*").permitAll() - .antMatchers("/v3/api-docs/swagger-config", "/v3/api-docs").permitAll() - .antMatchers("/openapi.json").permitAll() - .antMatchers(HttpMethod.OPTIONS).permitAll() - .anyRequest().authenticated() - .and() - .oauth2ResourceServer() - .jwt(); - return http.build(); + return http + .securityMatcher("/**") + .csrf(AbstractHttpConfigurer::disable) + .cors(Customizer.withDefaults()) + .headers(headers -> headers + .xssProtection(xssConfig -> xssConfig.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED)) + .contentSecurityPolicy(cspConfig -> cspConfig + .policyDirectives("default-src 'none'") + ) + .referrerPolicy(referrerPolicy -> + referrerPolicy + .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN) + )) + .authorizeHttpRequests(configurer -> configurer + .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() + .requestMatchers(HttpMethod.GET, Constants.API_HEALTHCHECK).permitAll() + // actuator (actuator metrics are disabled by default) + .requestMatchers(HttpMethod.GET, Constants.ACTUATOR).permitAll() + .anyRequest() + .authenticated() + ) + .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .oauth2ResourceServer(oauth2 -> oauth2 + .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter(config))) + ) + .build(); + + } + + @Bean + @Order(1) + SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { + String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token"; + String authorizedConnectionHost = config.getAuthType().equals("OIDC") ? + " " + tokenUrl : ""; + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); } @Bean @@ -69,5 +95,21 @@ public UserProvider getUserProvider() { }; } + private String[] publicUrls() { + return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**", + "/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"}; + } + + @Bean + JwtAuthenticationConverter jwtAuthenticationConverter(ApplicationConfig applicationConfig) { + JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); + jwtAuthenticationConverter.setPrincipalClaimName("preferred_username"); + jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter(applicationConfig)); + return jwtAuthenticationConverter; + } + + Converter> jwtGrantedAuthoritiesConverter(ApplicationConfig applicationConfig) { + return new GrantedAuthorityConverter(applicationConfig); + } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java new file mode 100644 index 00000000..953448d1 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java @@ -0,0 +1,51 @@ +package fr.insee.survey.datacollectionmanagement.config.auth.security; + +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; +import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter; + +@Configuration +public class PublicSecurityFilterChain { + + @Autowired + ApplicationConfig config; + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception { + return buildSecurityPublicFilterChain(http, publicUrls, ""); + } + + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception { + return http + .securityMatcher(publicUrls) + .csrf(AbstractHttpConfigurer::disable) + .cors(Customizer.withDefaults()) + .headers(headers -> headers + .xssProtection(xssConfig -> xssConfig.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED)) + .contentSecurityPolicy(cspConfig -> cspConfig + .policyDirectives("default-src 'none'; " + + "connect-src 'self' " + authorizedConnectionHost + "; " + + "img-src 'self' data:; " + + "style-src 'self'; " + + "script-src 'self' 'unsafe-inline'") + ) + .referrerPolicy(referrerPolicy -> + referrerPolicy + .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN) + )) + .authorizeHttpRequests(auth -> auth + .requestMatchers(HttpMethod.OPTIONS).permitAll() + .requestMatchers(publicUrls).permitAll() + .anyRequest() + .authenticated() + ) + .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .build(); + } +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java index 4752b661..2964a239 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java @@ -1,11 +1,11 @@ package fr.insee.survey.datacollectionmanagement.config.auth.user; -import java.util.Collection; -import java.util.List; - import org.json.JSONArray; import org.springframework.security.core.GrantedAuthority; +import java.util.Collection; +import java.util.List; + public class User { private JSONArray roles; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 0d022440..70d0f510 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -99,5 +99,6 @@ private Constants() { public static final String REVIEWER = "reviewer"; public static final String API_HEALTHCHECK = "/api/healthcheck"; + public static final String ACTUATOR = "/actuator/**"; } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java index d8216ac8..4ad81cc0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java @@ -1,16 +1,18 @@ package fr.insee.survey.datacollectionmanagement.contact.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; import lombok.Data; @Entity @Data public class Address { - @Id @GeneratedValue + @Id + @GeneratedValue private Long id; private String streetNumber; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java index 34e6bc1e..0580d58e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java @@ -2,18 +2,8 @@ import java.util.Set; -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.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.*; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index 46b2280e..e07f4573 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -1,29 +1,16 @@ package fr.insee.survey.datacollectionmanagement.contact.domain; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; - import com.fasterxml.jackson.databind.JsonNode; -import com.vladmihalcea.hibernate.type.json.JsonBinaryType; +import jakarta.persistence.*; +import lombok.*; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.ToString; +import java.util.Date; @Entity @Data @NoArgsConstructor -@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) public class ContactEvent { public enum ContactEventType { @@ -42,7 +29,7 @@ public enum ContactEventType { @ToString.Exclude private Contact contact; - @Type(type = "jsonb") + @JdbcTypeCode(SqlTypes.JSON) @Column(columnDefinition = "jsonb") private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 4e6bf935..2262438c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -1,43 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import fr.insee.survey.datacollectionmanagement.metadata.dto.OnGoingDto; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Upload; -import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignDto; +import fr.insee.survey.datacollectionmanagement.metadata.dto.OnGoingDto; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Upload; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -46,8 +19,24 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; -import org.webjars.NotFoundException; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java index e7ec998e..3c854e30 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java @@ -2,19 +2,10 @@ import java.util.Set; -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.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; + import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import jakarta.persistence.*; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java index 5a7e5967..29a60f67 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java @@ -2,11 +2,11 @@ import java.util.Date; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java index 4a17dc5d..26311e66 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java @@ -2,10 +2,10 @@ import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java index 7b2dcb68..3549613a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java @@ -2,12 +2,8 @@ import java.util.Date; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.*; import lombok.Data; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java index 931661aa..1808a17a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java @@ -2,9 +2,9 @@ import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; +import jakarta.persistence.*; import lombok.*; -import javax.persistence.*; import java.util.Set; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java index a4bd9438..7918fbaa 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java @@ -2,10 +2,10 @@ import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java index 63c0d8ca..eaf03544 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java @@ -2,16 +2,8 @@ import java.util.Set; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import jakarta.persistence.*; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java index aff3fdb9..3f6c04de 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java @@ -1,17 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; +import jakarta.ws.rs.NotFoundException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; -import org.webjars.NotFoundException; +import java.util.Collection; +import java.util.List; +import java.util.Optional; @Service public interface CampaignService { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java index 9b0b0047..51d7aaa9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java @@ -1,16 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - +import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; +import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; +import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; +import jakarta.ws.rs.NotFoundException; +import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -18,13 +15,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; -import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; -import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; -import lombok.extern.slf4j.Slf4j; -import org.webjars.NotFoundException; +import java.util.*; @Service @Slf4j diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java index 36b2eba3..e23a6868 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java @@ -1,21 +1,18 @@ package fr.insee.survey.datacollectionmanagement.query.controller; +import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; +import io.swagger.v3.oas.annotations.tags.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; -import io.swagger.v3.oas.annotations.tags.Tag; - -import javax.servlet.http.HttpServletRequest; @RestController @Tag(name = "4 - Cross domain") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java index cfa1448d..93192cfc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java @@ -1,33 +1,16 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.List; -import java.util.Map; -import java.util.Optional; - import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; -import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; -import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; -import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; import fr.insee.survey.datacollectionmanagement.query.service.MoogService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -36,7 +19,24 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; -import org.webjars.NotFoundException; +import jakarta.ws.rs.NotFoundException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java index 4e56a527..1ef55694 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java @@ -1,11 +1,9 @@ package fr.insee.survey.datacollectionmanagement.query.service; import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; -import org.apache.coyote.Response; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpServletRequest; @Service public interface CheckHabilitationService { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java index 850cae20..a01b3c91 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java @@ -1,16 +1,15 @@ package fr.insee.survey.datacollectionmanagement.query.service; -import java.util.Collection; -import java.util.List; - import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; import fr.insee.survey.datacollectionmanagement.view.domain.View; -import org.webjars.NotFoundException; +import jakarta.ws.rs.NotFoundException; +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.List; @Service public interface MoogService { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java index 6561ff6d..58c90a2a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java @@ -2,7 +2,6 @@ import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; @@ -19,11 +18,8 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.stereotype.Service; -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; @Service public class CheckHabilitationServiceImpl implements CheckHabilitationService { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java index f443ce84..aab0c030 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java @@ -1,33 +1,29 @@ package fr.insee.survey.datacollectionmanagement.query.service.impl; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; - import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; -import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; +import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.domain.MoogCampaign; +import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; import fr.insee.survey.datacollectionmanagement.query.repository.MoogRepository; import fr.insee.survey.datacollectionmanagement.query.service.MoogService; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; -import org.webjars.NotFoundException; +import jakarta.ws.rs.NotFoundException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; @Service @Slf4j @@ -147,7 +143,7 @@ public String getReadOnlyUrl(String idCampaign, String surveyUnitId) throws NotF } String msg = "0 questioning found for campaign "+idCampaign+" and survey unit "+ surveyUnitId; log.error(msg); - throw new NotFoundException(msg); + throw new NotFoundException(msg); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java index aee1dff6..35703e54 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java @@ -1,8 +1,9 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import javax.persistence.Entity; -import javax.persistence.Id; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import lombok.Data; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java index 19177c57..d73f6e17 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java @@ -1,9 +1,9 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; import lombok.Data; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java index 03f145a0..47cc3bbc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java @@ -1,16 +1,15 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; - +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; +import java.util.Set; + @Entity @Data public class OperatorService { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java index d2d91a67..fbd263be 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java @@ -1,22 +1,9 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import java.util.Set; +import jakarta.persistence.*; +import lombok.*; -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.ToString; +import java.util.Set; @Entity @Data diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java index 58508454..5e7da233 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java @@ -1,19 +1,13 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToOne; -import javax.persistence.Table; - +import jakarta.persistence.*; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; +import java.util.Date; + @Entity @Data @NoArgsConstructor diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java index 6ac4c3c4..4a79c210 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java @@ -1,22 +1,17 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import java.util.Date; - -import javax.persistence.*; - import com.fasterxml.jackson.annotation.JsonManagedReference; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; - import com.fasterxml.jackson.databind.JsonNode; -import com.vladmihalcea.hibernate.type.json.JsonBinaryType; - import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import jakarta.persistence.*; import lombok.Data; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + +import java.util.Date; @Entity @Data -@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) public class QuestioningEvent { @Id @@ -35,7 +30,7 @@ public class QuestioningEvent { @JsonManagedReference private Upload upload; - @Type(type = "jsonb") + @JdbcTypeCode(SqlTypes.JSON) @Column(columnDefinition = "jsonb") private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java index b01033a8..df63bcbf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java @@ -1,18 +1,10 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; - +import jakarta.persistence.*; import lombok.Data; +import java.util.Set; + @Entity @Data @Table(indexes = { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java index 44c819c3..c50a711b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java @@ -1,12 +1,13 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; + + @Entity @Getter @Setter diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Upload.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Upload.java index f4eb58ad..061ce594 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Upload.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Upload.java @@ -2,11 +2,10 @@ import com.fasterxml.jackson.annotation.JsonBackReference; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; +import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; -import javax.persistence.*; import java.util.List; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/QuestioningAccreditationDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/QuestioningAccreditationDto.java index 8c5b4d4f..51c7469f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/QuestioningAccreditationDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/QuestioningAccreditationDto.java @@ -1,19 +1,15 @@ package fr.insee.survey.datacollectionmanagement.questioning.dto; -import java.util.Date; - -import javax.persistence.Id; - import com.fasterxml.jackson.annotation.JsonIgnore; - import lombok.Getter; import lombok.Setter; +import java.util.Date; + @Getter @Setter public class QuestioningAccreditationDto { - @Id @JsonIgnore private Long id; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java index b268336d..541752fd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java @@ -2,15 +2,16 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToOne; + import java.util.Date; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index cb3d71ac..6bc7b2a3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -4,7 +4,7 @@ import lombok.EqualsAndHashCode; import lombok.ToString; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Set; @Entity diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index f476d497..c7152cd6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -1,18 +1,16 @@ package fr.insee.survey.datacollectionmanagement.user.domain; import com.fasterxml.jackson.databind.JsonNode; -import com.vladmihalcea.hibernate.type.json.JsonBinaryType; +import jakarta.persistence.*; import lombok.*; -import org.hibernate.annotations.Type; -import org.hibernate.annotations.TypeDef; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; -import javax.persistence.*; import java.util.Date; @Entity @Data @NoArgsConstructor -@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) public class UserEvent { public enum UserEventType { @@ -32,7 +30,7 @@ public enum UserEventType { @ToString.Exclude private User user; - @Type(type = "jsonb") + @JdbcTypeCode(SqlTypes.JSON) @Column(columnDefinition = "jsonb") private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java index 58e79bc7..64fd5ec9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java @@ -5,14 +5,12 @@ import lombok.Getter; import lombok.Setter; -import javax.persistence.Id; import java.util.Date; @Getter @Setter public class SourceAccreditationDto { - @Id @JsonIgnore private Long id; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java index bb91ff6c..65ef1336 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java @@ -1,31 +1,7 @@ package fr.insee.survey.datacollectionmanagement.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jeasy.random.EasyRandom; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; - -import com.github.javafaker.Animal; import com.github.javafaker.Faker; import com.github.javafaker.Name; - import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; @@ -34,39 +10,26 @@ import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; -import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.PartitioningRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; +import fr.insee.survey.datacollectionmanagement.metadata.domain.*; +import fr.insee.survey.datacollectionmanagement.metadata.repository.*; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; -import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Operator; -import fr.insee.survey.datacollectionmanagement.questioning.domain.OperatorService; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; -import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.OperatorRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.OperatorServiceRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningAccreditationRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningEventRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitAddressRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; +import fr.insee.survey.datacollectionmanagement.questioning.domain.*; +import fr.insee.survey.datacollectionmanagement.questioning.repository.*; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; +import jakarta.annotation.PostConstruct; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jeasy.random.EasyRandom; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.concurrent.TimeUnit; @Component public class Dataloader { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java index 17045cbe..48676367 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java @@ -1,31 +1,7 @@ package fr.insee.survey.datacollectionmanagement.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jeasy.random.EasyRandom; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; - -import com.github.javafaker.Animal; import com.github.javafaker.Faker; import com.github.javafaker.Name; - import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; @@ -34,39 +10,27 @@ import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; -import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.PartitioningRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; +import fr.insee.survey.datacollectionmanagement.metadata.domain.*; +import fr.insee.survey.datacollectionmanagement.metadata.repository.*; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; -import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Operator; -import fr.insee.survey.datacollectionmanagement.questioning.domain.OperatorService; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; -import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.OperatorRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.OperatorServiceRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningAccreditationRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningEventRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitAddressRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; +import fr.insee.survey.datacollectionmanagement.questioning.domain.*; +import fr.insee.survey.datacollectionmanagement.questioning.repository.*; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; +import jakarta.annotation.PostConstruct; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jeasy.random.EasyRandom; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.concurrent.TimeUnit; @Component @Profile("poc") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java b/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java index b46c03f4..93beb648 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java @@ -1,11 +1,7 @@ package fr.insee.survey.datacollectionmanagement.view.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Index; -import javax.persistence.Table; +import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/view/repository/ViewRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/view/repository/ViewRepository.java index d46b6587..e8d43b20 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/view/repository/ViewRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/view/repository/ViewRepository.java @@ -1,15 +1,15 @@ package fr.insee.survey.datacollectionmanagement.view.repository; -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.view.domain.View; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; -import fr.insee.survey.datacollectionmanagement.view.domain.View; +import java.util.List; @Repository -public interface ViewRepository extends PagingAndSortingRepository { +public interface ViewRepository extends PagingAndSortingRepository, JpaRepository { static final String FIND_DISTNCT_VIEW_BY_IDENTIFIER = "select " + " distinct on " @@ -40,4 +40,5 @@ public interface ViewRepository extends PagingAndSortingRepository { void deleteByIdentifier(String identifier); + } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 06cf686d..db5c520c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -79,3 +79,5 @@ S # Questioning url fr.insee.datacollectionmanagement.api.questioning.url=http://localhost:8081 +fr.insee.datacollectionmanagement.public.urls=/swagger-ui/**,/swagger-ui.html,/v3/api-docs/**,/csrf, /,/webjars/**,/swagger-resources/**,/environnement,/healthcheck,/actuator/** + diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java index 4a3992de..a6e44c20 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java @@ -2,8 +2,10 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootTest +@EnableJpaRepositories class DatacollectionManagementApplicationTests { @Test diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java index 30b17166..5f893961 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java @@ -1,31 +1,9 @@ package fr.insee.survey.datacollectionmanagement.config; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.Year; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.javafaker.Faker; - import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; @@ -33,35 +11,30 @@ import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; -import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.PartitioningRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; +import fr.insee.survey.datacollectionmanagement.metadata.domain.*; +import fr.insee.survey.datacollectionmanagement.metadata.repository.*; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; -import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; -import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningAccreditationRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningEventRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningRepository; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; +import fr.insee.survey.datacollectionmanagement.questioning.domain.*; +import fr.insee.survey.datacollectionmanagement.questioning.repository.*; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; +import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Year; +import java.util.*; +import java.util.stream.Collectors; -@Component +@Configuration @Profile("test") @Slf4j public class DataloaderTest { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index cb116e31..a6016fa9 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -1,18 +1,14 @@ package fr.insee.survey.datacollectionmanagement.contacts.controller; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.contact.domain.Address; +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; +import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; +import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; +import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; +import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -22,20 +18,21 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.contact.domain.Address; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; -import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; -import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; -import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; -import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; -import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest +@ContextConfiguration(classes = ApplicationConfig.class) @ActiveProfiles("test") public class ContactControllerTest { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java index d3217b98..b90d8ac4 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java @@ -1,32 +1,28 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.stream.Stream; - +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.query.dto.MyQuestioningDto; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import com.fasterxml.jackson.databind.ObjectMapper; - -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.dto.MyQuestioningDto; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") +@ContextConfiguration public class MyQuestioningsControllerTest { @Autowired diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 34a6a673..aeead15f 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -46,4 +46,7 @@ fr.insee.datacollectionmanagement.roles.webclient.role=webclient # Questioning url -fr.insee.datacollectionmanagement.api.questioning.url=http://localhost:8081 \ No newline at end of file +fr.insee.datacollectionmanagement.api.questioning.url=http://localhost:8081 + +spring.datasource.driverClassName=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file From 4b95df84b0987489844bb3ed929720340eaa214a Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 13 Nov 2023 09:26:54 +0100 Subject: [PATCH 003/111] Update DefaultSecurityContext.java --- .../config/auth/security/DefaultSecurityContext.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 8a0fc27c..5660eaf7 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -67,8 +67,14 @@ public UserProvider getUserProvider() { } private String[] publicUrls(){ - return (String[]) config.getPublicUrls().toArray(); + String[] str = new String[config.getPublicUrls().size()]; + for (int i = 0; i < config.getPublicUrls().size(); i++) { + str[i] = config.getPublicUrls().get(i); + } + return str; } + + } \ No newline at end of file From c89adbb95631f52533838b6c9309863193bd07de Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 11:31:15 +0100 Subject: [PATCH 004/111] fix: tests --- .gitignore | 1 + pom.xml | 15 +++--- .../contact/domain/ContactEvent.java | 1 + .../exception/NotFoundException.java | 7 +++ .../metadata/domain/Campaign.java | 14 ++--- .../metadata/domain/Partitioning.java | 7 ++- .../metadata/domain/Source.java | 4 +- .../metadata/domain/Survey.java | 13 ++--- .../query/controller/MoogController.java | 2 +- .../query/service/MoogService.java | 2 +- .../query/service/impl/MoogServiceImpl.java | 2 +- .../questioning/domain/Questioning.java | 2 +- .../domain/QuestioningAccreditation.java | 2 +- .../questioning/domain/QuestioningEvent.java | 2 +- .../user/domain/User.java | 1 + .../user/domain/UserEvent.java | 1 + .../controller/AddressControllerTest.java | 25 ++++----- .../controller/ContactControllerTest.java | 5 +- .../controller/CampaignControllerTest.java | 30 ++++++----- .../controller/SourceControllerTest.java | 32 +++++------- .../controller/SurveyControllerTest.java | 51 ++++++++----------- .../query/controller/MoogControllerTest.java | 7 +-- ...estionningAccreditationControllerTest.java | 42 +++++++-------- .../QuestionningControllerTest.java | 23 +++++---- .../QuestionningEventControllerTest.java | 28 +++++----- .../controller/SurveyUnitControllerTest.java | 27 +++++----- src/test/resources/application.properties | 4 +- src/test/resources/data.sql | 2 +- 28 files changed, 168 insertions(+), 184 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java diff --git a/.gitignore b/.gitignore index 6fea1f22..830567ce 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/**/target/ !**/src/test/**/target/ +*.log.* ### STS ### .apt_generated diff --git a/pom.xml b/pom.xml index aac3ce54..3dad39b1 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.0.29-rc + 1.1.0-rc platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI @@ -17,7 +17,6 @@ 3.1.0 5.0.0 1.0.2 - 1.15.3 20231013 @@ -104,12 +103,6 @@ - - org.testcontainers - junit-jupiter - ${testcontainers-version} - test - org.springframework.security spring-security-test @@ -119,6 +112,12 @@ org.springframework.boot spring-boot-starter-test test + + + com.vaadin.external.google + android-json + + com.h2database diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index e07f4573..834a3fcd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -22,6 +22,7 @@ public enum ContactEventType { private Long id; private Date eventDate; @NonNull + @Enumerated(EnumType.STRING) private ContactEventType type; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java new file mode 100644 index 00000000..a9abb02f --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java @@ -0,0 +1,7 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +public class NotFoundException extends Exception { + public NotFoundException(String errorMessage) { + super(errorMessage); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java index 3c854e30..819bb0d2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java @@ -1,16 +1,10 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Set; - - - import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import jakarta.persistence.*; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.ToString; +import lombok.*; + +import java.util.Set; @Entity @Data @@ -40,7 +34,7 @@ public class Campaign { @ToString.Exclude private Set partitionings; - @OneToOne + @ManyToOne private Survey survey; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java index 3549613a..53b81b38 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java @@ -1,11 +1,10 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Date; - - import jakarta.persistence.*; import lombok.Data; +import java.util.Date; + @Entity @Data @Table(indexes = { @@ -20,7 +19,7 @@ public class Partitioning { private Date closingDate; private Date returnDate; - @OneToOne + @ManyToOne private Campaign campaign; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java index 1808a17a..1da027d0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java @@ -32,11 +32,11 @@ public class Source { @ToString.Exclude private Set sourceAccreditations; - @OneToOne + @ManyToOne @NonNull private Owner owner; - @OneToOne + @ManyToOne @NonNull private Support support; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java index eaf03544..b989f3d2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java @@ -1,14 +1,9 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Set; - - import jakarta.persistence.*; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.ToString; +import lombok.*; + +import java.util.Set; @Entity @Data @@ -45,7 +40,7 @@ public class Survey { @ToString.Exclude private Set campaigns; - @OneToOne + @ManyToOne private Source source; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java index 93192cfc..059a4215 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java @@ -4,6 +4,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; @@ -19,7 +20,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java index a01b3c91..d7eeec41 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/MoogService.java @@ -1,11 +1,11 @@ package fr.insee.survey.datacollectionmanagement.query.service; import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; import fr.insee.survey.datacollectionmanagement.view.domain.View; -import jakarta.ws.rs.NotFoundException; import org.springframework.stereotype.Service; import java.util.Collection; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java index aab0c030..bbf38186 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java @@ -4,6 +4,7 @@ import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; @@ -18,7 +19,6 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; -import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java index fbd263be..ab4cadba 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java @@ -32,7 +32,7 @@ public class Questioning { @ToString.Exclude private Set questioningEvents; - @OneToOne(fetch = FetchType.EAGER) + @ManyToOne(fetch = FetchType.EAGER) @EqualsAndHashCode.Exclude @ToString.Exclude @NonNull diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java index 5e7da233..7ac37774 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java @@ -27,7 +27,7 @@ public class QuestioningAccreditation { @NonNull private String idContact; - @OneToOne + @ManyToOne @EqualsAndHashCode.Exclude private Questioning questioning; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java index 4a79c210..c6936438 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java @@ -22,7 +22,7 @@ public class QuestioningEvent { @Enumerated(EnumType.STRING) private TypeQuestioningEvent type; - @OneToOne + @ManyToOne private Questioning questioning; @ManyToOne(fetch = FetchType.EAGER) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index 6bc7b2a3..dbd68e21 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -20,6 +20,7 @@ public enum UserRoleType { @Id private String identifier; + @Enumerated(EnumType.STRING) private UserRoleType role; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index c7152cd6..accf0ed5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -23,6 +23,7 @@ public enum UserEventType { private Date eventDate; @NonNull + @Enumerated(EnumType.STRING) private UserEventType type; @ManyToOne diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java index 4402285e..21c051bf 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java @@ -1,12 +1,10 @@ package fr.insee.survey.datacollectionmanagement.contacts.controller; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.contact.domain.Address; +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; +import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -16,17 +14,20 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.contact.domain.Address; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; -import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; -import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") +@ContextConfiguration public class AddressControllerTest { @Autowired diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index a6016fa9..b4de3f64 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -1,6 +1,5 @@ package fr.insee.survey.datacollectionmanagement.contacts.controller; -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; @@ -18,13 +17,12 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -32,7 +30,6 @@ @AutoConfigureMockMvc @SpringBootTest -@ContextConfiguration(classes = ApplicationConfig.class) @ActiveProfiles("test") public class ContactControllerTest { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index c8cf8d20..4ef841e2 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -17,15 +17,17 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashSet; import java.util.Optional; import java.util.Set; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -48,15 +50,7 @@ class CampaignControllerTest { @Autowired private CampaignRepository campaignRepository; - @Test - void getCampaignOk() throws Exception { - String identifier = "SOURCE12023T01"; - Optional campaign = campaignService.findById(identifier); - assertTrue(campaign.isPresent()); - String json = createJson(campaign.get(), "SOURCE12023"); - this.mockMvc.perform(get(Constants.API_CAMPAIGNS_ID, identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); - } + @Test void getCampaignNotFound() throws Exception { @@ -80,7 +74,6 @@ void putCampaignsErrorId() throws Exception { } @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) void isCampaignOnGoing() throws Exception { String identifier = "OPENED"; Campaign campaign = initOpenedCampaign(identifier); @@ -94,7 +87,6 @@ void isCampaignOnGoing() throws Exception { } @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) void isCampaignOnGoingClose() throws Exception { String identifier = "CLOSED"; Campaign campaign = initClosedCampaign(identifier); @@ -108,7 +100,6 @@ void isCampaignOnGoingClose() throws Exception { } @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) void isCampaignOnGoingFutureCampaignFalse() throws Exception { String identifier = "FUTURE"; Campaign campaign = initFutureCampaign(identifier); @@ -123,7 +114,6 @@ void isCampaignOnGoingFutureCampaignFalse() throws Exception { } @Test - @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) void isCampaignOnGoingEmptyCampaignFalse() throws Exception { String identifier = "EMPTY"; Campaign campaign = initEmptyCampaign(identifier); @@ -233,4 +223,16 @@ private String createJson(Campaign campaign, String idSurvey) throws JSONExcepti return jo.toString(); } + @Test + @Transactional + @Rollback + void getCampaignOk() throws Exception { + String identifier = "SOURCE12023T01"; + Optional campaign = campaignService.findById(identifier); + assertTrue(campaign.isPresent()); + String json = createJson(campaign.get(), "SOURCE12023"); + this.mockMvc.perform(get(Constants.API_CAMPAIGNS_ID, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); + } + } \ No newline at end of file diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java index f213c9c4..ab756410 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java @@ -1,17 +1,10 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; +import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; +import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; +import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -20,16 +13,16 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.MethodMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; -import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; -import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @@ -45,7 +38,6 @@ public class SourceControllerTest { @Autowired private SourceRepository sourceRepository; - @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) @Test public void getSourceOk() throws Exception { String identifier = "SOURCE1"; diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index 4ded9794..525d9684 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -1,35 +1,27 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; +import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; +import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; import org.json.JSONException; import org.json.JSONObject; -import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.MethodMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; -import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @@ -45,16 +37,7 @@ public class SurveyControllerTest { @Autowired private SurveyRepository surveyRepository; - @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) - @Test - public void getSurveyOk() throws Exception { - String identifier = "SOURCE12022"; - Optional survey = surveyService.findById(identifier); - assertTrue(survey.isPresent()); - String json = createJson(survey.get(), "SOURCE1"); - this.mockMvc.perform(get(Constants.API_SURVEYS_ID, identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); - } + @Test public void getSurveyNotFound() throws Exception { @@ -65,7 +48,6 @@ public void getSurveyNotFound() throws Exception { } - @DirtiesContext(methodMode = MethodMode.BEFORE_METHOD) @Test public void putSurveyCreateUpdateDelete() throws Exception { String identifier = "SURVEYPUT"; @@ -139,4 +121,13 @@ private String createJson(Survey survey, String idSource) throws JSONException { return jo.toString(); } + @Test + public void getSurveyOk() throws Exception { + String identifier = "SOURCE12022"; + Optional survey = surveyService.findById(identifier); + assertTrue(survey.isPresent()); + String json = createJson(survey.get(), "SOURCE1"); + this.mockMvc.perform(get(Constants.API_SURVEYS_ID, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); + } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java index e7ee0336..4975f7c9 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java @@ -1,14 +1,11 @@ package fr.insee.survey.datacollectionmanagement.query.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import fr.insee.survey.datacollectionmanagement.query.service.MoogService; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; @@ -39,7 +36,7 @@ public void getMoogReadOnlyUrl() throws Exception { @Test public void getMoogReadOnlyUrlCampaignNotFound() throws Exception { - String idCampaign= "SOURCE12023T00"; + String idCampaign= "CAMPAIGN"; String surveyUnitId= "100000000"; this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } @@ -47,7 +44,7 @@ public void getMoogReadOnlyUrlCampaignNotFound() throws Exception { @Test public void getMoogReadOnlyUrlQuestioningNotFound() throws Exception { String idCampaign= "SOURCE12023T01"; - String surveyUnitId= "10"; + String surveyUnitId= "SU"; this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java index b68255d1..0ef4b1f2 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java @@ -1,15 +1,9 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Set; -import java.util.stream.Collectors; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -19,19 +13,22 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class QuestionningAccreditationControllerTest { @Autowired @@ -42,7 +39,8 @@ public class QuestionningAccreditationControllerTest { @Test public void getQuestioningAccreditationOk() throws Exception { - String identifier = "83"; + Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); + Long identifier = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJsonQuestioningAcreditation(identifier); this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); @@ -58,7 +56,7 @@ public void getQuestioningAccreditationNotFound() throws Exception { @Test public void postAccreditationQuestioningNotFound() throws Exception { - int idQuestioning = 1000; + int idQuestioning = 10000; String idContact = "CONT1"; // create contact - status created @@ -72,7 +70,8 @@ public void postAccreditationQuestioningNotFound() throws Exception { @Test public void postAccreditationContactNotFound() throws Exception { - int idQuestioning = 12; + Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); + Long idQuestioning = q.getId(); String idContact = "CONT7500"; // create contact - status created @@ -86,7 +85,8 @@ public void postAccreditationContactNotFound() throws Exception { @Test public void postAccreditationCreateUpdate() throws Exception { - int idQuestioning = 11; + Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); + Long idQuestioning = q.getId(); String idContact = "CONT5"; // create accreditation - status created @@ -137,7 +137,7 @@ private String createJson(QuestioningAccreditation accreditation) throws JSONExc return jo.toString(); } - private String createJsonQuestioningAcreditation(String identifier) throws JSONException { + private String createJsonQuestioningAcreditation(Long identifier) throws JSONException { JSONObject jo1 = new JSONObject(); jo1.put("idContact", "CONT1"); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java index 6e2553fd..56a4816c 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java @@ -1,10 +1,8 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -13,24 +11,29 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; -import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class QuestionningControllerTest { @Autowired private MockMvc mockMvc; + @Autowired + QuestioningService questioningService; + @Test public void getQuestioningOk() throws Exception { - int id = 11; + Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); + Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJson(id).toString(); this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID, id)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); @@ -54,7 +57,7 @@ public void getQuestioningsBySurveyUnit() throws Exception { } - private JSONObject createJson(int id) throws JSONException { + private JSONObject createJson(Long id) throws JSONException { JSONObject jo = new JSONObject(); jo.put("id", id); return jo; diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java index 6606ce1f..23efccdb 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java @@ -1,10 +1,8 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -13,26 +11,32 @@ import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; -import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class QuestionningEventControllerTest { @Autowired private MockMvc mockMvc; + @Autowired + QuestioningService questioningService; + + @Test public void getQuestioningEventOk() throws Exception { - String identifier = "11"; - String json = createJsonQuestioningEvent(identifier); - this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,identifier)).andDo(print()).andExpect(status().isOk()) + Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); + Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); + String json = createJsonQuestioningEvent(id); + this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,id)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } @@ -44,7 +48,7 @@ public void getQuestioningEventNotFound() throws Exception { } - private String createJsonQuestioningEvent(String identifier) throws JSONException { + private String createJsonQuestioningEvent(Long identifier) throws JSONException { JSONObject joEventInitla = new JSONObject(); joEventInitla.put("type", "INITLA"); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java index 94f80749..cecac765 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java @@ -1,13 +1,10 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; +import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; +import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -16,20 +13,20 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; -import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; -import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class SurveyUnitControllerTest { @Autowired diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index aeead15f..5d35db12 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -49,4 +49,6 @@ fr.insee.datacollectionmanagement.roles.webclient.role=webclient fr.insee.datacollectionmanagement.api.questioning.url=http://localhost:8081 spring.datasource.driverClassName=org.h2.Driver -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect + +fr.insee.datacollectionmanagement.public.urls=/swagger-ui/**,/swagger-ui.html,/v3/api-docs/**,/csrf, /,/webjars/**,/swagger-resources/**,/environnement,/healthcheck,/actuator/** \ No newline at end of file diff --git a/src/test/resources/data.sql b/src/test/resources/data.sql index 8337aefd..9e7aea9e 100644 --- a/src/test/resources/data.sql +++ b/src/test/resources/data.sql @@ -1 +1 @@ -create domain if not exists jsonb as other; +create domain if not exists jsonb as json; From c31d3c7108a25eab6e5484a3a3aa172fe5102a1a Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 14:06:16 +0100 Subject: [PATCH 005/111] refactor: versions in pom --- pom.xml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 3dad39b1..ffd2f1aa 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,9 @@ REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI 17 + 2.2.0 3.1.0 + 3.1.0 5.0.0 1.0.2 20231013 @@ -56,12 +58,12 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 2.2.0 + ${springdoc-version} jakarta.ws.rs jakarta.ws.rs-api - 3.1.0 + ${jakarta-version} From 84a2373d4f8251f966954293763f73031719e609 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 14:12:50 +0100 Subject: [PATCH 006/111] test: add coverage with jacoco --- pom.xml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/pom.xml b/pom.xml index ffd2f1aa..a45a5e90 100644 --- a/pom.xml +++ b/pom.xml @@ -169,4 +169,36 @@ + + coverage + + + + org.jacoco + jacoco-maven-plugin + 0.8.7 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + XML + + + + + + + + + From b3586fb8b165890bf131a49effc2d5a2d4bda8f5 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 14:14:34 +0100 Subject: [PATCH 007/111] test: jacoco coverage --- pom.xml | 55 ++++++++++++++++++++++++------------------------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/pom.xml b/pom.xml index a45a5e90..617527af 100644 --- a/pom.xml +++ b/pom.xml @@ -166,39 +166,32 @@ + + org.jacoco + jacoco-maven-plugin + 0.8.7 + + + prepare-agent + + prepare-agent + + + + report + + report + + + + XML + + + + + - - coverage - - - - org.jacoco - jacoco-maven-plugin - 0.8.7 - - - prepare-agent - - prepare-agent - - - - report - - report - - - - XML - - - - - - - - From 510b89578bb4724cd64d4e88e63ff8cd69d90ca3 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 17:30:33 +0100 Subject: [PATCH 008/111] refactor: public urls --- .../auth/security/DefaultSecurityContext.java | 11 +---------- .../OpenIDConnectSecurityContext.java | 7 +------ .../security/PublicSecurityFilterChain.java | 19 ++++++++++++++----- 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 5660eaf7..3f66af99 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -58,22 +58,13 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @Bean @Order(1) SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { - System.out.println(publicUrls()); - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http); } @Bean public UserProvider getUserProvider() { return auth -> new User(); } - private String[] publicUrls(){ - String[] str = new String[config.getPublicUrls().size()]; - for (int i = 0; i < config.getPublicUrls().size(); i++) { - str[i] = config.getPublicUrls().get(i); - } - return str; - - } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index e34a4e78..1d40dbb8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -80,7 +80,7 @@ SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token"; String authorizedConnectionHost = config.getAuthType().equals("OIDC") ? " " + tokenUrl : ""; - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, authorizedConnectionHost); } @Bean @@ -95,11 +95,6 @@ public UserProvider getUserProvider() { }; } - private String[] publicUrls() { - return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**", - "/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"}; - } - @Bean JwtAuthenticationConverter jwtAuthenticationConverter(ApplicationConfig applicationConfig) { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java index 953448d1..acab51c9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java @@ -17,13 +17,13 @@ public class PublicSecurityFilterChain { @Autowired ApplicationConfig config; - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception { - return buildSecurityPublicFilterChain(http, publicUrls, ""); + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http) throws Exception { + return buildSecurityPublicFilterChain(http, ""); } - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception { + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String authorizedConnectionHost) throws Exception { return http - .securityMatcher(publicUrls) + .securityMatcher(publicUrls()) .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers @@ -41,11 +41,20 @@ SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] p )) .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.OPTIONS).permitAll() - .requestMatchers(publicUrls).permitAll() + .requestMatchers(publicUrls()).permitAll() .anyRequest() .authenticated() ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .build(); } + + private String[] publicUrls(){ + String[] str = new String[config.getPublicUrls().size()]; + for (int i = 0; i < config.getPublicUrls().size(); i++) { + str[i] = config.getPublicUrls().get(i); + } + return str; + + } } From 85c9086321a43c3858c66249cbe1030879a7fc02 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 15 Nov 2023 17:30:33 +0100 Subject: [PATCH 009/111] refactor: public urls --- pom.xml | 26 +------------------ .../auth/security/DefaultSecurityContext.java | 11 +------- .../OpenIDConnectSecurityContext.java | 7 +---- .../security/PublicSecurityFilterChain.java | 19 ++++++++++---- src/main/resources/banner.txt | 11 ++++++++ 5 files changed, 28 insertions(+), 46 deletions(-) create mode 100644 src/main/resources/banner.txt diff --git a/pom.xml b/pom.xml index 617527af..1fa47e6d 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI - 17 + 21 2.2.0 3.1.0 3.1.0 @@ -166,30 +166,6 @@ - - org.jacoco - jacoco-maven-plugin - 0.8.7 - - - prepare-agent - - prepare-agent - - - - report - - report - - - - XML - - - - - diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 5660eaf7..3f66af99 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -58,22 +58,13 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @Bean @Order(1) SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { - System.out.println(publicUrls()); - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http); } @Bean public UserProvider getUserProvider() { return auth -> new User(); } - private String[] publicUrls(){ - String[] str = new String[config.getPublicUrls().size()]; - for (int i = 0; i < config.getPublicUrls().size(); i++) { - str[i] = config.getPublicUrls().get(i); - } - return str; - - } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index e34a4e78..1d40dbb8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -80,7 +80,7 @@ SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token"; String authorizedConnectionHost = config.getAuthType().equals("OIDC") ? " " + tokenUrl : ""; - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, authorizedConnectionHost); } @Bean @@ -95,11 +95,6 @@ public UserProvider getUserProvider() { }; } - private String[] publicUrls() { - return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**", - "/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"}; - } - @Bean JwtAuthenticationConverter jwtAuthenticationConverter(ApplicationConfig applicationConfig) { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java index 953448d1..acab51c9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java @@ -17,13 +17,13 @@ public class PublicSecurityFilterChain { @Autowired ApplicationConfig config; - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception { - return buildSecurityPublicFilterChain(http, publicUrls, ""); + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http) throws Exception { + return buildSecurityPublicFilterChain(http, ""); } - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception { + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String authorizedConnectionHost) throws Exception { return http - .securityMatcher(publicUrls) + .securityMatcher(publicUrls()) .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers @@ -41,11 +41,20 @@ SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] p )) .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.OPTIONS).permitAll() - .requestMatchers(publicUrls).permitAll() + .requestMatchers(publicUrls()).permitAll() .anyRequest() .authenticated() ) .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .build(); } + + private String[] publicUrls(){ + String[] str = new String[config.getPublicUrls().size()]; + for (int i = 0; i < config.getPublicUrls().size(); i++) { + str[i] = config.getPublicUrls().get(i); + } + return str; + + } } diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt new file mode 100644 index 00000000..a17f8c69 --- /dev/null +++ b/src/main/resources/banner.txt @@ -0,0 +1,11 @@ + + + ######## ## ### ######## #### ## ## ######## + ## ## ## ## ## ## ## ### ## ## + ## ## ## ## ## ## ## #### ## ## + ######## ## ## ## ## ## ## ## ## ###### + ## ## ######### ## ## ## #### ## + ## ## ## ## ## ## ## ### ## + ## ######## ## ## ## #### ## ## ######## + + From 99fd9aeef8d610a6c497100b7b62f74da3154104 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 17 Nov 2023 13:38:25 +0100 Subject: [PATCH 010/111] fix: rollback refactor --- .../auth/security/DefaultSecurityContext.java | 10 ++++++++-- .../security/OpenIDConnectSecurityContext.java | 9 +++++++-- .../security/PublicSecurityFilterChain.java | 18 +++++------------- 3 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 3f66af99..38d04341 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -58,13 +58,19 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { @Bean @Order(1) SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http); - } + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); } @Bean public UserProvider getUserProvider() { return auth -> new User(); } + private String[] publicUrls(){ + String[] str = new String[config.getPublicUrls().size()]; + for (int i = 0; i < config.getPublicUrls().size(); i++) { + str[i] = config.getPublicUrls().get(i); + } + return str; + } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index 1d40dbb8..8ae5d996 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -80,8 +80,7 @@ SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token"; String authorizedConnectionHost = config.getAuthType().equals("OIDC") ? " " + tokenUrl : ""; - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, authorizedConnectionHost); - } + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); } @Bean public UserProvider getUserProvider() { @@ -107,4 +106,10 @@ Converter> jwtGrantedAuthoritiesConverter(Appl return new GrantedAuthorityConverter(applicationConfig); } + private String[] publicUrls() { + return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**", + "/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"}; + } + + } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java index acab51c9..7c85151e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java @@ -17,13 +17,13 @@ public class PublicSecurityFilterChain { @Autowired ApplicationConfig config; - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http) throws Exception { - return buildSecurityPublicFilterChain(http, ""); + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception { + return buildSecurityPublicFilterChain(http, publicUrls, ""); } - SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String authorizedConnectionHost) throws Exception { + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception { return http - .securityMatcher(publicUrls()) + .securityMatcher(publicUrls) .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers @@ -41,7 +41,7 @@ SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String aut )) .authorizeHttpRequests(auth -> auth .requestMatchers(HttpMethod.OPTIONS).permitAll() - .requestMatchers(publicUrls()).permitAll() + .requestMatchers(publicUrls).permitAll() .anyRequest() .authenticated() ) @@ -49,12 +49,4 @@ SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String aut .build(); } - private String[] publicUrls(){ - String[] str = new String[config.getPublicUrls().size()]; - for (int i = 0; i < config.getPublicUrls().size(); i++) { - str[i] = config.getPublicUrls().get(i); - } - return str; - - } } From 981c995a002e99528a848a7f5824feb363aff9fb Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 17 Nov 2023 13:39:59 +0100 Subject: [PATCH 011/111] ci: bump java to 21 --- .github/workflows/ci.yml | 4 ++-- .github/workflows/codeql-analysis.yml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1e5bd95..b1045841 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,11 +10,11 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: Set up JDK 17 + - name: Set up JDK 21 uses: actions/setup-java@v3 with: distribution: temurin - java-version: 17 + java-version: 21 - name: Build with Maven run: mvn -B clean package - name: Upload jar diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 2c638d81..8717b106 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -57,7 +57,7 @@ jobs: - name: Autobuild uses: actions/setup-java@v3 with: - java-version: "17" + java-version: "21" distribution: "temurin" - name: Build with Maven run: mvn -DskipTests package From 82070e6e206f137d62e607f78ebc1e1616add088 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 09:19:54 +0100 Subject: [PATCH 012/111] refactor: optimize pom, use Slf4j --- pom.xml | 18 ---- .../DatacollectionManagementApplication.java | 3 - .../config/ApplicationConfig.java | 4 +- .../config/LogInterceptor.java | 12 +-- .../config/OpenAPIConfiguration.java | 19 ++-- .../config/PropertyLogger.java | 18 ++-- .../auth/security/DefaultSecurityContext.java | 17 +--- .../OpenIDConnectSecurityContext.java | 12 +-- .../security/PublicSecurityFilterChain.java | 7 +- .../auth/user/AuthorizeMethodDecider.java | 57 +++++------ .../config/auth/user/User.java | 47 ++------- .../config/auth/user/UserToMdcFilter.java | 37 +++++++ .../constants/AuthConstants.java | 6 ++ .../contact/controller/AddressController.java | 39 ++++---- .../contact/controller/ContactController.java | 55 ++++------- .../controller/ContactEventController.java | 42 ++++---- .../controller/CampaignController.java | 9 +- .../PeriodPeriodicityController.java | 30 +++--- .../metadata/dto/CampaignDto.java | 2 + .../service/impl/CampaignServiceImpl.java | 8 +- .../CheckHabilitationController.java | 7 +- .../controller/MonitoringController.java | 36 ++++--- .../controller/MyQuestioningsController.java | 18 ++-- .../QuestioningAccreditationController.java | 39 ++++---- .../impl/CheckHabilitationServiceImpl.java | 96 +++++++------------ .../service/impl/MySurveysServiceImpl.java | 22 ++--- .../QuestioningEventController.java | 48 ++++------ .../controller/SurveyUnitController.java | 48 ++++------ .../controller/UploadController.java | 15 ++- .../service/impl/EventOrderServiceImpl.java | 11 +-- .../SourceAccreditationController.java | 6 +- .../user/controller/UserController.java | 10 +- .../util/Dataloader.java | 27 +++--- .../util/DataloaderPoc.java | 28 +++--- .../controller/CampaignControllerTest.java | 5 +- 35 files changed, 352 insertions(+), 506 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/constants/AuthConstants.java diff --git a/pom.xml b/pom.xml index 1fa47e6d..eb154aba 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,6 @@ 3.1.0 5.0.0 1.0.2 - 20231013 @@ -83,13 +82,6 @@ org.springframework.security spring-security-oauth2-client - - - org.json - json - ${orgjson-version} - - @@ -114,12 +106,6 @@ org.springframework.boot spring-boot-starter-test test - - - com.vaadin.external.google - android-json - - com.h2database @@ -138,10 +124,6 @@ io.micrometer micrometer-registry-prometheus - - org.springframework.security - spring-security-oauth2-jose - diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplication.java b/src/main/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplication.java index 83f55ab1..a52dfaf4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplication.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplication.java @@ -5,9 +5,6 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import io.swagger.v3.oas.annotations.OpenAPIDefinition; -import io.swagger.v3.oas.annotations.servers.Server; - @SpringBootApplication public class DatacollectionManagementApplication extends SpringBootServletInitializer { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java index f7c1dee6..0738f24b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java @@ -47,6 +47,6 @@ public class ApplicationConfig { @Value("${fr.insee.datacollectionmanagement.api.questioning.url}") private String questioningUrl; - @Value("#{'${fr.insee.datacollectionmanagement.public.urls}'.split(',')}") - List publicUrls; + @Value("#{'${fr.insee.datacollectionmanagement.public.urls}'}") + String[] publicUrls; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java index bb314d5f..79a83cf3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java @@ -3,11 +3,11 @@ import fr.insee.survey.datacollectionmanagement.config.auth.user.User; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.ThreadContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -18,11 +18,9 @@ import java.util.UUID; @Component +@Slf4j public class LogInterceptor implements HandlerInterceptor { - private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class); - - @Autowired ApplicationConfig applicationConfig; @@ -40,7 +38,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons switch (applicationConfig.getAuthType()) { - case "OIDC": + case AuthConstants.OIDC: Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); User currentUser = userProvider.getUser(authentication); userId=(currentUser!=null && currentUser.getId()!=null ?currentUser.getId() : "anonymous"); @@ -56,7 +54,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons ThreadContext.put("method", method); - logger.info("["+userId.toUpperCase()+"] - ["+method+"] - ["+operationPath+"]"); + log.info("["+userId.toUpperCase()+"] - ["+method+"] - ["+operationPath+"]"); return true; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java index 89265455..82f5fe3c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java @@ -1,23 +1,18 @@ package fr.insee.survey.datacollectionmanagement.config; -import java.util.Arrays; - +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.info.BuildProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.info.Info; -import io.swagger.v3.oas.models.security.OAuthFlow; -import io.swagger.v3.oas.models.security.OAuthFlows; -import io.swagger.v3.oas.models.security.Scopes; -import io.swagger.v3.oas.models.security.SecurityRequirement; -import io.swagger.v3.oas.models.security.SecurityScheme; -import io.swagger.v3.oas.models.servers.Server; +import java.util.Arrays; @Configuration @@ -36,7 +31,7 @@ public class OpenAPIConfiguration { switch(applicationConfig.getAuthType()) { - case "OIDC": + case AuthConstants.OIDC: OAuthFlows flows = new OAuthFlows(); OAuthFlow flow = new OAuthFlow(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/PropertyLogger.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/PropertyLogger.java index 8a5222e9..e7e44c8d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/PropertyLogger.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/PropertyLogger.java @@ -1,11 +1,7 @@ package fr.insee.survey.datacollectionmanagement.config; -import java.util.Arrays; -import java.util.stream.StreamSupport; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.AbstractEnvironment; @@ -14,11 +10,13 @@ import org.springframework.core.env.MutablePropertySources; import org.springframework.stereotype.Component; +import java.util.Arrays; +import java.util.stream.StreamSupport; + @Component +@Slf4j public class PropertyLogger { - private static final Logger LOGGER = LoggerFactory.getLogger(PropertyLogger.class); - private static boolean alreadyDisplayed=false; @EventListener @@ -28,7 +26,7 @@ public void handleContextRefresh(ContextRefreshedEvent event) { if (!alreadyDisplayed) { - LOGGER.info("================================ Properties ================================"); + log.info("================================ Properties ================================"); final MutablePropertySources sources = ((AbstractEnvironment) env).getPropertySources(); StreamSupport.stream(sources.spliterator(), false) .filter(ps -> ps instanceof EnumerablePropertySource) @@ -39,8 +37,8 @@ public void handleContextRefresh(ContextRefreshedEvent event) { || prop.contains("pw") || prop.contains("Password"))) .filter(prop -> prop.startsWith("fr.insee") || prop.startsWith("logging") || prop.startsWith("jwt") || prop.startsWith("spring")) .sorted() - .forEach(prop -> LOGGER.info("{}: {}", prop, env.getProperty(prop))); - LOGGER.info("==========================================================================="); + .forEach(prop -> log.info("{}: {}", prop, env.getProperty(prop))); + log.info("==========================================================================="); } alreadyDisplayed=true; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 38d04341..4088d959 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -17,6 +17,8 @@ import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter; +import java.util.Collections; + @Configuration @EnableWebSecurity @EnableMethodSecurity @@ -50,28 +52,17 @@ SecurityFilterChain filterChain(HttpSecurity http) throws Exception { referrerPolicy .policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN) )) - .anonymous(anonymousConfig -> anonymousConfig - .authorities("ROLE_ADMIN")) .authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll()) .build(); } @Bean @Order(1) SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls()); } + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, config.getPublicUrls()); } @Bean public UserProvider getUserProvider() { - return auth -> new User(); - } - - private String[] publicUrls(){ - String[] str = new String[config.getPublicUrls().size()]; - for (int i = 0; i < config.getPublicUrls().size(); i++) { - str[i] = config.getPublicUrls().get(i); - } - return str; + return auth -> new User("anonymous", Collections.emptyList()); } - } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index 8ae5d996..a7a0689c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -3,6 +3,7 @@ import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.config.auth.user.User; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import fr.insee.survey.datacollectionmanagement.constants.Constants; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -30,7 +31,7 @@ @Configuration @EnableWebSecurity -@ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = "OIDC") +@ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = AuthConstants.OIDC) @Slf4j @AllArgsConstructor public class OpenIDConnectSecurityContext { @@ -46,6 +47,7 @@ public class OpenIDConnectSecurityContext { protected SecurityFilterChain configure(HttpSecurity http) throws Exception { return http .securityMatcher("/**") + //.addFilterAfter(new UserToMdcFilter(getUserProvider(config)), AuthorizationFilter.class) .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers @@ -78,9 +80,9 @@ protected SecurityFilterChain configure(HttpSecurity http) throws Exception { @Order(1) SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { String tokenUrl = config.getKeyCloakUrl() + "/realms/" + config.getKeycloakRealm() + "/protocol/openid-connect/token"; - String authorizedConnectionHost = config.getAuthType().equals("OIDC") ? + String authorizedConnectionHost = config.getAuthType().equals(AuthConstants.OIDC) ? " " + tokenUrl : ""; - return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, publicUrls(), authorizedConnectionHost); } + return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, config.getPublicUrls(), authorizedConnectionHost); } @Bean public UserProvider getUserProvider() { @@ -106,10 +108,6 @@ Converter> jwtGrantedAuthoritiesConverter(Appl return new GrantedAuthorityConverter(applicationConfig); } - private String[] publicUrls() { - return new String[]{"/csrf", "/", "/webjars/**", "/swagger-resources/**", "/environnement", Constants.API_HEALTHCHECK, "/actuator/**", - "/swagger-ui/*", "/swagger-ui/html", "/v3/api-docs/swagger-config", "/v3/api-docs", "/openapi.json"}; - } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java index 7c85151e..048a7e54 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/PublicSecurityFilterChain.java @@ -1,12 +1,9 @@ package fr.insee.survey.datacollectionmanagement.config.auth.security; -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; @@ -15,8 +12,7 @@ @Configuration public class PublicSecurityFilterChain { - @Autowired - ApplicationConfig config; + SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls) throws Exception { return buildSecurityPublicFilterChain(http, publicUrls, ""); } @@ -24,7 +20,6 @@ SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] p SecurityFilterChain buildSecurityPublicFilterChain(HttpSecurity http, String[] publicUrls, String authorizedConnectionHost) throws Exception { return http .securityMatcher(publicUrls) - .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers .xssProtection(xssConfig -> xssConfig.headerValue(XXssProtectionHeaderWriter.HeaderValue.DISABLED)) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java index 7b011eda..12e42634 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java @@ -1,31 +1,32 @@ package fr.insee.survey.datacollectionmanagement.config.auth.user; -import org.json.JSONArray; -import org.json.JSONException; +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import lombok.extern.slf4j.Slf4j; - +import java.util.ArrayList; import java.util.List; @Component("AuthorizeMethodDecider") @Slf4j +@RequiredArgsConstructor public class AuthorizeMethodDecider { + public static final String ROLE_OFFLINE_ACCESS = "ROLE_offline_access"; + public static final String ROLE_UMA_AUTHORIZATION = "ROLE_uma_authorization"; private User noAuthUser; - - @Autowired - private UserProvider userProvider; + private final UserProvider userProvider; @Autowired ApplicationConfig config; public User getUser() { - if (config.getAuthType().equals("OIDC")) { + if (config.getAuthType().equals(AuthConstants.OIDC)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); User currentUser = userProvider.getUser(authentication); return currentUser; @@ -38,62 +39,56 @@ private User noAuthUser() { return this.noAuthUser; } - JSONArray roles = new JSONArray(); - roles.put("ROLE_offline_access"); - roles.put(config.getRoleAdmin().get(0)); - roles.put("ROLE_uma_authorization"); + List roles = new ArrayList<>(); + roles.add(ROLE_OFFLINE_ACCESS); + roles.add(config.getRoleAdmin().get(0)); + roles.add(ROLE_UMA_AUTHORIZATION); return new User("GUEST", roles); } - public boolean isInternalUser() throws JSONException { + public boolean isInternalUser() { User user = getUser(); return isInternalUser(user); } - public boolean isInternalUser(User user) throws JSONException { + public boolean isInternalUser(User user) { return (hasRole(user, config.getRoleInternalUser())); } - public boolean isAdmin() throws JSONException { + public boolean isAdmin() { User user = getUser(); return isAdmin(user); } - public boolean isAdmin(User user) throws JSONException { + public boolean isAdmin(User user) { return (hasRole(user, config.getRoleAdmin())); } - public boolean isWebClient() throws JSONException { + public boolean isWebClient() { User user = getUser(); return isWebClient(user); } - public boolean isWebClient(User user) throws JSONException { + public boolean isWebClient(User user) { return hasRole(user, config.getRoleWebClient()); } - public boolean isRespondent() throws JSONException { + public boolean isRespondent() { User user = getUser(); return isRespondent(user); } - public boolean isRespondent(User user) throws JSONException { + public boolean isRespondent(User user) { return hasRole(user, config.getRoleRespondent()); } - private boolean hasRole(User user, List role) throws JSONException { + private boolean hasRole(User user, List authorizedRoles) { Boolean hasRole = false; - JSONArray roles = user.getRoles(); - for (int i = 0; i < roles.length(); i++) { - if (role.contains(roles.getString(i))) { - hasRole = true; - log.info("role :"+roles.getString(i)+" has been found"); - } - } - return hasRole; + List userRoles = user.getRoles(); + return userRoles.stream().filter(r -> authorizedRoles.contains(r)).count() > 0; } - public String getUsername() throws JSONException { + public String getUsername() { User user = getUser(); return user.getId().toUpperCase(); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java index 2964a239..0de0dfa4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java @@ -1,50 +1,19 @@ package fr.insee.survey.datacollectionmanagement.config.auth.user; -import org.json.JSONArray; -import org.springframework.security.core.GrantedAuthority; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; -import java.util.Collection; import java.util.List; +@Getter +@Setter +@RequiredArgsConstructor public class User { - private JSONArray roles; - private String id; + private final String id; - private Collection authorities; - - public User() { - super(); - } - - public User(String id, JSONArray roles) { - this.id=id; - this.roles = roles; - } - - public User(String id, List roles) { - this.id=id; - this.roles = new JSONArray(roles); - } - - public JSONArray getRoles() { - return roles; - } - public void setRoles(JSONArray roles) { - this.roles = roles; - } - - public Collection getAuthorities() { - return authorities; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } + private final List roles; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java new file mode 100644 index 00000000..6fec89a4 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java @@ -0,0 +1,37 @@ +package fr.insee.survey.datacollectionmanagement.config.auth.user; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class UserToMdcFilter extends OncePerRequestFilter { + + private static final String USER = "user"; + + private final UserProvider userProvider; + + @Override + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain filterChain + ) throws ServletException, IOException { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + User currentUser = userProvider.getUser(authentication); + String userId = (currentUser != null && currentUser.getId() != null ? currentUser.getId() : "anonymous"); + MDC.put(USER, userId); + try { + filterChain.doFilter(request, response); + } finally { + MDC.remove(USER); + } + } + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/AuthConstants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/AuthConstants.java new file mode 100644 index 00000000..14246eb9 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/AuthConstants.java @@ -0,0 +1,6 @@ +package fr.insee.survey.datacollectionmanagement.constants; + +public class AuthConstants { + + public static final String OIDC = "OIDC"; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index d1e7db74..e3a9caee 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -1,24 +1,5 @@ package fr.insee.survey.datacollectionmanagement.contact.controller; -import java.util.List; -import java.util.Optional; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; @@ -35,16 +16,28 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") +@Slf4j public class AddressController { - static final Logger LOGGER = LoggerFactory.getLogger(AddressController.class); - @Autowired private AddressService addressService; @@ -106,12 +99,12 @@ public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); if (contact.getAddress() != null) { - LOGGER.info("Update address for the contact {} ", id); + log.info("Update address for the contact {} ", id); address.setId(contact.getAddress().getId()); addressUpdate = addressService.saveAddress(address); httpStatus = HttpStatus.OK; } else { - LOGGER.info("Create address for the contact {} ", id); + log.info("Create address for the contact {} ", id); addressUpdate = addressService.saveAddress(address); contact.setAddress(addressUpdate); contactService.saveContact(contact); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index 6fbb359b..5e2bc7a3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -1,40 +1,7 @@ package fr.insee.survey.datacollectionmanagement.contact.controller; -import java.text.ParseException; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto; import fr.insee.survey.datacollectionmanagement.contact.dto.ContactFirstLoginDto; @@ -52,6 +19,24 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.text.ParseException; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -61,8 +46,6 @@ @Slf4j public class ContactController { - static final Logger LOGGER = LoggerFactory.getLogger(ContactController.class); - @Autowired private ContactService contactService; @@ -145,7 +128,7 @@ public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse contact"); } catch (NoSuchElementException e) { - LOGGER.info("Creating contact with the identifier {}", contactDto.getIdentifier()); + log.info("Creating contact with the identifier {}", contactDto.getIdentifier()); contact = convertToEntityNewContact(contactDto); if (contactDto.getAddress() != null) contact.setAddress(addressService.convertToEntity(contactDto.getAddress())); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index bd2431ed..c38f87dd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -1,29 +1,5 @@ package fr.insee.survey.datacollectionmanagement.contact.controller; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; @@ -39,6 +15,22 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; @RestController(value = "contactEvents") @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -47,8 +39,6 @@ @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") public class ContactEventController { - static final Logger LOGGER = LoggerFactory.getLogger(ContactEventController.class); - @Autowired private ContactEventService contactEventService; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 2262438c..07a8bc2a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -19,6 +19,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -30,6 +31,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -44,6 +46,7 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j +@Validated public class CampaignController { @Autowired @@ -94,7 +97,7 @@ public ResponseEntity getCampaignsBySurvey(@PathVariable("id") String id) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey does not exist"); } return ResponseEntity.ok() - .body(survey.get().getCampaigns().stream().map(s -> convertToDto(s)).collect(Collectors.toList())); + .body(survey.get().getCampaigns().stream().map(s -> convertToDto(s)).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -128,7 +131,7 @@ public ResponseEntity getCampaign(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = CampaignDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody CampaignDto campaignDto) { + public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Valid CampaignDto campaignDto) { if (StringUtils.isBlank(campaignDto.getId()) || !campaignDto.getId().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idCampaign don't match"); } @@ -188,7 +191,7 @@ public ResponseEntity deleteCampaign(@PathVariable("id") String id) { for (Partitioning partitioning : listPartitionings) { nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); } - uploadsCamp.stream().forEach(up->uploadService.delete(up)); + uploadsCamp.forEach(up->uploadService.delete(up)); log.info("Campaign {} deleted with all its metadata children - {} questioning deleted - {} view deleted - {} uploads deleted", id, nbQuestioningDeleted, nbViewDeleted, uploadsCamp.size()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java index 530f45ba..ef90620d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java @@ -1,16 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; @@ -18,6 +7,13 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import net.minidev.json.JSONArray; +import net.minidev.json.JSONObject; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -31,13 +27,13 @@ public class PeriodPeriodicityController { @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK") }) - public ResponseEntity getPeriodicities() throws JsonProcessingException, JSONException { + public ResponseEntity getPeriodicities() { JSONArray jsonArray = new JSONArray(); for (PeriodicityEnum periodicity : PeriodicityEnum.values()) { JSONObject json = new JSONObject(); json.put("key", periodicity.name()); json.put("label", periodicity.getValue()); - jsonArray.put(json); + jsonArray.add(json); } return ResponseEntity.ok().body(jsonArray.toString()); } @@ -47,7 +43,7 @@ public ResponseEntity getPeriodicities() throws JsonProcessingException, JSON @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK") }) - public ResponseEntity getPeriods() throws JsonProcessingException, JSONException { + public ResponseEntity getPeriods() { JSONArray jsonArray = new JSONArray(); for (PeriodEnum period : PeriodEnum.values()) { @@ -55,7 +51,7 @@ public ResponseEntity getPeriods() throws JsonProcessingException, JSONExcept json.put("key", period.name()); json.put("label", period.getValue()); json.put("period",period.getPeriod().name()); - jsonArray.put(json); + jsonArray.add(json); } return ResponseEntity.ok().body(jsonArray.toString()); } @@ -65,7 +61,7 @@ public ResponseEntity getPeriods() throws JsonProcessingException, JSONExcept @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK") }) - public ResponseEntity getPeriodsOdPeriodicity(String periodicity) throws JsonProcessingException, JSONException { + public ResponseEntity getPeriodsOdPeriodicity(String periodicity) { try { PeriodicityEnum.valueOf(periodicity); JSONArray jsonArray = new JSONArray(); @@ -75,7 +71,7 @@ public ResponseEntity getPeriodsOdPeriodicity(String periodicity) throws Json json.put("key", period.name()); json.put("label", period.getValue()); json.put("period",period.getPeriod().name()); - jsonArray.put(json); + jsonArray.add(json); } } return ResponseEntity.ok().body(jsonArray.toString()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignDto.java index 41125197..67a1f4c6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignDto.java @@ -1,11 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import jakarta.validation.constraints.NotBlank; import lombok.Data; @Data public class CampaignDto { + @NotBlank private String id; private String surveyId; private int year; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java index 51d7aaa9..8902b2bb 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java @@ -8,8 +8,6 @@ import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -21,8 +19,6 @@ @Slf4j public class CampaignServiceImpl implements CampaignService { - static final Logger LOGGER = LoggerFactory.getLogger(CampaignServiceImpl.class); - @Autowired CampaignRepository campaignRepository; @@ -133,9 +129,9 @@ public boolean isCampaignOngoing(String idCampaign) throws NotFoundException { for (Partitioning part : camp.get().getPartitionings()) { if (partitioningService.isOnGoing(part, now)) { nbOnGoingParts++; - LOGGER.info("Partitiong {} of campaign {} is ongoing", part.getId(), idCampaign); + log.info("Partitiong {} of campaign {} is ongoing", part.getId(), idCampaign); } else { - LOGGER.info("Partitiong {} of campaign {} is closed", part.getId(), idCampaign); + log.info("Partitiong {} of campaign {} is closed", part.getId(), idCampaign); } } return !camp.get().getPartitionings().isEmpty() && nbOnGoingParts == camp.get().getPartitionings().size(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java index e23a6868..2f62b5c6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java @@ -4,11 +4,10 @@ import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import io.swagger.v3.oas.annotations.tags.Tag; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -18,7 +17,6 @@ @Tag(name = "4 - Cross domain") public class CheckHabilitationController { - static final Logger LOGGER = LoggerFactory.getLogger(CheckHabilitationController.class); @Autowired private CheckHabilitationService checkHabilitationService; @@ -31,7 +29,8 @@ public class CheckHabilitationController { public ResponseEntity checkHabilitation( @RequestParam(required = false) String role, @RequestParam(required = true) String id, - @RequestParam(required = true) String campaign) { + @RequestParam(required = true) String campaign, + Authentication authentication) { return checkHabilitationService.checkHabilitation(role, id,campaign); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java index ed5aa05d..d5a3ea8c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java @@ -1,17 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -22,14 +10,24 @@ import fr.insee.survey.datacollectionmanagement.query.service.MonitoringService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "5 - Moog", description = "Enpoints for moog") +@Slf4j public class MonitoringController { - static final Logger LOGGER = LoggerFactory.getLogger(MonitoringController.class); @Autowired MonitoringService monitoringService; @@ -45,33 +43,33 @@ public class MonitoringController { @GetMapping(value = "/api/moog/campaigns/{idCampaign}/monitoring/progress", produces = "application/json") public JSONCollectionWrapper getDataForProgress(@PathVariable String idCampaign) { - LOGGER.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); + log.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); return monitoringService.getProgress(idCampaign); } @GetMapping(value = "/api/moog/campaigns/{idCampaign}/monitoring/follow-up", produces = "application/json") public JSONCollectionWrapper getDataToFollowUp(@PathVariable String idCampaign) { - LOGGER.info("Request GET for following table for campaign : {}", idCampaign); + log.info("Request GET for following table for campaign : {}", idCampaign); return monitoringService.getFollowUp(idCampaign); } @GetMapping(value = "/api/temp/moog/campaigns/{idCampaign}/monitoring/progress", produces = "application/json") public JSONCollectionWrapper getDataForProgressTemp(@PathVariable String idCampaign) { - LOGGER.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); + log.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); Optional campaign = campaignService.findById(idCampaign); if (!campaign.isPresent()) { throw new NoSuchElementException("campaign does not exist"); } - LOGGER.info("{} partitionings found", campaign.get().getPartitionings().stream().map(Partitioning::getId) + log.info("{} partitionings found", campaign.get().getPartitionings().stream().map(Partitioning::getId) .collect(Collectors.toList()).size()); - campaign.get().getPartitionings().forEach(part -> LOGGER.info("{} partitionig found", part.getId())); + campaign.get().getPartitionings().forEach(part -> log.info("{} partitionig found", part.getId())); return null; } @GetMapping(value = "/api/temp/moog/campaigns/{idCampaign}/monitoring/follow-up", produces = "application/json") public JSONCollectionWrapper getDataToFollowUpTemp(@PathVariable String idCampaign) { - LOGGER.info("Request GET for following table for campaign : {}", idCampaign); + log.info("Request GET for following table for campaign : {}", idCampaign); return monitoringService.getFollowUp(idCampaign); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java index d786ac8b..41eea61b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java @@ -1,24 +1,20 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.List; - import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.query.dto.MyQuestioningDto; +import fr.insee.survey.datacollectionmanagement.query.service.MySurveysService; +import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.dto.MyQuestioningDto; -import fr.insee.survey.datacollectionmanagement.query.service.MySurveysService; -import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; @RestController @Tag(name = "4 - Cross domain") @@ -39,7 +35,7 @@ public List findById() { String idec=null; - if (config.getAuthType().equals("OIDC")) { + if (config.getAuthType().equals(AuthConstants.OIDC)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final Jwt jwt = (Jwt) authentication.getPrincipal(); idec=jwt.getClaimAsString(config.getIdClaim()).toUpperCase(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java index 468d3534..dff09631 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java @@ -1,26 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -38,16 +17,30 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") +@Slf4j public class QuestioningAccreditationController { - static final Logger LOGGER = LoggerFactory.getLogger(QuestioningAccreditationController.class); - @Autowired private QuestioningAccreditationService questioningAccreditationService; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java index 58c90a2a..e27fb9f0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java @@ -1,16 +1,15 @@ package fr.insee.survey.datacollectionmanagement.query.service.impl; import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import fr.insee.survey.datacollectionmanagement.user.domain.User; import fr.insee.survey.datacollectionmanagement.user.service.UserService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -22,21 +21,15 @@ import java.util.Optional; @Service +@RequiredArgsConstructor +@Slf4j public class CheckHabilitationServiceImpl implements CheckHabilitationService { - static final Logger LOGGER = LoggerFactory.getLogger(CheckHabilitationServiceImpl.class); + private final ApplicationConfig applicationConfig; - @Autowired - ApplicationConfig applicationConfig; + private final ViewService viewService; - @Autowired - private ViewService viewService; - - @Autowired - CampaignService campaignService; - - @Autowired - UserService userService; + private final UserService userService; @Override public ResponseEntity checkHabilitation(String role, String idSu, String campaignId) { @@ -44,89 +37,74 @@ public ResponseEntity checkHabilitation(String role, String idS HabilitationDto resp = new HabilitationDto(); //noauth - if (!applicationConfig.getAuthType().equals("OIDC")) { + if (!applicationConfig.getAuthType().equals(AuthConstants.OIDC)) { resp.setHabilitated(true); return new ResponseEntity<>(resp, HttpStatus.OK); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final Jwt jwt = (Jwt) authentication.getPrincipal(); List roles = jwt.getClaimAsStringList(applicationConfig.getRoleClaim()); - String idec=jwt.getClaimAsString(applicationConfig.getIdClaim()).toUpperCase(); + String idec = jwt.getClaimAsString(applicationConfig.getIdClaim()).toUpperCase(); //admin - if(isUserInRole(roles, applicationConfig.getRoleAdmin())){ - LOGGER.info("Check habilitation of admin {} for accessing survey-unit {} of campaign {} resulted in true",idec,idSu,campaignId); + if (isUserInRole(roles, applicationConfig.getRoleAdmin())) { + log.info("Check habilitation of admin {} for accessing survey-unit {} of campaign {} resulted in true", idec, idSu, campaignId); resp.setHabilitated(true); return new ResponseEntity<>(resp, HttpStatus.OK); } //respondents - if (role == null || role.isBlank() || role.equals(Constants.INTERVIEWER) ) - { - if(isUserInRole(roles, applicationConfig.getRoleRespondent())) { + if (role == null || role.isBlank() || role.equals(Constants.INTERVIEWER)) { + if (isUserInRole(roles, applicationConfig.getRoleRespondent())) { boolean habilitated = viewService.countViewByIdentifierIdSuCampaignId(idec, idSu, campaignId) != 0; - LOGGER.info("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} resulted in {}", idec, idSu, campaignId, habilitated); + log.info("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} resulted in {}", idec, idSu, campaignId, habilitated); resp.setHabilitated(habilitated); return new ResponseEntity<>(resp, HttpStatus.OK); } - LOGGER.warn("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} - no respondent habilitation found in token - check habilitation: false", idec, idSu, campaignId); + log.warn("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} - no respondent habilitation found in token - check habilitation: false", idec, idSu, campaignId); resp.setHabilitated(false); return new ResponseEntity<>(resp, HttpStatus.OK); } // internal users - Optional user= userService.findByIdentifier(idec); - if(role.equals(Constants.REVIEWER) ) { - if(isUserInRole(roles, applicationConfig.getRoleInternalUser())) { - if (user.isPresent()) { - String userRole; - //List accreditedSources = new ArrayList<>(); - userRole = user.get().getRole().toString(); - if (userRole.equals(User.UserRoleType.assistance)) { - resp.setHabilitated(false); - LOGGER.warn("User '{}' has assistance profile - check habilitation: false", idec); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - /*accreditedSources = userService.findAccreditedSources(user.get().getIdentifier()); - Optional campaign = campaignService.findById(campaignId); - if (campaign.isPresent()) { - String sourceSearched = campaign.get().getSurvey().getSource().getId(); - if (accreditedSources.contains(sourceSearched)) { - LOGGER.info("User {} with profile {} - accreditation found for campaign {} - Check habilitation:true", idec, userRole, campaignId); - resp.setHabilitated(true); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - LOGGER.warn("User {} with profile {} - has no accreditation for campaign {} - Check habilitation:false", idec, userRole, campaignId); - resp.setHabilitated(false); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - LOGGER.warn("Check habilitation of user {} for accessing survey-unit {} of campaign {} - campaign doesn't exist - check habilitation:false", idec, idSu, campaign); + Optional user = userService.findByIdentifier(idec); + if (!role.equals(Constants.REVIEWER)) { + resp.setHabilitated(false); + log.warn("User {} - internal user habilitation not found in token - Check habilitation:false", idec); + return new ResponseEntity<>(resp, HttpStatus.OK); + } + if (isUserInRole(roles, applicationConfig.getRoleInternalUser())) { + if (user.isPresent()) { + String userRole; + //List accreditedSources = new ArrayList<>(); + userRole = user.get().getRole().toString(); + if (userRole.equals(User.UserRoleType.assistance)) { resp.setHabilitated(false); - return new ResponseEntity<>(resp, HttpStatus.OK);*/ - resp.setHabilitated(true); - LOGGER.warn("User '{}' has {} profile - check habilitation: true", idec, userRole); + log.warn("User '{}' has assistance profile - check habilitation: false", idec); return new ResponseEntity<>(resp, HttpStatus.OK); } - - resp.setHabilitated(false); - LOGGER.warn("User '{}' doesn't exists", idec); + resp.setHabilitated(true); + log.warn("User '{}' has {} profile - check habilitation: true", idec, userRole); return new ResponseEntity<>(resp, HttpStatus.OK); } + resp.setHabilitated(false); - LOGGER.warn("User {} - internal user habilitation not found in token - Check habilitation:false", idec); + log.warn("User '{}' doesn't exists", idec); return new ResponseEntity<>(resp, HttpStatus.OK); + + } resp.setHabilitated(false); - LOGGER.warn("Only '{}' ans '{}' are accepted as a role in query argument", Constants.REVIEWER, Constants.INTERVIEWER); + log.warn("Only '{}' ans '{}' are accepted as a role in query argument", Constants.REVIEWER, Constants.INTERVIEWER); return new ResponseEntity<>(resp, HttpStatus.OK); } private boolean isUserInRole(List roles, List role) { - return role.stream().anyMatch(r -> roles.contains(r)); + return role.stream().anyMatch(r -> roles.contains(r)); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java index 7fbdf6eb..927dcb21 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java @@ -1,18 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.service.impl; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; -import lombok.extern.slf4j.Slf4j; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; @@ -23,7 +10,16 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @Service @Slf4j diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java index ac670055..5d450df1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java @@ -1,37 +1,13 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import java.text.ParseException; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import fr.insee.survey.datacollectionmanagement.questioning.domain.Upload; -import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Upload; import fr.insee.survey.datacollectionmanagement.questioning.dto.QuestioningEventDto; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -40,16 +16,32 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.text.ParseException; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") +@Slf4j public class QuestioningEventController { - static final Logger LOGGER = LoggerFactory.getLogger(QuestioningEventController.class); - @Autowired private QuestioningEventService questioningEventService; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index c3b4666c..b7f216b9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -1,34 +1,5 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; -import java.text.ParseException; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.dto.SurveyUnitDto; @@ -40,6 +11,21 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.text.ParseException; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -49,8 +35,6 @@ @Slf4j public class SurveyUnitController { - static final Logger LOGGER = LoggerFactory.getLogger(SurveyUnitController.class); - @Autowired private SurveyUnitService surveyUnitService; @@ -123,7 +107,7 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo if (surveyUnitService.findbyId(surveyUnitDto.getIdSu()).isPresent()) responseStatus = HttpStatus.OK; else { - LOGGER.info("Creating survey with the id {}", surveyUnitDto.getIdSu()); + log.info("Creating survey with the id {}", surveyUnitDto.getIdSu()); responseStatus = HttpStatus.CREATED; } return ResponseEntity.status(responseStatus) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java index 1b576908..3e5ef5fc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java @@ -4,15 +4,14 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.RessourceNotValidatedException; import fr.insee.survey.datacollectionmanagement.query.domain.ResultUpload; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.Upload; import fr.insee.survey.datacollectionmanagement.questioning.dto.UploadDto; -import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import io.swagger.v3.oas.annotations.tags.Tag; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -27,8 +26,8 @@ + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "5 - Moog", description = "Enpoints for moog") +@Slf4j public class UploadController { - static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class); @Autowired UploadService moogUploadService; @@ -41,7 +40,7 @@ public class UploadController { @DeleteMapping(value = Constants.MOOG_API_UPLOADS_ID) public ResponseEntity deleteOneUpload(@PathVariable Long id) { - LOGGER.info("Request DELETE for upload n° {}", id); + log.info("Request DELETE for upload n° {}", id); Optional upOpt = moogUploadService.findById(id); if(!upOpt.isPresent()) { @@ -64,14 +63,14 @@ public ResponseEntity deleteOneUpload(@PathVariable Long id) { @GetMapping(value = Constants.MOOG_API_CAMPAIGN_UPLOADS, produces = "application/json") public JSONCollectionWrapper displayAllUploads(@PathVariable String idCampaign) { - LOGGER.info("Request GET for uploads"); + log.info("Request GET for uploads"); return new JSONCollectionWrapper(moogUploadService.findAllByIdCampaign(idCampaign)); } @PostMapping(value = Constants.MOOG_API_CAMPAIGN_UPLOADS, produces = "application/json") public ResultUpload addQuestioningEventViaUpload(@PathVariable String idCampaign, @RequestBody UploadDto request) throws RessourceNotValidatedException { - LOGGER.info("Request POST to add an upload"); + log.info("Request POST to add an upload"); ResultUpload retourInfo = moogUploadService.save(idCampaign, request); return retourInfo; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java index d60d5d11..a0265d15 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java @@ -1,19 +1,16 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.EventOrderService; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; @Service +@Slf4j public class EventOrderServiceImpl implements EventOrderService { - static final Logger LOGGER = LoggerFactory.getLogger(EventOrderServiceImpl.class); - @Autowired EventOrderRepository eventOrderRepository; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java index b1cd0147..42e37974 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java @@ -16,9 +16,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -38,10 +37,9 @@ + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") +@Slf4j public class SourceAccreditationController { - static final Logger LOGGER = LoggerFactory.getLogger(SourceAccreditationController.class); - @Autowired private SourceAccreditationService sourceAccreditationService; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index c8abf72f..d8607014 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -18,8 +18,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; @@ -45,9 +43,7 @@ @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") @Slf4j public class UserController { - - static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); - + @Autowired UserService userService; @@ -125,14 +121,14 @@ public ResponseEntity putUser(@PathVariable("id") String id, @RequestBody Use } catch (NoSuchElementException e) { - LOGGER.info("Creating user with the identifier {}", userDto.getIdentifier()); + log.info("Creating user with the identifier {}", userDto.getIdentifier()); user = convertToEntityNewContact(userDto); User userCreate = userService.createUserEvent(user, null); return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).body(convertToDto(userCreate)); } - LOGGER.info("Updating user with the identifier {}", userDto.getIdentifier()); + log.info("Updating user with the identifier {}", userDto.getIdentifier()); User userUpdate = userService.updateUserEvent(user, null); return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(userUpdate)); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java index 65ef1336..fcae4c2c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java @@ -20,10 +20,9 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jeasy.random.EasyRandom; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -32,9 +31,9 @@ import java.util.concurrent.TimeUnit; @Component +@Slf4j public class Dataloader { - private static final Logger LOGGER = LogManager.getLogger(Dataloader.class); @Autowired private ContactRepository contactRepository; @@ -197,11 +196,11 @@ private Operator createOperator(Faker faker) { private void initOrder() { Long nbExistingOrders = orderRepository.count(); - LOGGER.info("{} orders in database", nbExistingOrders); + log.info("{} orders in database", nbExistingOrders); if (nbExistingOrders !=8 ) { // Creating table order - LOGGER.info("loading eventorder data"); + log.info("loading eventorder data"); orderRepository.deleteAll(); orderRepository .saveAndFlush(new EventOrder(Long.parseLong("8"), TypeQuestioningEvent.REFUSAL.toString(), 8)); @@ -225,7 +224,7 @@ private void initContact(Faker faker) { List
listAddresses = new ArrayList<>(); Long nbExistingContacts = contactRepository.count(); - LOGGER.info("{} contacts exist in database", nbExistingContacts); + log.info("{} contacts exist in database", nbExistingContacts); int nbContacts = 1000000; @@ -267,10 +266,10 @@ private void initContact(Faker faker) { listContact = new ArrayList<>(); long end = System.currentTimeMillis(); - // LOGGER.info("It took {}ms to execute save() for 100 contacts.", (end - + // log.info("It took {}ms to execute save() for 100 contacts.", (end - // start)); - LOGGER.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); + log.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); } } @@ -293,10 +292,10 @@ private void initContact(Faker faker) { // contactRepository.saveAll(listContact); // long end = System.currentTimeMillis(); // - // LOGGER.info("It took {}ms to execute save() for {} contacts.", (end - start), + // log.info("It took {}ms to execute save() for {} contacts.", (end - start), // (nbContacts - nbExistingContacts)); - // LOGGER.info("It took {}ms to execute saveAll() for {} contacts.", (end - + // log.info("It took {}ms to execute saveAll() for {} contacts.", (end - // start), (nbContacts - nbExistingContacts)); } @@ -331,7 +330,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { supportSsne.setLabel("Insee Normandie - SSNE"); Set setSourcesSupportSsne = new HashSet<>(); - LOGGER.info("{} campaigns exist in database", campaignRepository.count()); + log.info("{} campaigns exist in database", campaignRepository.count()); while (sourceRepository.count() < 10) { @@ -438,7 +437,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { Long nbExistingQuestionings = questioningRepository.count(); - LOGGER.info("{} questionings exist in database", nbExistingQuestionings); + log.info("{} questionings exist in database", nbExistingQuestionings); long start = System.currentTimeMillis(); Questioning qu; @@ -449,7 +448,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { String fakeSiren; Random qeRan = new Random(); - LOGGER.info("{} survey units exist in database", surveyUnitRepository.count()); + log.info("{} survey units exist in database", surveyUnitRepository.count()); for (Long i = surveyUnitRepository.count(); i < 500000; i++) { SurveyUnit su = new SurveyUnit(); @@ -546,7 +545,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { questioningRepository.save(qu); if (i % 100 == 0) { long end = System.currentTimeMillis(); - LOGGER.info("It took {}ms to execute save() for 100 questionings.", (end - start)); + log.info("It took {}ms to execute save() for 100 questionings.", (end - start)); start = System.currentTimeMillis(); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java index 48676367..164af1d2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java @@ -20,10 +20,9 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jeasy.random.EasyRandom; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; @@ -34,10 +33,9 @@ @Component @Profile("poc") +@Slf4j public class DataloaderPoc { - private static final Logger LOGGER = LogManager.getLogger(DataloaderPoc.class); - @Autowired private ContactRepository contactRepository; @@ -199,11 +197,11 @@ private Operator createOperator(Faker faker) { private void initOrder() { Long nbExistingOrders = orderRepository.count(); - LOGGER.info("{} orders in database", nbExistingOrders); + log.info("{} orders in database", nbExistingOrders); if (nbExistingOrders == 0) { // Creating table order - LOGGER.info("loading eventorder data"); + log.info("loading eventorder data"); orderRepository .saveAndFlush(new EventOrder(Long.parseLong("8"), TypeQuestioningEvent.REFUSAL.toString(), 8)); orderRepository @@ -226,7 +224,7 @@ private void initContact(Faker faker) { List
listAddresses = new ArrayList<>(); Long nbExistingContacts = contactRepository.count(); - LOGGER.info("{} contacts exist in database", nbExistingContacts); + log.info("{} contacts exist in database", nbExistingContacts); int nbContacts = 1000000; @@ -268,10 +266,10 @@ private void initContact(Faker faker) { listContact = new ArrayList<>(); long end = System.currentTimeMillis(); - // LOGGER.info("It took {}ms to execute save() for 100 contacts.", (end - + // log.info("It took {}ms to execute save() for 100 contacts.", (end - // start)); - LOGGER.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); + log.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); } } @@ -294,10 +292,10 @@ private void initContact(Faker faker) { // contactRepository.saveAll(listContact); // long end = System.currentTimeMillis(); // - // LOGGER.info("It took {}ms to execute save() for {} contacts.", (end - start), + // log.info("It took {}ms to execute save() for {} contacts.", (end - start), // (nbContacts - nbExistingContacts)); - // LOGGER.info("It took {}ms to execute saveAll() for {} contacts.", (end - + // log.info("It took {}ms to execute saveAll() for {} contacts.", (end - // start), (nbContacts - nbExistingContacts)); } @@ -332,7 +330,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { supportSsne.setLabel("Insee Normandie - SSNE"); Set setSourcesSupportSsne = new HashSet<>(); - LOGGER.info("{} campaigns exist in database", campaignRepository.count()); + log.info("{} campaigns exist in database", campaignRepository.count()); while (sourceRepository.count() < 10) { @@ -439,7 +437,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { Long nbExistingQuestionings = questioningRepository.count(); - LOGGER.info("{} questionings exist in database", nbExistingQuestionings); + log.info("{} questionings exist in database", nbExistingQuestionings); long start = System.currentTimeMillis(); Questioning qu; @@ -450,7 +448,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { String fakeSiren; Random qeRan = new Random(); - LOGGER.info("{} survey units exist in database", surveyUnitRepository.count()); + log.info("{} survey units exist in database", surveyUnitRepository.count()); for (Long i = surveyUnitRepository.count(); i < 500000; i++) { SurveyUnit su = new SurveyUnit(); @@ -547,7 +545,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { questioningRepository.save(qu); if (i % 100 == 0) { long end = System.currentTimeMillis(); - LOGGER.info("It took {}ms to execute save() for 100 questionings.", (end - start)); + log.info("It took {}ms to execute save() for 100 questionings.", (end - start)); start = System.currentTimeMillis(); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index 4ef841e2..ba304a61 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -7,9 +7,8 @@ import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import net.minidev.json.JSONObject; import org.assertj.core.util.DateUtil; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -213,7 +212,7 @@ private String createJsonPart(Partitioning part) { return jo.toString(); } - private String createJson(Campaign campaign, String idSurvey) throws JSONException { + private String createJson(Campaign campaign, String idSurvey) { JSONObject jo = new JSONObject(); jo.put("id", campaign.getId()); jo.put("year", campaign.getYear()); From 530374ab85648f3a0161b72b3b59e0fd58692fea Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 10:44:44 +0100 Subject: [PATCH 013/111] fix: campaign controller test --- .../metadata/controller/CampaignControllerTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index ba304a61..b07783ca 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -205,9 +205,9 @@ private String createJsonPart(Partitioning part) { JSONObject jo = new JSONObject(); jo.put("id", part.getId()); jo.put("campaignId", part.getCampaign().getId()); - jo.put("openingDate", part.getOpeningDate().toInstant()); - jo.put("closingDate", part.getClosingDate().toInstant()); - jo.put("returnDate", part.getClosingDate().toInstant()); + jo.put("openingDate", part.getOpeningDate().toInstant().toString()); + jo.put("closingDate", part.getClosingDate().toInstant().toString()); + jo.put("returnDate", part.getClosingDate().toInstant().toString()); jo.put("label", "label"); return jo.toString(); } From 1d13e723a8b1ea2b7593aead521444b75bafb467 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 10:52:34 +0100 Subject: [PATCH 014/111] refactor: toList --- .../contact/controller/ContactController.java | 7 ++- .../controller/ContactEventController.java | 4 +- .../service/impl/ContactServiceImpl.java | 29 ++++-------- .../controller/CampaignController.java | 18 +++++--- .../metadata/controller/OwnerController.java | 38 ++++++--------- .../controller/PartitioningController.java | 43 ++++++++--------- .../metadata/controller/SourceController.java | 46 +++++++------------ .../controller/SupportController.java | 38 ++++++--------- .../metadata/controller/SurveyController.java | 41 +++++++---------- .../metadata/service/CampaignService.java | 2 +- .../service/impl/CampaignServiceImpl.java | 2 +- .../controller/MonitoringController.java | 5 +- .../QuestioningAccreditationController.java | 11 ++--- .../controller/QuestioningController.java | 30 +++++------- .../impl/SearchContactServiceImpl.java | 32 ++++++------- .../QuestioningEventController.java | 2 +- .../controller/SurveyUnitController.java | 3 +- .../impl/QuestioningEventServiceImpl.java | 21 +++------ .../service/impl/UploadServiceImpl.java | 15 +++--- .../user/controller/UserController.java | 2 +- .../user/controller/UserEventController.java | 4 +- .../user/service/impl/UserServiceImpl.java | 5 +- ...estionningAccreditationControllerTest.java | 2 +- 23 files changed, 163 insertions(+), 237 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index 5e2bc7a3..da9e8394 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -36,7 +36,6 @@ import java.util.NoSuchElementException; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -75,7 +74,7 @@ public ResponseEntity getContacts( @RequestParam(defaultValue = "identifier") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageC = contactService.findAll(pageable); - List listC = pageC.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listC = pageC.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new ContactPage(listC, pageable, pageC.getTotalElements())); } @@ -187,7 +186,7 @@ private ContactFirstLoginDto convertToFirstLoginDto(Contact contact) { ContactFirstLoginDto contactFirstLoginDto = modelMapper.map(contact, ContactFirstLoginDto.class); contactFirstLoginDto.setCivility(contact.getGender()); contactFirstLoginDto.setFirstConnect(contact.getContactEvents().stream() - .filter(e -> e.getType().equals(ContactEventType.firstConnect)).collect(Collectors.toList()).isEmpty()); + .filter(e -> e.getType().equals(ContactEventType.firstConnect)).count() == 0); return contactFirstLoginDto; } @@ -195,7 +194,7 @@ private Contact convertToEntity(ContactDto contactDto) throws ParseException, No Contact contact = modelMapper.map(contactDto, Contact.class); contact.setGender(contactDto.getCivility()); Optional oldContact = contactService.findByIdentifier(contactDto.getIdentifier()); - if (!oldContact.isPresent()) { + if (oldContact.isEmpty()) { throw new NoSuchElementException(); } contact.setComment(oldContact.get().getComment()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index c38f87dd..fa543cf6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -61,8 +61,8 @@ public ResponseEntity getContactContactEvents(@PathVariable("id") String iden Optional optContact = contactService.findByIdentifier(identifier); if (optContact.isPresent()) { return ResponseEntity.status(HttpStatus.OK) - .body(optContact.get().getContactEvents().stream().map(ce -> convertToDto(ce)) - .collect(Collectors.toList())); + .body(optContact.get().getContactEvents().stream().map(this::convertToDto) + .toList()); } else return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 2d336372..5fea711b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -1,22 +1,6 @@ package fr.insee.survey.datacollectionmanagement.contact.service.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import com.fasterxml.jackson.databind.JsonNode; - import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; @@ -24,6 +8,13 @@ import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.*; @Service public class ContactServiceImpl implements ContactService { @@ -90,7 +81,7 @@ public List searchListContactParameters(String identifier, String lastN alwaysEmpty = false; } else listContactContact = listContactContact.stream().filter(c -> c.getLastName().equalsIgnoreCase(lastName)) - .collect(Collectors.toList()); + .toList(); } @@ -100,7 +91,7 @@ public List searchListContactParameters(String identifier, String lastN alwaysEmpty = false; } else listContactContact = listContactContact.stream() - .filter(c -> c.getFirstName().equalsIgnoreCase(firstName)).collect(Collectors.toList()); + .filter(c -> c.getFirstName().equalsIgnoreCase(firstName)) .toList(); } if (!StringUtils.isEmpty(email)) { @@ -109,7 +100,7 @@ public List searchListContactParameters(String identifier, String lastN alwaysEmpty = false; } else listContactContact = listContactContact.stream().filter(c -> c.getEmail().equalsIgnoreCase(email)) - .collect(Collectors.toList()); + .toList(); } return listContactContact; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 07a8bc2a..a727fa9d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; @@ -20,7 +21,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; -import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; @@ -66,7 +66,7 @@ public class CampaignController { @Autowired UploadService uploadService; - + @Operation(summary = "Search for campaigns, paginated") @GetMapping(value = Constants.API_CAMPAIGNS, produces = "application/json") @ApiResponses(value = { @@ -168,10 +168,16 @@ public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @ApiResponse(responseCode = "400", description = "Bad Request") }) @Transactional - public ResponseEntity deleteCampaign(@PathVariable("id") String id) { - if(campaignService.isCampaignOngoing(id)){ - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign is still ongoing and can't be deleted"); + public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr.insee.survey.datacollectionmanagement.exception.NotFoundException { + + try { + if (campaignService.isCampaignOngoing(id)) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign is still ongoing and can't be deleted"); + } + } catch (NotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Campaign does not exist"); } + try { Optional campaign = campaignService.findById(id); if (!campaign.isPresent()) { @@ -191,7 +197,7 @@ public ResponseEntity deleteCampaign(@PathVariable("id") String id) { for (Partitioning partitioning : listPartitionings) { nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); } - uploadsCamp.forEach(up->uploadService.delete(up)); + uploadsCamp.forEach(up -> uploadService.delete(up)); log.info("Campaign {} deleted with all its metadata children - {} questioning deleted - {} view deleted - {} uploads deleted", id, nbQuestioningDeleted, nbViewDeleted, uploadsCamp.size()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index 77ddbed8..d8ba0e1f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -1,29 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.dto.OwnerDto; @@ -35,6 +11,18 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; @RestController @CrossOrigin @@ -62,7 +50,7 @@ public ResponseEntity getOwners( @RequestParam(defaultValue = "id") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageOwner = ownerService.findAll(pageable); - List listOwners = pageOwner.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listOwners = pageOwner.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new OwnerPage(listOwners, pageable, pageOwner.getTotalElements())); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index 736d45fd..82e7243b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -1,27 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -37,6 +15,21 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -68,13 +61,13 @@ public class PartitioningController { public ResponseEntity getPartitioningsByCampaign(@PathVariable("id") String id) { try { Optional campaign = campaignService.findById(id); - if (!campaign.isPresent()) { + if (campaign.isEmpty()) { log.warn("Campaign {} does not exist", id); return ResponseEntity.status(HttpStatus.NOT_FOUND).body("campaign does not exist"); } return ResponseEntity.ok() - .body(campaign.get().getPartitionings().stream().map(s -> convertToDto(s)) - .collect(Collectors.toList())); + .body(campaign.get().getPartitionings().stream().map(this::convertToDto) + .toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index 7cd69979..f06421a6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -1,32 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; @@ -47,6 +20,21 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -85,7 +73,7 @@ public ResponseEntity getSources( @RequestParam(defaultValue = "id") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageSource = sourceService.findAll(pageable); - List listSources = pageSource.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listSources = pageSource.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new SourcePage(listSources, pageable, pageSource.getTotalElements())); } @@ -202,7 +190,7 @@ public ResponseEntity getSourcesByOwner(@PathVariable("id") String id) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("owner does not exist"); } return ResponseEntity.ok() - .body(owner.get().getSources().stream().map(s -> convertToDto(s)).collect(Collectors.toList())); + .body(owner.get().getSources().stream().map(this::convertToDto).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index 030c30b7..993535d2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -1,29 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.CrossOrigin; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.dto.SupportDto; @@ -35,6 +11,18 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.List; +import java.util.Optional; @RestController @CrossOrigin @@ -62,7 +50,7 @@ public ResponseEntity getSupports( @RequestParam(defaultValue = "id") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageSupport = supportService.findAll(pageable); - List listSupports = pageSupport.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listSupports = pageSupport.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new SupportPage(listSupports, pageable, pageSupport.getTotalElements())); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 1480f8a5..8959061c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -1,28 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -41,6 +18,22 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -80,7 +73,7 @@ public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("source does not exist"); } return ResponseEntity.ok() - .body(source.get().getSurveys().stream().map(s -> convertToDto(s)).collect(Collectors.toList())); + .body(source.get().getSurveys().stream().map(this::convertToDto).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java index 3f6c04de..e1dfb192 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java @@ -1,9 +1,9 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; -import jakarta.ws.rs.NotFoundException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java index 8902b2bb..f3680ba8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java @@ -1,12 +1,12 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; -import jakarta.ws.rs.NotFoundException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java index d5a3ea8c..6b7dd8a8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java @@ -19,7 +19,6 @@ import java.util.NoSuchElementException; import java.util.Optional; -import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -57,11 +56,11 @@ public JSONCollectionWrapper getDataToFollowUp(@PathVariable St public JSONCollectionWrapper getDataForProgressTemp(@PathVariable String idCampaign) { log.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); Optional campaign = campaignService.findById(idCampaign); - if (!campaign.isPresent()) { + if (campaign.isEmpty()) { throw new NoSuchElementException("campaign does not exist"); } log.info("{} partitionings found", campaign.get().getPartitionings().stream().map(Partitioning::getId) - .collect(Collectors.toList()).size()); + .toList().size()); campaign.get().getPartitionings().forEach(part -> log.info("{} partitionig found", part.getId())); return null; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java index dff09631..c175f205 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java @@ -31,7 +31,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -72,8 +71,8 @@ public ResponseEntity getQuestioningAccreditation(@PathVariable("id") Long id Optional optQuestioning = questioningService.findbyId(id); if (optQuestioning.isPresent()) return new ResponseEntity<>( - optQuestioning.get().getQuestioningAccreditations().stream().map(c -> convertToDto(c)) - .collect(Collectors.toList()), + optQuestioning.get().getQuestioningAccreditations().stream().map(this::convertToDto) + .toList(), HttpStatus.OK); else return new ResponseEntity<>("Questioning does not exist", HttpStatus.NOT_FOUND); @@ -101,7 +100,7 @@ public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long i // Check if questioning exists try { optQuestioning = questioningService.findbyId(id); - if (!optQuestioning.isPresent()) + if (optQuestioning.isEmpty()) return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Questioning does not exist"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); @@ -109,7 +108,7 @@ public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long i Questioning questioning = optQuestioning.get(); // Check if contact exists - if (!contactService.findByIdentifier(idContact).isPresent()) + if (contactService.findByIdentifier(idContact).isEmpty()) return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); HttpHeaders responseHeaders = new HttpHeaders(); @@ -123,7 +122,7 @@ public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long i .filter(acc -> acc.getIdContact().equals(idContact) && acc.getQuestioning().getIdPartitioning().equals(part.get().getId()) && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) - .collect(Collectors.toList()); + .toList(); if (listContactAccreditations.isEmpty()) { // Create new accreditation diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java index a2ef5ee8..0a56a6e4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java @@ -1,22 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; @@ -32,6 +15,17 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -119,7 +113,7 @@ public ResponseEntity getQuestioningsBySurveyUnit(@PathVariable("id") String Optional optSu = surveyUnitService.findbyId(StringUtils.upperCase(id)); if (optSu.isPresent()) return new ResponseEntity<>( - optSu.get().getQuestionings().stream().map(q -> convertToDto(q)).collect(Collectors.toList()), + optSu.get().getQuestionings().stream().map(this::convertToDto).toList(), HttpStatus.OK); else { log.warn("survey unit {} does not exist", id); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index de8f6218..0e376061 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -1,14 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.service.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; @@ -20,6 +11,13 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import lombok.EqualsAndHashCode; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; @Service @EqualsAndHashCode @@ -68,7 +66,7 @@ public List searchContactCrossDomain( alwaysEmpty = false; } else if (!alwaysEmpty) { listView = listView.stream().filter(v -> viewService.findViewByIdSu(idSu).contains(v)) - .collect(Collectors.toList()); + .toList(); } } @@ -89,7 +87,7 @@ public List searchContactCrossDomain( listViewC .addAll(listView.stream() .filter(v -> viewService.findViewByCampaignId(c.getId()).contains(v)) - .collect(Collectors.toList())); + .toList()); } listView = listViewC; } @@ -109,7 +107,7 @@ public List searchContactCrossDomain( listViewC .addAll(listView.stream() .filter(v -> viewService.findViewByCampaignId(c.getId()).contains(v)) - .collect(Collectors.toList())); + .toList()); } listView = listViewC; } @@ -127,7 +125,7 @@ public List searchContactCrossDomain( listView = listView.stream() .filter(v -> lastName .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getLastName())) - .collect(Collectors.toList()); + .toList(); } if (!StringUtils.isEmpty(firstName)) { @@ -142,7 +140,7 @@ public List searchContactCrossDomain( listView = listView.stream() .filter(v -> firstName .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getFirstName())) - .collect(Collectors.toList()); + .toList(); } if (!StringUtils.isEmpty(email)) { @@ -156,7 +154,7 @@ public List searchContactCrossDomain( listView = listView.stream().filter( v -> email.equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getEmail())) - .collect(Collectors.toList()); + .toList(); } if (!StringUtils.isEmpty(identificationCode)) { @@ -171,7 +169,7 @@ public List searchContactCrossDomain( for (SurveyUnit s : listSurveyUnits) { listView = listView.stream() .filter(v -> identificationCode.equalsIgnoreCase(s.getIdentificationCode())) - .collect(Collectors.toList()); + .toList(); } } @@ -189,7 +187,7 @@ public List searchContactCrossDomain( for (SurveyUnit s : listSurveyUnits) { listView = listView.stream() .filter(v -> identificationName.equalsIgnoreCase(s.getIdentificationName())) - .collect(Collectors.toList()); + .toList(); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java index 5d450df1..15c98dda 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java @@ -68,7 +68,7 @@ public ResponseEntity findQuestioningEventsByQuestioning(@PathVariable("id") Set setQe = questioning.get().getQuestioningEvents(); return ResponseEntity.status(HttpStatus.OK) .body(setQe.stream() - .map(q -> convertToDto(q)).collect(Collectors.toList())); + .map(this::convertToDto).toList()); } else return ResponseEntity.status(HttpStatus.NOT_FOUND).body("questioning not found"); } catch (Exception e) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index b7f216b9..a326be4b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -25,7 +25,6 @@ import java.text.ParseException; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -54,7 +53,7 @@ public Page getSurveyUnits( @RequestParam(defaultValue = "idSu") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageC = surveyUnitService.findAll(pageable); - List listSuDto = pageC.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listSuDto = pageC.stream().map(this::convertToDto).toList(); return new SurveyUnitPage(listSuDto, pageable, pageC.getTotalElements()); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java index f61b9733..aad5e901 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java @@ -1,19 +1,16 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningEventRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.util.LastQuestioningEventComparator; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; @Service public class QuestioningEventServiceImpl implements QuestioningEventService { @@ -45,17 +42,13 @@ public Optional getLastQuestioningEvent(Questioning questionin List events) { List listQuestioningEvent = questioning.getQuestioningEvents().stream() - .filter(qe -> events.contains(qe.getType())) - .collect(Collectors.toList()); - Collections.sort(listQuestioningEvent, lastQuestioningEventComparator); + .filter(qe -> events.contains(qe.getType())).sorted(lastQuestioningEventComparator).toList(); return listQuestioningEvent.stream().findFirst(); } @Override public List findbyIdUpload(Long id){ - List listQuestioningEvent = questioningEventRepository.findAll().stream().filter(qe -> qe.getUpload()!= null && qe.getUpload().getId().equals(id)).collect(Collectors.toList()); - - return listQuestioningEvent; + return questioningEventRepository.findAll().stream().filter(qe -> qe.getUpload()!= null && qe.getUpload().getId().equals(id)).toList(); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java index 4b33251a..75caf212 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java @@ -23,7 +23,6 @@ import org.springframework.stereotype.Service; import java.util.*; -import java.util.stream.Collectors; @Service @Slf4j @@ -63,7 +62,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc QuestioningEvent qe = new QuestioningEvent(); Optional campaign = campaignService.findById(idCampaign); - if (!campaign.isPresent()) { + if (campaign.isEmpty()) { throw new RessourceNotValidatedException("Campaign", idCampaign); } Set setParts = campaign.get().getPartitionings(); @@ -75,7 +74,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc List listIdParts = campaignService.findById(idCampaign).get().getPartitionings().stream().map(Partitioning::getId).toList(); Optional quest = questionings.stream().filter(q -> listIdParts.contains(q.getIdPartitioning()) && q.getQuestioningAccreditations().stream().map(QuestioningAccreditation::getIdContact) - .collect(Collectors.toList()).contains(mmDto.getIdContact())).findFirst(); + .toList().contains(mmDto.getIdContact())).findFirst(); qe.setUpload(up); qe.setType(TypeQuestioningEvent.valueOf(mmDto.getStatus())); @@ -97,7 +96,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc result.addIdKo(identifier, "RessourceNotFound or unprocessable request"); } } - if (result.getListIdOK().size() == 0) { + if (result.getListIdOK().isEmpty()) { delete(up); return result; } @@ -117,13 +116,13 @@ public List findAllByIdCampaign(String idCampaign) { Optional campaign = campaignService.findById(idCampaign); - List partitioningIds = campaign.get().getPartitionings().stream().map(Partitioning::getId).collect(Collectors.toList()); + List partitioningIds = campaign.get().getPartitionings().stream().map(Partitioning::getId).toList(); // Keeps the uploads which first managementMonitoringInfo belongs to the survey return uploadRepository.findAll().stream().filter(upload -> !upload.getQuestioningEvents().isEmpty()) .filter(upload -> partitioningIds.contains(upload.getQuestioningEvents().stream().findFirst().get().getQuestioning().getIdPartitioning() )) - .collect(Collectors.toList()); + .toList(); } @@ -142,10 +141,10 @@ public boolean checkUploadDate(String idCampaign, Date date) { Optional campaign = campaignService.findById(idCampaign); Long timestamp = date.getTime(); Long start = campaign.get().getPartitionings().stream().map(Partitioning::getOpeningDate) - .collect(Collectors.toList()).stream() + .toList().stream() .min(Comparator.comparing(Date::getTime)).get().getTime(); Long end = campaign.get().getPartitionings().stream().map(Partitioning::getClosingDate) - .collect(Collectors.toList()).stream() + .toList().stream() .max(Comparator.comparing(Date::getTime)).get().getTime(); return (start < timestamp && timestamp < end); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index d8607014..f7fa956a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -68,7 +68,7 @@ public ResponseEntity getUsers( @RequestParam(defaultValue = "identifier") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageC = userService.findAll(pageable); - List listC = pageC.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listC = pageC.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new UserController.UserPage(listC, pageable, pageC.getTotalElements())); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java index dff884f1..c358ae1c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java @@ -60,8 +60,8 @@ public ResponseEntity getUserUserEvents(@PathVariable("id") String identifier Optional optUser = userService.findByIdentifier(identifier); if (optUser.isPresent()) { return ResponseEntity.status(HttpStatus.OK) - .body(optUser.get().getUserEvents().stream().map(ce -> convertToDto(ce)) - .collect(Collectors.toList())); + .body(optUser.get().getUserEvents().stream().map(this::convertToDto) + .toList()); } else return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index 03383970..0af3808a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -15,7 +15,6 @@ import org.springframework.stereotype.Service; import java.util.*; -import java.util.stream.Collectors; @Service public class UserServiceImpl implements UserService { @@ -82,8 +81,8 @@ public List findAccreditedSources(String identifier){ List accreditedSources = new ArrayList<>(); List accreditations = sourceAccreditationService.findByUserIdentifier(identifier); - List accSource = accreditations.stream().map(SourceAccreditation::getSource).collect(Collectors.toList()); - accSource.stream().forEach(acc -> accreditedSources.add(acc.getId())); + List accSource = accreditations.stream().map(SourceAccreditation::getSource).toList(); + accSource.forEach(acc -> accreditedSources.add(acc.getId())); return accreditedSources; } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java index 0ef4b1f2..cefab50d 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java @@ -116,7 +116,7 @@ public void postAccreditationCreateUpdate() throws Exception { QuestioningAccreditation accreditationFoundAfterUpdate = questioningService.findbyId((long) idQuestioning).get() .getQuestioningAccreditations().stream().filter(acc -> acc.getIdContact().equals(idContact)) - .collect(Collectors.toList()).get(0); + .toList().get(0); assertEquals(true, accreditationFoundAfterUpdate.isMain()); } From 276974bac80c79f2f15a4488d2b80f00c95dfea8 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 16:27:37 +0100 Subject: [PATCH 015/111] refactor: rename User to AuthUser --- .../config/LogInterceptor.java | 6 +- .../auth/security/DefaultSecurityContext.java | 4 +- .../OpenIDConnectSecurityContext.java | 6 +- .../auth/user/{User.java => AuthUser.java} | 2 +- .../auth/user/AuthorizeMethodDecider.java | 62 ++++++++++--------- .../config/auth/user/UserProvider.java | 2 +- .../config/auth/user/UserToMdcFilter.java | 4 +- 7 files changed, 45 insertions(+), 41 deletions(-) rename src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/{User.java => AuthUser.java} (92%) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java index 79a83cf3..82601354 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java @@ -1,7 +1,7 @@ package fr.insee.survey.datacollectionmanagement.config; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import jakarta.servlet.http.HttpServletRequest; @@ -40,8 +40,8 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons case AuthConstants.OIDC: Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - User currentUser = userProvider.getUser(authentication); - userId=(currentUser!=null && currentUser.getId()!=null ?currentUser.getId() : "anonymous"); + AuthUser currentAuthUser = userProvider.getUser(authentication); + userId=(currentAuthUser !=null && currentAuthUser.getId()!=null ? currentAuthUser.getId() : "anonymous"); ThreadContext.put("user", userId.toUpperCase()); break; default: diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 4088d959..7379971d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -1,7 +1,7 @@ package fr.insee.survey.datacollectionmanagement.config.auth.security; import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; @@ -61,7 +61,7 @@ SecurityFilterChain filterPublicUrlsChain(HttpSecurity http) throws Exception { return publicSecurityFilterChainConfiguration.buildSecurityPublicFilterChain(http, config.getPublicUrls()); } @Bean public UserProvider getUserProvider() { - return auth -> new User("anonymous", Collections.emptyList()); + return auth -> new AuthUser("anonymous", Collections.emptyList()); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index a7a0689c..45576460 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -1,7 +1,7 @@ package fr.insee.survey.datacollectionmanagement.config.auth.security; import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.config.auth.user.User; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import fr.insee.survey.datacollectionmanagement.constants.Constants; @@ -15,6 +15,7 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; @@ -31,6 +32,7 @@ @Configuration @EnableWebSecurity +@EnableMethodSecurity @ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = AuthConstants.OIDC) @Slf4j @AllArgsConstructor @@ -92,7 +94,7 @@ public UserProvider getUserProvider() { final Jwt jwt = (Jwt) auth.getPrincipal(); List tryRoles = jwt.getClaimAsStringList(config.getRoleClaim()); String tryId = jwt.getClaimAsString(config.getIdClaim()); - return new User(tryId, tryRoles); + return new AuthUser(tryId, tryRoles); }; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthUser.java similarity index 92% rename from src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java rename to src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthUser.java index 0de0dfa4..8190fba2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthUser.java @@ -9,7 +9,7 @@ @Getter @Setter @RequiredArgsConstructor -public class User { +public class AuthUser { private final String id; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java index 12e42634..5ff9e4c6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java @@ -2,7 +2,6 @@ import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; @@ -14,27 +13,29 @@ @Component("AuthorizeMethodDecider") @Slf4j -@RequiredArgsConstructor public class AuthorizeMethodDecider { public static final String ROLE_OFFLINE_ACCESS = "ROLE_offline_access"; public static final String ROLE_UMA_AUTHORIZATION = "ROLE_uma_authorization"; - private User noAuthUser; - private final UserProvider userProvider; + private AuthUser noAuthUser; + + @Autowired + private UserProvider userProvider; @Autowired ApplicationConfig config; - public User getUser() { + + public AuthUser getUser() { if (config.getAuthType().equals(AuthConstants.OIDC)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - User currentUser = userProvider.getUser(authentication); - return currentUser; + AuthUser currentAuthUser = userProvider.getUser(authentication); + return currentAuthUser; } return noAuthUser(); } - private User noAuthUser() { + private AuthUser noAuthUser() { if (this.noAuthUser != null) { return this.noAuthUser; } @@ -43,54 +44,55 @@ private User noAuthUser() { roles.add(ROLE_OFFLINE_ACCESS); roles.add(config.getRoleAdmin().get(0)); roles.add(ROLE_UMA_AUTHORIZATION); - return new User("GUEST", roles); + return new AuthUser("GUEST", roles); } public boolean isInternalUser() { - User user = getUser(); - return isInternalUser(user); + AuthUser authUser = getUser(); + return isInternalUser(authUser); } - public boolean isInternalUser(User user) { - return (hasRole(user, config.getRoleInternalUser())); + public boolean isInternalUser(AuthUser authUser) { + return (hasRole(authUser, config.getRoleInternalUser())); } public boolean isAdmin() { - User user = getUser(); - return isAdmin(user); + AuthUser authUser = getUser(); + return isAdmin(authUser); } - public boolean isAdmin(User user) { - return (hasRole(user, config.getRoleAdmin())); + public boolean isAdmin(AuthUser authUser) { + return (hasRole(authUser, config.getRoleAdmin())); } public boolean isWebClient() { - User user = getUser(); - return isWebClient(user); + AuthUser authUser = getUser(); + return isWebClient(authUser); } - public boolean isWebClient(User user) { - return hasRole(user, config.getRoleWebClient()); + public boolean isWebClient(AuthUser authUser) { + return hasRole(authUser, config.getRoleWebClient()); } public boolean isRespondent() { - User user = getUser(); - return isRespondent(user); + AuthUser authUser = getUser(); + return isRespondent(authUser); } - public boolean isRespondent(User user) { - return hasRole(user, config.getRoleRespondent()); + public boolean isRespondent(AuthUser authUser) { + + return hasRole(authUser, config.getRoleRespondent()); } - private boolean hasRole(User user, List authorizedRoles) { + private boolean hasRole(AuthUser authUser, List authorizedRoles) { Boolean hasRole = false; - List userRoles = user.getRoles(); - return userRoles.stream().filter(r -> authorizedRoles.contains(r)).count() > 0; + List userRoles = authUser.getRoles(); + return userRoles.stream().anyMatch(authorizedRoles::contains); } public String getUsername() { - User user = getUser(); - return user.getId().toUpperCase(); + AuthUser authUser = getUser(); + return authUser.getId().toUpperCase(); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserProvider.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserProvider.java index b67ba536..75017cf6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserProvider.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserProvider.java @@ -5,6 +5,6 @@ @FunctionalInterface public interface UserProvider { - User getUser(Authentication authentication); + AuthUser getUser(Authentication authentication); } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java index 6fec89a4..c3d5cb03 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/UserToMdcFilter.java @@ -24,8 +24,8 @@ protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain ) throws ServletException, IOException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - User currentUser = userProvider.getUser(authentication); - String userId = (currentUser != null && currentUser.getId() != null ? currentUser.getId() : "anonymous"); + AuthUser currentAuthUser = userProvider.getUser(authentication); + String userId = (currentAuthUser != null && currentAuthUser.getId() != null ? currentAuthUser.getId() : "anonymous"); MDC.put(USER, userId); try { filterChain.doFilter(request, response); From 121a3af48fe58f2388b2c8d23f5eba8df160ba21 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 16:28:14 +0100 Subject: [PATCH 016/111] refactor: check habilitation --- .../constants/CheckHabilitationsRoles.java | 6 + .../constants/Constants.java | 5 - .../CheckHabilitationController.java | 13 ++- .../service/CheckHabilitationService.java | 5 +- .../impl/CheckHabilitationServiceImpl.java | 110 ------------------ .../CheckHabilitationServiceImplNoAuth.java | 21 ++++ .../CheckHabilitationServiceImplOidc.java | 87 ++++++++++++++ 7 files changed, 127 insertions(+), 120 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/constants/CheckHabilitationsRoles.java delete mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplNoAuth.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/CheckHabilitationsRoles.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/CheckHabilitationsRoles.java new file mode 100644 index 00000000..365f581e --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/CheckHabilitationsRoles.java @@ -0,0 +1,6 @@ +package fr.insee.survey.datacollectionmanagement.constants; + +public class CheckHabilitationsRoles { + public static final String INTERVIEWER = "interviewer"; + public static final String REVIEWER = "reviewer"; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 70d0f510..f03b822b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -93,11 +93,6 @@ private Constants() { public static final String API_WEBCLIENT_METADATA_ID = "/api/metadata/{id}"; public static final String API_WEBCLIENT_QUESTIONINGS = "/api/questionings"; - // CHECK HABILITATION ROLES - - public static final String INTERVIEWER = "interviewer"; - public static final String REVIEWER = "reviewer"; - public static final String API_HEALTHCHECK = "/api/healthcheck"; public static final String ACTUATOR = "/actuator/**"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java index 2f62b5c6..35641a47 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java @@ -1,10 +1,13 @@ package fr.insee.survey.datacollectionmanagement.query.controller; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; @@ -21,6 +24,9 @@ public class CheckHabilitationController { @Autowired private CheckHabilitationService checkHabilitationService; + @Autowired + UserProvider userProvider; + @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isRespondent()" @@ -31,8 +37,11 @@ public ResponseEntity checkHabilitation( @RequestParam(required = true) String id, @RequestParam(required = true) String campaign, Authentication authentication) { - - return checkHabilitationService.checkHabilitation(role, id,campaign); + AuthUser authUser = userProvider.getUser(authentication); + HabilitationDto habDto = new HabilitationDto(); + boolean habilitated = checkHabilitationService.checkHabilitation(role, id,campaign, authUser); + habDto.setHabilitated(habilitated); + return new ResponseEntity<>(habDto, HttpStatus.OK); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java index 1ef55694..b4f4002c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/CheckHabilitationService.java @@ -1,13 +1,12 @@ package fr.insee.survey.datacollectionmanagement.query.service; -import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; -import org.springframework.http.ResponseEntity; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import org.springframework.stereotype.Service; @Service public interface CheckHabilitationService { - ResponseEntity checkHabilitation(String role, String idSu, String campaign); + boolean checkHabilitation(String role, String idSu, String campaign, AuthUser authUser); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java deleted file mode 100644 index e27fb9f0..00000000 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImpl.java +++ /dev/null @@ -1,110 +0,0 @@ -package fr.insee.survey.datacollectionmanagement.query.service.impl; - -import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; -import fr.insee.survey.datacollectionmanagement.user.domain.User; -import fr.insee.survey.datacollectionmanagement.user.service.UserService; -import fr.insee.survey.datacollectionmanagement.view.service.ViewService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Optional; - -@Service -@RequiredArgsConstructor -@Slf4j -public class CheckHabilitationServiceImpl implements CheckHabilitationService { - - private final ApplicationConfig applicationConfig; - - private final ViewService viewService; - - private final UserService userService; - - @Override - public ResponseEntity checkHabilitation(String role, String idSu, String campaignId) { - - HabilitationDto resp = new HabilitationDto(); - - //noauth - if (!applicationConfig.getAuthType().equals(AuthConstants.OIDC)) { - resp.setHabilitated(true); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - final Jwt jwt = (Jwt) authentication.getPrincipal(); - List roles = jwt.getClaimAsStringList(applicationConfig.getRoleClaim()); - String idec = jwt.getClaimAsString(applicationConfig.getIdClaim()).toUpperCase(); - - //admin - if (isUserInRole(roles, applicationConfig.getRoleAdmin())) { - log.info("Check habilitation of admin {} for accessing survey-unit {} of campaign {} resulted in true", idec, idSu, campaignId); - resp.setHabilitated(true); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - - //respondents - if (role == null || role.isBlank() || role.equals(Constants.INTERVIEWER)) { - if (isUserInRole(roles, applicationConfig.getRoleRespondent())) { - boolean habilitated = viewService.countViewByIdentifierIdSuCampaignId(idec, idSu, campaignId) != 0; - log.info("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} resulted in {}", idec, idSu, campaignId, habilitated); - resp.setHabilitated(habilitated); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - log.warn("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} - no respondent habilitation found in token - check habilitation: false", idec, idSu, campaignId); - resp.setHabilitated(false); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - - - // internal users - Optional user = userService.findByIdentifier(idec); - if (!role.equals(Constants.REVIEWER)) { - resp.setHabilitated(false); - log.warn("User {} - internal user habilitation not found in token - Check habilitation:false", idec); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - if (isUserInRole(roles, applicationConfig.getRoleInternalUser())) { - if (user.isPresent()) { - String userRole; - //List accreditedSources = new ArrayList<>(); - userRole = user.get().getRole().toString(); - if (userRole.equals(User.UserRoleType.assistance)) { - resp.setHabilitated(false); - log.warn("User '{}' has assistance profile - check habilitation: false", idec); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - resp.setHabilitated(true); - log.warn("User '{}' has {} profile - check habilitation: true", idec, userRole); - return new ResponseEntity<>(resp, HttpStatus.OK); - } - - resp.setHabilitated(false); - log.warn("User '{}' doesn't exists", idec); - return new ResponseEntity<>(resp, HttpStatus.OK); - - - } - - resp.setHabilitated(false); - log.warn("Only '{}' ans '{}' are accepted as a role in query argument", Constants.REVIEWER, Constants.INTERVIEWER); - return new ResponseEntity<>(resp, HttpStatus.OK); - - } - - private boolean isUserInRole(List roles, List role) { - - return role.stream().anyMatch(r -> roles.contains(r)); - } - -} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplNoAuth.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplNoAuth.java new file mode 100644 index 00000000..5f660495 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplNoAuth.java @@ -0,0 +1,21 @@ +package fr.insee.survey.datacollectionmanagement.query.service.impl; + +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +@ConditionalOnExpression("'${fr.insee.datacollectionmanagement.auth.mode}' ne 'OIDC'") +@Slf4j +public class CheckHabilitationServiceImplNoAuth implements CheckHabilitationService { + + @Override + public boolean checkHabilitation(String role, String idSu, String campaignId, AuthUser authUser) { + return true; + } + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java new file mode 100644 index 00000000..550c1e6a --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java @@ -0,0 +1,87 @@ +package fr.insee.survey.datacollectionmanagement.query.service.impl; + +import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; +import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; +import fr.insee.survey.datacollectionmanagement.constants.CheckHabilitationsRoles; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; +import fr.insee.survey.datacollectionmanagement.user.domain.User; +import fr.insee.survey.datacollectionmanagement.user.service.UserService; +import fr.insee.survey.datacollectionmanagement.view.service.ViewService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +@RequiredArgsConstructor +@ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = AuthConstants.OIDC) +@Slf4j +public class CheckHabilitationServiceImplOidc implements CheckHabilitationService { + + private final ApplicationConfig applicationConfig; + + private final ViewService viewService; + + private final UserService userService; + + @Override + public boolean checkHabilitation(String role, String idSu, String campaignId, AuthUser authUser) { + + String userId = authUser.getId().toUpperCase(); + + //admin + if (isUserInRole(authUser.getRoles(), applicationConfig.getRoleAdmin())) { + log.info("Check habilitation of admin {} for accessing survey-unit {} of campaign {} resulted in true", userId, idSu, campaignId); + return true; + } + + //respondents + if (role == null || role.isBlank() || role.equals(CheckHabilitationsRoles.INTERVIEWER)) { + if (isUserInRole(authUser.getRoles(), applicationConfig.getRoleRespondent())) { + boolean habilitated = viewService.countViewByIdentifierIdSuCampaignId(userId.toUpperCase(), idSu, campaignId) != 0; + log.info("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} resulted in {}", userId, idSu, campaignId, habilitated); + return habilitated; + } + log.warn("Check habilitation of interviewer {} for accessing survey-unit {} of campaign {} - no respondent habilitation found in token - check habilitation: false", userId, idSu, campaignId); + return false; + } + + + // internal users + if (!role.equals(CheckHabilitationsRoles.REVIEWER)) { + log.warn("User {} - internal user habilitation not found in token - Check habilitation:false", userId); + return false; + } + + Optional user = userService.findByIdentifier(userId); + if (user.isEmpty()) { + log.warn("User '{}' doesn't exists", userId); + return false; + } + + if (isUserInRole(authUser.getRoles(), applicationConfig.getRoleInternalUser())) { + String userRole = user.get().getRole().toString(); + if (userRole.equals(User.UserRoleType.assistance.toString())) { + log.warn("User '{}' has assistance profile - check habilitation: false", userId); + return false; + } + log.warn("User '{}' has {} profile - check habilitation: true", userId, userRole); + return true; + + + } + log.warn("Only '{}' and '{}' are accepted as a role in query argument", CheckHabilitationsRoles.REVIEWER, CheckHabilitationsRoles.INTERVIEWER); + return false; + + } + + private boolean isUserInRole(List roles, List role) { + + return role.stream().anyMatch(roles::contains); + } + +} From 090c270898ab19c811dcb5d49853c6df3d1101e2 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 16:29:05 +0100 Subject: [PATCH 017/111] refactor: user domain --- .../contact/domain/ContactEvent.java | 2 +- .../user/controller/UserController.java | 48 ++++++++----------- .../user/domain/User.java | 2 +- .../user/domain/UserEvent.java | 2 +- .../user/dto/UserDto.java | 5 +- .../user/repository/UserRepository.java | 4 ++ .../user/service/impl/UserServiceImpl.java | 2 +- .../user/validation/UserRoleValid.java | 26 ++++++++++ .../user/validation/UserRoleValidator.java | 23 +++++++++ 9 files changed, 82 insertions(+), 32 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index 834a3fcd..ffc4b6b5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -22,7 +22,7 @@ public enum ContactEventType { private Long id; private Date eventDate; @NonNull - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.ORDINAL) private ContactEventType type; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index f7fa956a..99e3ae1c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -5,6 +5,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; import fr.insee.survey.datacollectionmanagement.user.domain.User; +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.dto.UserDto; import fr.insee.survey.datacollectionmanagement.user.exception.RoleException; import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; @@ -15,24 +16,23 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.text.ParseException; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -42,20 +42,17 @@ " || @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") @Slf4j +@Validated +@RequiredArgsConstructor public class UserController { + private final UserService userService; - @Autowired - UserService userService; + private final SourceService sourceService; - @Autowired - SourceService sourceService; + private final SourceAccreditationService sourceAccreditationService; - @Autowired - SourceAccreditationService sourceAccreditationService; - - @Autowired - ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for users, paginated") @GetMapping(value = Constants.API_USERS_ALL, produces = "application/json") @@ -80,7 +77,7 @@ public ResponseEntity getUsers( @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity getUser(@PathVariable("id") String id) { - Optional user = userService.findByIdentifier(StringUtils.upperCase(id)); + Optional user = userService.findByIdentifier(id); try { if (user.isPresent()) return ResponseEntity.ok().body(convertToDto(user.get())); @@ -99,7 +96,7 @@ public ResponseEntity getUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = UserDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putUser(@PathVariable("id") String id, @RequestBody UserDto userDto) { + public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto) { if (StringUtils.isBlank(userDto.getIdentifier()) || !userDto.getIdentifier().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and user identifier don't match"); } @@ -113,14 +110,12 @@ public ResponseEntity putUser(@PathVariable("id") String id, @RequestBody Use } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse user"); - } - catch (RoleException e){ + } catch (RoleException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Role not recognized: only [" + Stream.of(User.UserRoleType.values()) .map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); - } - catch (NoSuchElementException e) { + } catch (NoSuchElementException e) { log.info("Creating user with the identifier {}", userDto.getIdentifier()); user = convertToEntityNewContact(userDto); @@ -174,19 +169,17 @@ public ResponseEntity deleteUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity getUserSources(@PathVariable("id") String id){ + public ResponseEntity getUserSources(@PathVariable("id") String id) { Optional user = userService.findByIdentifier(id); if (user.isPresent()) { - List accreditedSources= userService.findAccreditedSources(id); - return ResponseEntity.status(HttpStatus.OK).body(accreditedSources); - } - else { + List accreditedSources = userService.findAccreditedSources(id); + return ResponseEntity.status(HttpStatus.OK).body(accreditedSources); + } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); } } - private User convertToEntity(UserDto userDto) throws ParseException, NoSuchElementException, RoleException { User user = modelMapper.map(userDto, User.class); @@ -194,7 +187,7 @@ private User convertToEntity(UserDto userDto) throws ParseException, NoSuchEleme if (!oldUser.isPresent()) { throw new NoSuchElementException(); } - if(user.getRole()==null){ + if (user.getRole() == null || Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> userDto.getRole().equals(v))) { throw new RoleException("Role missing or not recognized. Only [" + Stream.of(User.UserRoleType.values()).map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); } user.setUserEvents(oldUser.get().getUserEvents()); @@ -211,6 +204,7 @@ private UserDto convertToDto(User user) { UserDto userDto = modelMapper.map(user, UserDto.class); return userDto; } + class UserPage extends PageImpl { private static final long serialVersionUID = 656181199902518234L; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index dbd68e21..3185add9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -20,7 +20,7 @@ public enum UserRoleType { @Id private String identifier; - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.ORDINAL) private UserRoleType role; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index accf0ed5..92a409ce 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -23,7 +23,7 @@ public enum UserEventType { private Date eventDate; @NonNull - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.ORDINAL) private UserEventType type; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java index 169f357e..7f23d455 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java @@ -1,14 +1,17 @@ package fr.insee.survey.datacollectionmanagement.user.dto; +import fr.insee.survey.datacollectionmanagement.user.validation.UserRoleValid; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserDto{ - + @NotBlank private String identifier; + @UserRoleValid private String role; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/UserRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/UserRepository.java index 18a0dcb8..5083ff41 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/UserRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/UserRepository.java @@ -6,7 +6,11 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; +import java.util.Optional; + public interface UserRepository extends PagingAndSortingRepository, JpaRepository { Page findAll(Pageable pageable); + + Optional findByIdentifierIgnoreCase(String identifier); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index 0af3808a..c9682b64 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -35,7 +35,7 @@ public Page findAll(Pageable pageable) { @Override public Optional findByIdentifier(String identifier) { - return userRepository.findById(identifier); + return userRepository.findByIdentifierIgnoreCase(identifier); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java new file mode 100644 index 00000000..c05777c6 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java @@ -0,0 +1,26 @@ +package fr.insee.survey.datacollectionmanagement.user.validation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Target({FIELD, PARAMETER, METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Constraint(validatedBy = UserRoleValidator.class) +public @interface UserRoleValid { + //error message + String message() default "Role missing or not recognized."; + + //represents group of constraints + Class[] groups() default {}; + + //represents additional information about annotation + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java new file mode 100644 index 00000000..f861b35b --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java @@ -0,0 +1,23 @@ +package fr.insee.survey.datacollectionmanagement.user.validation; + +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.Arrays; + +public class UserRoleValidator implements ConstraintValidator { + + + @Override + public void initialize(UserRoleValid constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if(value == null) + return false; + return Arrays.stream(UserEvent.UserEventType.values()).anyMatch( v -> value.equals(v)); + } +} From 0215e3ff26fe2abd15919a31d526c9164dca8a2e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 16:54:09 +0100 Subject: [PATCH 018/111] fix: tests --- .../contact/domain/ContactEvent.java | 1 + .../SourceAccreditationController.java | 16 ++++++---------- .../user/controller/UserController.java | 2 +- .../user/controller/UserEventController.java | 12 +++++------- .../user/domain/SourceAccreditation.java | 9 ++------- .../user/domain/User.java | 15 ++++++++------- .../user/domain/UserEvent.java | 3 ++- src/test/resources/data.sql | 1 + 8 files changed, 26 insertions(+), 33 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index ffc4b6b5..cb3b2836 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -22,6 +22,7 @@ public enum ContactEventType { private Long id; private Date eventDate; @NonNull + @JdbcTypeCode(SqlTypes.INTEGER) @Enumerated(EnumType.ORDINAL) private ContactEventType type; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java index 42e37974..2b92471e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java @@ -16,9 +16,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -38,21 +38,17 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") @Slf4j +@RequiredArgsConstructor public class SourceAccreditationController { - @Autowired - private SourceAccreditationService sourceAccreditationService; + private final SourceAccreditationService sourceAccreditationService; - @Autowired - private SourceService sourceService; + private final SourceService sourceService; - @Autowired - private UserService userService; + private final UserService userService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired private ModelMapper modelMapper; @Operation(summary = "Search for source accreditations by source id") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 99e3ae1c..c02f8948 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -45,7 +45,7 @@ @Validated @RequiredArgsConstructor public class UserController { - + private final UserService userService; private final SourceService sourceService; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java index c358ae1c..f1bdcceb 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java @@ -15,9 +15,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -36,16 +36,14 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Slf4j @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") +@RequiredArgsConstructor public class UserEventController { - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; - @Autowired - UserService userService; + private final UserService userService; - @Autowired - UserEventService userEventService; + private final UserEventService userEventService; @Operation(summary = "Search for userEvents by user's id") @GetMapping(value = Constants.API_USERS_ID_USEREVENTS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java index 541752fd..928294da 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java @@ -6,16 +6,12 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToOne; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; - +import lombok.*; import java.util.Date; @Entity -@Data +@Getter@Setter @NoArgsConstructor public class SourceAccreditation { @@ -29,7 +25,6 @@ public class SourceAccreditation { private String idUser; @OneToOne - @EqualsAndHashCode.Exclude private Source source; @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index 3185add9..70f36195 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -1,14 +1,16 @@ package fr.insee.survey.datacollectionmanagement.user.domain; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.ToString; - import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.JdbcTypeCode; +import org.hibernate.type.SqlTypes; + import java.util.Set; @Entity -@Data +@Getter +@Setter @Table(name = "InternalUsers") public class User { @@ -20,12 +22,11 @@ public enum UserRoleType { @Id private String identifier; + @JdbcTypeCode(SqlTypes.INTEGER) @Enumerated(EnumType.ORDINAL) private UserRoleType role; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set userEvents; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index 92a409ce..5189fcd5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -9,7 +9,7 @@ import java.util.Date; @Entity -@Data +@Getter@Setter @NoArgsConstructor public class UserEvent { @@ -24,6 +24,7 @@ public enum UserEventType { private Date eventDate; @NonNull @Enumerated(EnumType.ORDINAL) + @JdbcTypeCode(SqlTypes.INTEGER) private UserEventType type; @ManyToOne diff --git a/src/test/resources/data.sql b/src/test/resources/data.sql index 9e7aea9e..cf5eb2d3 100644 --- a/src/test/resources/data.sql +++ b/src/test/resources/data.sql @@ -1 +1,2 @@ create domain if not exists jsonb as json; + From 8c91c687f0ad6feb14b02463424c89841c5ecd35 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 17:19:43 +0100 Subject: [PATCH 019/111] refactor: user domain --- .../impl/CheckHabilitationServiceImplOidc.java | 2 +- .../SourceAccreditationController.java | 15 +++++++++------ .../user/controller/UserController.java | 7 ++++--- .../user/domain/User.java | 2 +- .../user/domain/UserEvent.java | 5 ++--- .../user/dto/SourceAccreditationDto.java | 3 ++- .../SourceAccreditationRepository.java | 2 +- .../impl/SourceAccreditationServiceImpl.java | 6 +++--- .../user/service/impl/UserEventServiceImpl.java | 6 +++--- .../user/service/impl/UserServiceImpl.java | 16 +++++++--------- 10 files changed, 33 insertions(+), 31 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java index 550c1e6a..d9465825 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java @@ -65,7 +65,7 @@ public boolean checkHabilitation(String role, String idSu, String campaignId, Au if (isUserInRole(authUser.getRoles(), applicationConfig.getRoleInternalUser())) { String userRole = user.get().getRole().toString(); - if (userRole.equals(User.UserRoleType.assistance.toString())) { + if (userRole.equals(User.UserRoleType.ASSISTANCE.toString())) { log.warn("User '{}' has assistance profile - check habilitation: false", userId); return false; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java index 2b92471e..f5da2b89 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java @@ -16,6 +16,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -24,6 +25,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -39,17 +41,18 @@ @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") @Slf4j @RequiredArgsConstructor +@Validated public class SourceAccreditationController { - private final SourceAccreditationService sourceAccreditationService; + private final SourceAccreditationService sourceAccreditationService; - private final SourceService sourceService; + private final SourceService sourceService; - private final UserService userService; + private final UserService userService; - private final ViewService viewService; + private final ViewService viewService; - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for source accreditations by source id") @GetMapping(value = Constants.API_SOURCE_ID_SOURCE_ACCREDITATIONS, produces = "application/json") @@ -84,7 +87,7 @@ public ResponseEntity getSourceAccreditation(@PathVariable("id") String id) { }) @Transactional public ResponseEntity postSourceAccreditation(@PathVariable("id") String id, - @RequestBody SourceAccreditationDto sourceAccreditationDto) { + @RequestBody @Valid SourceAccreditationDto sourceAccreditationDto) { Optional optSource = null; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index c02f8948..45e7c142 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -183,13 +183,14 @@ public ResponseEntity getUserSources(@PathVariable("id") String id) { private User convertToEntity(UserDto userDto) throws ParseException, NoSuchElementException, RoleException { User user = modelMapper.map(userDto, User.class); + if (user.getRole() == null || Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> userDto.getRole().equals(v))) { + throw new RoleException("Role missing or not recognized. Only [" + Stream.of(User.UserRoleType.values()).map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); + } + Optional oldUser = userService.findByIdentifier(userDto.getIdentifier()); if (!oldUser.isPresent()) { throw new NoSuchElementException(); } - if (user.getRole() == null || Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> userDto.getRole().equals(v))) { - throw new RoleException("Role missing or not recognized. Only [" + Stream.of(User.UserRoleType.values()).map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); - } user.setUserEvents(oldUser.get().getUserEvents()); return user; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index 70f36195..a674fe6d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -15,7 +15,7 @@ public class User { public enum UserRoleType { - responsable, gestionnaire, assistance + RESPONSABLE, GESTIONNAIRE, ASSISTANCE } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index 5189fcd5..e8c9ca4f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -14,7 +14,7 @@ public class UserEvent { public enum UserEventType { - create, update, delete + CREATE, UPDATE, DELETE } @Id @@ -22,14 +22,13 @@ public enum UserEventType { private Long id; private Date eventDate; + @NonNull @Enumerated(EnumType.ORDINAL) @JdbcTypeCode(SqlTypes.INTEGER) private UserEventType type; @ManyToOne - @EqualsAndHashCode.Exclude - @ToString.Exclude private User user; @JdbcTypeCode(SqlTypes.JSON) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java index 64fd5ec9..5cc3b2f6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -13,9 +14,9 @@ public class SourceAccreditationDto { @JsonIgnore private Long id; - private Date creationDate; private String creationAuthor; + @NotBlank private String idUser; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/SourceAccreditationRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/SourceAccreditationRepository.java index b186c3c8..56313733 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/SourceAccreditationRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/repository/SourceAccreditationRepository.java @@ -7,5 +7,5 @@ public interface SourceAccreditationRepository extends JpaRepository { - public List findByIdUser(String idUser); + List findByIdUser(String idUser); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java index d40c4ec3..893c0aca 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java @@ -3,7 +3,7 @@ import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; import fr.insee.survey.datacollectionmanagement.user.repository.SourceAccreditationRepository; import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -12,10 +12,10 @@ import java.util.Optional; @Service +@RequiredArgsConstructor public class SourceAccreditationServiceImpl implements SourceAccreditationService { - @Autowired - private SourceAccreditationRepository sourceAccreditationRepository; + private final SourceAccreditationRepository sourceAccreditationRepository; public List findByUserIdentifier(String id) { return sourceAccreditationRepository.findByIdUser(id); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java index 49f0254c..cc42675f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java @@ -6,7 +6,7 @@ import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.repository.UserEventRepository; import fr.insee.survey.datacollectionmanagement.user.service.UserEventService; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -16,10 +16,10 @@ import java.util.Set; @Service +@RequiredArgsConstructor public class UserEventServiceImpl implements UserEventService { - @Autowired - private UserEventRepository userEventRepository; + private final UserEventRepository userEventRepository; @Override public Page findAll(Pageable pageable) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index c9682b64..c4613fc0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -9,7 +9,7 @@ import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; import fr.insee.survey.datacollectionmanagement.user.service.UserEventService; import fr.insee.survey.datacollectionmanagement.user.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -17,16 +17,14 @@ import java.util.*; @Service +@RequiredArgsConstructor public class UserServiceImpl implements UserService { - @Autowired - UserEventService userEventService; + private final UserEventService userEventService; - @Autowired - UserRepository userRepository; + private final UserRepository userRepository; - @Autowired - SourceAccreditationService sourceAccreditationService; + private final SourceAccreditationService sourceAccreditationService; @Override public Page findAll(Pageable pageable) { @@ -52,7 +50,7 @@ public void deleteUser(String identifier) { @Override public User createUserEvent(User user, JsonNode payload) { - UserEvent newUserEvent = userEventService.createUserEvent(user, UserEvent.UserEventType.create, + UserEvent newUserEvent = userEventService.createUserEvent(user, UserEvent.UserEventType.CREATE, payload); user.setUserEvents(new HashSet<>(Arrays.asList(newUserEvent))); return saveUser(user); @@ -64,7 +62,7 @@ public User updateUserEvent(User user, JsonNode payload) { User existingUser = findByIdentifier(user.getIdentifier()).get(); Set setUserEventsUser = existingUser.getUserEvents(); - UserEvent userEventUpdate = userEventService.createUserEvent(user, UserEvent.UserEventType.update, + UserEvent userEventUpdate = userEventService.createUserEvent(user, UserEvent.UserEventType.UPDATE, payload); setUserEventsUser.add(userEventUpdate); user.setUserEvents(setUserEventsUser); From 26041ca62304bc423fcaed946700d655393be01c Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 13:44:27 +0100 Subject: [PATCH 020/111] refator: remove Autowired --- pom.xml | 5 +- .../config/CorsGlobalConfig.java | 6 +- .../config/LogInterceptor.java | 14 ++--- .../config/OpenAPIConfiguration.java | 10 ++-- .../config/WebConfig.java | 9 ++- .../auth/security/DefaultSecurityContext.java | 4 +- .../OpenIDConnectSecurityContext.java | 10 +--- .../auth/user/AuthorizeMethodDecider.java | 9 ++- .../contact/controller/AddressController.java | 12 ++-- .../contact/controller/ContactController.java | 25 ++++---- .../controller/ContactEventController.java | 12 ++-- .../service/impl/AddressServiceImpl.java | 20 +++---- .../service/impl/ContactEventServiceImpl.java | 22 ++++--- .../service/impl/ContactServiceImpl.java | 12 ++-- .../controller/CampaignController.java | 22 +++---- .../controller/MetadataController.java | 24 +++----- .../metadata/controller/OwnerController.java | 9 ++- .../controller/PartitioningController.java | 15 ++--- .../metadata/controller/SourceController.java | 21 +++---- .../controller/SupportController.java | 8 +-- .../metadata/controller/SurveyController.java | 20 +++---- .../repository/CampaignRepository.java | 5 +- .../service/impl/CampaignServiceImpl.java | 9 ++- .../service/impl/OwnerServiceImpl.java | 17 +++--- .../service/impl/PartioningServiceImpl.java | 15 +++-- .../service/impl/SourceServiceImpl.java | 23 ++++---- .../service/impl/SupportServiceImpl.java | 17 +++--- .../service/impl/SurveyServiceImpl.java | 23 ++++---- .../CheckHabilitationController.java | 10 ++-- .../controller/MonitoringController.java | 17 ++---- .../query/controller/MoogController.java | 20 ++----- .../controller/MyQuestioningsController.java | 11 ++-- .../QuestioningAccreditationController.java | 21 +++---- .../controller/QuestioningController.java | 15 ++--- .../controller/SearchContactController.java | 45 +++++++------- .../query/controller/WebclientController.java | 46 +++++---------- .../repository/MonitoringRepository.java | 17 +++--- .../query/repository/MoogRepository.java | 23 +++----- .../service/impl/MonitoringServiceImpl.java | 15 +++-- .../query/service/impl/MoogServiceImpl.java | 25 +++----- .../service/impl/MySurveysServiceImpl.java | 15 ++--- .../impl/SearchContactServiceImpl.java | 15 ++--- .../QuestioningEventController.java | 15 ++--- .../controller/SurveyUnitController.java | 10 ++-- .../controller/UploadController.java | 12 ++-- .../service/impl/EventOrderServiceImpl.java | 6 +- .../QuestioningAccreditationServiceImpl.java | 23 ++++---- .../impl/QuestioningEventServiceImpl.java | 9 ++- .../service/impl/QuestioningServiceImpl.java | 31 +++++----- .../service/impl/SurveyUnitServiceImpl.java | 22 ++++--- .../service/impl/UploadServiceImpl.java | 16 +++-- .../util/LastQuestioningEventComparator.java | 13 ++--- .../SourceAccreditationController.java | 2 +- .../user/dto/SourceAccreditationDto.java | 3 +- .../user/dto/UserEventDto.java | 3 + .../user/validation/UserEventTypeValid.java | 26 +++++++++ .../validation/UserEventTypeValidator.java | 23 ++++++++ .../user/validation/UserRoleValid.java | 2 +- .../user/validation/UserRoleValidator.java | 4 +- .../util/Dataloader.java | 58 +++++++------------ .../util/DataloaderPoc.java | 57 +++++++----------- .../view/serviceImpl/ViewServiceImpl.java | 13 ++--- .../controller/CampaignControllerTest.java | 9 +-- .../controller/SourceControllerTest.java | 6 +- 64 files changed, 464 insertions(+), 592 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValid.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java diff --git a/pom.xml b/pom.xml index eb154aba..fbe316a4 100644 --- a/pom.xml +++ b/pom.xml @@ -29,11 +29,14 @@ org.springframework.boot spring-boot-starter-tomcat - org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-validation + org.modelmapper modelmapper diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java index d2883454..928fec41 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java @@ -1,6 +1,6 @@ package fr.insee.survey.datacollectionmanagement.config; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; @@ -9,10 +9,10 @@ @Configuration @EnableWebMvc +@RequiredArgsConstructor public class CorsGlobalConfig { - @Autowired - ApplicationConfig applicationConfig; + private final ApplicationConfig applicationConfig; @Bean public WebMvcConfigurer corsConfigurer() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java index 82601354..4a8d7a32 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/LogInterceptor.java @@ -6,9 +6,9 @@ import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.logging.log4j.ThreadContext; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @@ -19,14 +19,12 @@ @Component @Slf4j +@RequiredArgsConstructor public class LogInterceptor implements HandlerInterceptor { - @Autowired - ApplicationConfig applicationConfig; - - @Autowired - UserProvider userProvider; + private final ApplicationConfig applicationConfig; + private final UserProvider userProvider; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { @@ -41,7 +39,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons case AuthConstants.OIDC: Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); AuthUser currentAuthUser = userProvider.getUser(authentication); - userId=(currentAuthUser !=null && currentAuthUser.getId()!=null ? currentAuthUser.getId() : "anonymous"); + userId = (currentAuthUser != null && currentAuthUser.getId() != null ? currentAuthUser.getId() : "anonymous"); ThreadContext.put("user", userId.toUpperCase()); break; default: @@ -54,7 +52,7 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons ThreadContext.put("method", method); - log.info("["+userId.toUpperCase()+"] - ["+method+"] - ["+operationPath+"]"); + log.info("[" + userId.toUpperCase() + "] - [" + method + "] - [" + operationPath + "]"); return true; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java index 82f5fe3c..8f907222 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/OpenAPIConfiguration.java @@ -6,7 +6,7 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.*; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.info.BuildProperties; import org.springframework.context.annotation.Bean; @@ -17,14 +17,12 @@ @Configuration @ConditionalOnProperty(name = "springdoc.swagger-ui.enabled", havingValue = "true", matchIfMissing = true) - +@RequiredArgsConstructor public class OpenAPIConfiguration { - @Autowired - BuildProperties buildProperties; + private final BuildProperties buildProperties; - @Autowired - ApplicationConfig applicationConfig; + private final ApplicationConfig applicationConfig; @Bean public OpenAPI customOpenAPI() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/WebConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/WebConfig.java index 87862586..e7489bff 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/WebConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/WebConfig.java @@ -1,13 +1,20 @@ package fr.insee.survey.datacollectionmanagement.config; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; +import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration +@RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { + private final ApplicationConfig applicationConfig; + + private final UserProvider userProvider; + @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.myLogInterceptor()); @@ -16,7 +23,7 @@ public void addInterceptors(InterceptorRegistry registry) { @Bean public LogInterceptor myLogInterceptor() { - return new LogInterceptor(); + return new LogInterceptor(applicationConfig,userProvider); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java index 7379971d..4021787f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/DefaultSecurityContext.java @@ -4,7 +4,6 @@ import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import lombok.AllArgsConstructor; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -28,8 +27,7 @@ public class DefaultSecurityContext { private final PublicSecurityFilterChain publicSecurityFilterChainConfiguration; - @Autowired - ApplicationConfig config; + private final ApplicationConfig config; /** * Configure spring security filter chain when no authentication * @param http Http Security Object diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java index 45576460..491d772d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/security/OpenIDConnectSecurityContext.java @@ -5,9 +5,8 @@ import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import fr.insee.survey.datacollectionmanagement.constants.Constants; -import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -35,21 +34,18 @@ @EnableMethodSecurity @ConditionalOnProperty(name = "fr.insee.datacollectionmanagement.auth.mode", havingValue = AuthConstants.OIDC) @Slf4j -@AllArgsConstructor +@RequiredArgsConstructor public class OpenIDConnectSecurityContext { - private final PublicSecurityFilterChain publicSecurityFilterChainConfiguration; - @Autowired - ApplicationConfig config; + private final ApplicationConfig config; @Bean @Order(2) protected SecurityFilterChain configure(HttpSecurity http) throws Exception { return http .securityMatcher("/**") - //.addFilterAfter(new UserToMdcFilter(getUserProvider(config)), AuthorizationFilter.class) .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .headers(headers -> headers diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java index 5ff9e4c6..4b0ce74d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/auth/user/AuthorizeMethodDecider.java @@ -2,8 +2,8 @@ import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; @@ -13,17 +13,16 @@ @Component("AuthorizeMethodDecider") @Slf4j +@RequiredArgsConstructor public class AuthorizeMethodDecider { public static final String ROLE_OFFLINE_ACCESS = "ROLE_offline_access"; public static final String ROLE_UMA_AUTHORIZATION = "ROLE_uma_authorization"; private AuthUser noAuthUser; - @Autowired - private UserProvider userProvider; + private final UserProvider userProvider; - @Autowired - ApplicationConfig config; + private final ApplicationConfig config; public AuthUser getUser() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index e3a9caee..d720d5be 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -16,8 +16,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -36,16 +36,14 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") @Slf4j +@RequiredArgsConstructor public class AddressController { - @Autowired - private AddressService addressService; + private final AddressService addressService; - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private ContactEventService contactEventService; + private final ContactEventService contactEventService; @Operation(summary = "Search for a contact address by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_ADDRESS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index da9e8394..84f07a57 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -18,10 +18,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -43,25 +43,20 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") @Slf4j +@RequiredArgsConstructor public class ContactController { - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private AddressService addressService; + private final AddressService addressService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - private QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for contacts, paginated") @GetMapping(value = Constants.API_CONTACTS_ALL, produces = "application/json") @@ -124,7 +119,7 @@ public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody try { contact = convertToEntity(contactDto); - } catch (ParseException e) { + } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse contact"); } catch (NoSuchElementException e) { log.info("Creating contact with the identifier {}", contactDto.getIdentifier()); @@ -207,7 +202,7 @@ private Contact convertToEntity(ContactDto contactDto) throws ParseException, No private Contact convertToEntityNewContact(ContactDto contactDto) { Contact contact = modelMapper.map(contactDto, Contact.class); contact.setGender(contactDto.getCivility()); - return contact; + return contact; } class ContactPage extends PageImpl { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index fa543cf6..5e4e6734 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -15,8 +15,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -37,16 +37,14 @@ + "|| @AuthorizeMethodDecider.isWebClient() "+ "|| @AuthorizeMethodDecider.isRespondent() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") +@RequiredArgsConstructor public class ContactEventController { - @Autowired - private ContactEventService contactEventService; + private final ContactEventService contactEventService; - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for contactEvents by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_CONTACTEVENTS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java index c52249d8..dd623268 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java @@ -1,26 +1,24 @@ package fr.insee.survey.datacollectionmanagement.contact.service.impl; -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.contact.domain.Address; +import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; +import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; +import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; +import lombok.RequiredArgsConstructor; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import fr.insee.survey.datacollectionmanagement.contact.domain.Address; -import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; -import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; -import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; +import java.util.Optional; @Service +@RequiredArgsConstructor public class AddressServiceImpl implements AddressService { - @Autowired - AddressRepository addressRepository; + private final AddressRepository addressRepository; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Override public Optional
findById(Long id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java index e5c55149..35775827 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java @@ -1,27 +1,25 @@ package fr.insee.survey.datacollectionmanagement.contact.service.impl; -import java.util.Date; -import java.util.Optional; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import com.fasterxml.jackson.databind.JsonNode; - import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.Optional; +import java.util.Set; @Service +@RequiredArgsConstructor public class ContactEventServiceImpl implements ContactEventService { - @Autowired - private ContactEventRepository contactEventRepository; + private final ContactEventRepository contactEventRepository; @Override public Page findAll(Pageable pageable) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 5fea711b..053b88bb 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -8,8 +8,8 @@ import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -17,16 +17,14 @@ import java.util.*; @Service +@RequiredArgsConstructor public class ContactServiceImpl implements ContactService { - @Autowired - private ContactRepository contactRepository; + private final ContactRepository contactRepository; - @Autowired - private AddressService addressService; + private final AddressService addressService; - @Autowired - private ContactEventService contactEventService; + private final ContactEventService contactEventService; @Override public Page findAll(Pageable pageable) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index a727fa9d..584b4a47 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -21,10 +21,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -47,25 +47,21 @@ @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j @Validated +@RequiredArgsConstructor public class CampaignController { - @Autowired - private CampaignService campaignService; + private final CampaignService campaignService; - @Autowired - private SurveyService surveyService; + private final SurveyService surveyService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private ModelMapper modelmapper; + private final QuestioningService questioningService; - @Autowired - private QuestioningService questioningService; + private final UploadService uploadService; + + private final ModelMapper modelmapper; - @Autowired - UploadService uploadService; @Operation(summary = "Search for campaigns, paginated") @GetMapping(value = Constants.API_CAMPAIGNS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java index 477ad481..ad8494b1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java @@ -1,25 +1,18 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; +import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignDto; -import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; -import fr.insee.survey.datacollectionmanagement.query.domain.MoogCampaign; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.*; - -import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; +import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; import java.util.Date; -import java.util.List; import java.util.Optional; @RestController @@ -28,13 +21,12 @@ @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") +@RequiredArgsConstructor public class MetadataController { - @Autowired - CampaignService campaignService; + private final CampaignService campaignService; - @Autowired - PartitioningService partitioningService; + private final PartitioningService partitioningService; @GetMapping(value = Constants.MOOG_API_CAMPAIGNS) public JSONCollectionWrapper displayCampaignInProgress() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index d8ba0e1f..9f848953 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -10,9 +10,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -31,13 +31,12 @@ + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") +@RequiredArgsConstructor public class OwnerController { - @Autowired - private ModelMapper modelmapper; + private final ModelMapper modelmapper; - @Autowired - private OwnerService ownerService; + private final OwnerService ownerService; @Operation(summary = "Search for owners, paginated") @GetMapping(value = Constants.API_OWNERS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index 82e7243b..ff5ff1e8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -14,10 +14,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -37,19 +37,16 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j +@RequiredArgsConstructor public class PartitioningController { - @Autowired - private PartitioningService partitioningService; + private final PartitioningService partitioningService; - @Autowired - private CampaignService campaignService; + private final CampaignService campaignService; - @Autowired - private ModelMapper modelmapper; + private final ModelMapper modelmapper; - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; @Operation(summary = "Search for partitionings by the campaign id") @GetMapping(value = Constants.API_CAMPAIGNS_ID_PARTITIONINGS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index f06421a6..b4ca8fc9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -19,10 +19,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -42,25 +42,20 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j +@RequiredArgsConstructor public class SourceController { - @Autowired - private SourceService sourceService; + private final SourceService sourceService; - @Autowired - private OwnerService ownerService; + private final OwnerService ownerService; - @Autowired - private SupportService supportService; + private final SupportService supportService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private ModelMapper modelmapper; + private final ModelMapper modelmapper; - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; @Operation(summary = "Search for sources, paginated") @GetMapping(value = Constants.API_SOURCES, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index 993535d2..aaaf3e9a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -10,6 +10,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; @@ -31,13 +32,12 @@ + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") +@RequiredArgsConstructor public class SupportController { - @Autowired - private ModelMapper modelmapper; + private final ModelMapper modelmapper; - @Autowired - private SupportService supportService; + private final SupportService supportService; @Operation(summary = "Search for supports, paginated") @GetMapping(value = Constants.API_SUPPORTS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 8959061c..db50a36d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -17,10 +17,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -41,22 +41,18 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j +@RequiredArgsConstructor public class SurveyController { - @Autowired - private SurveyService surveyService; + private final SurveyService surveyService; - @Autowired - private SourceService sourceService; + private final SourceService sourceService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private ModelMapper modelmapper; - - @Autowired - private QuestioningService questioningService; + private final ModelMapper modelmapper; + + private final QuestioningService questioningService; @Operation(summary = "Search for surveys by the source id") @GetMapping(value = Constants.API_SOURCES_ID_SURVEYS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/CampaignRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/CampaignRepository.java index b833760f..fb747c4d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/CampaignRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/CampaignRepository.java @@ -1,12 +1,11 @@ package fr.insee.survey.datacollectionmanagement.metadata.repository; -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; +import java.util.List; public interface CampaignRepository extends JpaRepository,PagingAndSortingRepository { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java index f3680ba8..815c249e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java @@ -7,8 +7,8 @@ import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -17,13 +17,12 @@ @Service @Slf4j +@RequiredArgsConstructor public class CampaignServiceImpl implements CampaignService { - @Autowired - CampaignRepository campaignRepository; + private final CampaignRepository campaignRepository; - @Autowired - PartitioningService partitioningService; + private final PartitioningService partitioningService; public Collection getCampaigns() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java index 3fa113d7..659bf6ce 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java @@ -1,24 +1,23 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Optional; @Service @Slf4j +@RequiredArgsConstructor public class OwnerServiceImpl implements OwnerService { - @Autowired - private OwnerRepository ownerRepository; + private final OwnerRepository ownerRepository; public Optional findById(String owner) { return ownerRepository.findById(owner); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java index 2ed08dc2..e964adf6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java @@ -1,22 +1,21 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.Date; -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.repository.PartitioningRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.Optional; @Service @Slf4j +@RequiredArgsConstructor public class PartioningServiceImpl implements PartitioningService { - @Autowired - private PartitioningRepository partitioningRepository; + private final PartitioningRepository partitioningRepository; @Override public Optional findById(String id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java index d4b140b0..244b34a3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java @@ -1,28 +1,25 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; -import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; -import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; @Service @Slf4j +@RequiredArgsConstructor public class SourceServiceImpl implements SourceService { - @Autowired - private SourceRepository sourceRepository; + private final SourceRepository sourceRepository; public Optional findById(String source) { return sourceRepository.findById(source); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java index caa36f95..b9cbe718 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java @@ -1,24 +1,23 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Optional; @Service @Slf4j +@RequiredArgsConstructor public class SupportServiceImpl implements SupportService { - @Autowired - private SupportRepository supportRepository; + private final SupportRepository supportRepository; public Optional findById(String support) { return supportRepository.findById(support); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java index 62b3b98c..f088daad 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java @@ -1,27 +1,26 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; @Service @Slf4j +@RequiredArgsConstructor public class SurveyServiceImpl implements SurveyService { - @Autowired - private SurveyRepository surveyRepository; + private final SurveyRepository surveyRepository; @Override public List findByYear(int year) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java index 35641a47..aa7b368a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationController.java @@ -6,7 +6,7 @@ import fr.insee.survey.datacollectionmanagement.query.dto.HabilitationDto; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -18,14 +18,12 @@ @RestController @Tag(name = "4 - Cross domain") +@RequiredArgsConstructor public class CheckHabilitationController { + private final CheckHabilitationService checkHabilitationService; - @Autowired - private CheckHabilitationService checkHabilitationService; - - @Autowired - UserProvider userProvider; + private final UserProvider userProvider; @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java index 6b7dd8a8..ef6897e9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java @@ -4,14 +4,12 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; -import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.dto.MoogFollowUpDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogProgressDto; import fr.insee.survey.datacollectionmanagement.query.service.MonitoringService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -26,19 +24,12 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "5 - Moog", description = "Enpoints for moog") @Slf4j +@RequiredArgsConstructor public class MonitoringController { - @Autowired - MonitoringService monitoringService; + private final MonitoringService monitoringService; - @Autowired - QuestioningService questioningService; - - @Autowired - PartitioningService partitioningService; - - @Autowired - CampaignService campaignService; + private final CampaignService campaignService; @GetMapping(value = "/api/moog/campaigns/{idCampaign}/monitoring/progress", produces = "application/json") public JSONCollectionWrapper getDataForProgress(@PathVariable String idCampaign) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java index 059a4215..bcc9f8b7 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java @@ -9,9 +9,6 @@ import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogSearchDto; import fr.insee.survey.datacollectionmanagement.query.service.MoogService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; -import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -20,8 +17,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; @@ -44,22 +41,13 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "5 - Moog", description = "Enpoints for moog") @Slf4j +@RequiredArgsConstructor public class MoogController { - - @Autowired - private MoogService moogService; - @Autowired - private ContactService contactService; + private final MoogService moogService; - @Autowired - QuestioningEventService questioningEventService; + private final ContactService contactService; - @Autowired - QuestioningService questioningService; - - @Autowired - UploadService uploadService; @GetMapping(path = Constants.API_MOOG_SEARCH) public ResponseEntity moogSearch(@RequestParam(required = false) String filter1, diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java index 41eea61b..0c5bc1df 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsController.java @@ -6,7 +6,7 @@ import fr.insee.survey.datacollectionmanagement.query.dto.MyQuestioningDto; import fr.insee.survey.datacollectionmanagement.query.service.MySurveysService; import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -18,13 +18,12 @@ @RestController @Tag(name = "4 - Cross domain") +@RequiredArgsConstructor public class MyQuestioningsController { - @Autowired - private MySurveysService mySurveysService; + private final MySurveysService mySurveysService; - @Autowired - ApplicationConfig config; + private final ApplicationConfig config; @GetMapping(value = Constants.API_MY_QUESTIONINGS_ID) @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -33,7 +32,7 @@ public class MyQuestioningsController { + "|| @AuthorizeMethodDecider.isAdmin() ") public List findById() { - String idec=null; + String idec; if (config.getAuthType().equals(AuthConstants.OIDC)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java index c175f205..d8c6be3f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java @@ -17,9 +17,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -38,25 +38,20 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") @Slf4j +@RequiredArgsConstructor public class QuestioningAccreditationController { - @Autowired - private QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private PartitioningService partitioningService; + private final PartitioningService partitioningService; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for questioning accreditations by questioning id") @GetMapping(value = Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java index 0a56a6e4..b5c87896 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java @@ -14,10 +14,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -33,19 +33,16 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Slf4j @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") +@RequiredArgsConstructor public class QuestioningController { - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - private SurveyUnitService surveyUnitService; + private final SurveyUnitService surveyUnitService; - @Autowired - private PartitioningService partitioningService; + private final PartitioningService partitioningService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for a questioning by id") @GetMapping(value = Constants.API_QUESTIONINGS_ID, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 059e22a0..30a015e2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -1,23 +1,5 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; @@ -35,7 +17,24 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -43,16 +42,14 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "4 - Cross domain") @Slf4j +@RequiredArgsConstructor public class SearchContactController { - @Autowired - private SearchContactService searchContactService; + private final SearchContactService searchContactService; - @Autowired - private QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - private PartitioningService partitioningService; + private final PartitioningService partitioningService; @GetMapping(path = Constants.API_CONTACTS_SEARCH, produces = "application/json") @Operation(summary = "Multi-criteria search contacts") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index e159b531..2d5ebf45 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; @@ -33,10 +32,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -53,49 +52,36 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Slf4j @Tag(name = "6 - Webclients", description = "Enpoints for webclients") +@RequiredArgsConstructor public class WebclientController { - @Autowired - QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - SurveyUnitService surveyUnitService; + private final SurveyUnitService surveyUnitService; - @Autowired - PartitioningService partitioningService; + private final PartitioningService partitioningService; - @Autowired - SourceService sourceService; + private final SourceService sourceService; - @Autowired - SurveyService surveyService; + private final SurveyService surveyService; - @Autowired - CampaignService campaignService; + private final CampaignService campaignService; - @Autowired - OwnerService ownerService; + private final OwnerService ownerService; - @Autowired - SupportService supportService; + private final SupportService supportService; - @Autowired - ContactService contactService; + private final ContactService contactService; - @Autowired - AddressService addressService; + private final AddressService addressService; - @Autowired - ViewService viewService; + private final ViewService viewService; - @Autowired - QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Create or update questioning for webclients - Returns the questioning and all its accreditations") @PutMapping(value = Constants.API_WEBCLIENT_QUESTIONINGS, produces = "application/json", consumes = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MonitoringRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MonitoringRepository.java index 6959780b..dd8b836c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MonitoringRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MonitoringRepository.java @@ -1,22 +1,21 @@ package fr.insee.survey.datacollectionmanagement.query.repository; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; +import fr.insee.survey.datacollectionmanagement.query.dto.MoogFollowUpDto; +import fr.insee.survey.datacollectionmanagement.query.dto.MoogRowProgressDto; +import lombok.RequiredArgsConstructor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; -import fr.insee.survey.datacollectionmanagement.query.dto.MoogFollowUpDto; -import fr.insee.survey.datacollectionmanagement.query.dto.MoogRowProgressDto; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; @Repository +@RequiredArgsConstructor public class MonitoringRepository { - @Autowired - JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; final String progressQuery = "SELECT COUNT(survey_unit_id_su) as total,status,batch_num FROM\n" + "(SELECT DISTINCT ON (survey_unit_id_su) survey_unit_id_su,status,event_order,batch_num FROM (SELECT event_order, campaign_id, C.status, batch_num, survey_unit_id_su FROM (SELECT campaign_id, type as status, id_partitioning as batch_num, survey_unit_id_su FROM\n" + diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java index aac44099..b1eb2c1f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java @@ -1,31 +1,26 @@ package fr.insee.survey.datacollectionmanagement.query.repository; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.Collection; -import java.util.List; -import java.util.Optional; - import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; -import fr.insee.survey.datacollectionmanagement.contact.service.impl.AddressServiceImpl; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; +import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; +import lombok.RequiredArgsConstructor; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; -import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; @Repository +@RequiredArgsConstructor public class MoogRepository { - @Autowired - JdbcTemplate jdbcTemplate; + private final JdbcTemplate jdbcTemplate; - @Autowired - AddressService addressService; + private final AddressService addressService; final String getEventsQuery = "SELECT qe.id, date, type, survey_unit_id_su, campaign_id " + " FROM questioning_event qe join questioning q on qe.questioning_id=q.id join partitioning p on q.id_partitioning=p.id " diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MonitoringServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MonitoringServiceImpl.java index 7b3502d3..e02d7fee 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MonitoringServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MonitoringServiceImpl.java @@ -1,23 +1,22 @@ package fr.insee.survey.datacollectionmanagement.query.service.impl; -import java.util.HashMap; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.config.JSONCollectionWrapper; import fr.insee.survey.datacollectionmanagement.query.dto.MoogFollowUpDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogProgressDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogRowProgressDto; import fr.insee.survey.datacollectionmanagement.query.repository.MonitoringRepository; import fr.insee.survey.datacollectionmanagement.query.service.MonitoringService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.List; @Service +@RequiredArgsConstructor public class MonitoringServiceImpl implements MonitoringService { - @Autowired - MonitoringRepository monitoringRepository; + private final MonitoringRepository monitoringRepository; @Override public JSONCollectionWrapper getProgress(String idCampaign) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java index bbf38186..64f60c44 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java @@ -8,7 +8,6 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; -import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.domain.MoogCampaign; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; @@ -19,38 +18,30 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service @Slf4j +@RequiredArgsConstructor public class MoogServiceImpl implements MoogService { public static final String READONLY_QUESTIONNAIRE = "/readonly/questionnaire/"; public static final String UNITE_ENQUETEE = "/unite-enquetee/"; - @Autowired - private ViewService viewService; + private final ViewService viewService; - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private CampaignService campaignService; + private final CampaignService campaignService; - @Autowired - private MoogRepository moogRepository; + private final MoogRepository moogRepository; - @Autowired - QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - PartitioningService partitioningService; - - @Autowired - ApplicationConfig applicationConfig; + private final ApplicationConfig applicationConfig; @Override public List moogSearch(String field) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java index 927dcb21..95dbff83 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java @@ -12,8 +12,8 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Timestamp; @@ -23,19 +23,16 @@ @Service @Slf4j +@RequiredArgsConstructor public class MySurveysServiceImpl implements MySurveysService { - @Autowired - private QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - private PartitioningService partitioningService; + private final PartitioningService partitioningService; - @Autowired - private QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - QuestioningService questioningService; + private final QuestioningService questioningService; @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 0e376061..8086bf4e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -11,8 +11,8 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import lombok.EqualsAndHashCode; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -21,20 +21,17 @@ @Service @EqualsAndHashCode +@RequiredArgsConstructor public class SearchContactServiceImpl implements SearchContactService { - @Autowired - private ContactService contactService; + private final ContactService contactService; - @Autowired - private SurveyUnitService surveyUnitService; + private final SurveyUnitService surveyUnitService; - @Autowired - private CampaignService campaignService; + private final CampaignService campaignService; - @Autowired @EqualsAndHashCode.Exclude - private ViewService viewService;; + private final ViewService viewService;; @Override public List searchContactCrossDomain( diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java index 15c98dda..c5f94c86 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java @@ -16,9 +16,9 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -40,19 +40,16 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") @Slf4j +@RequiredArgsConstructor public class QuestioningEventController { - @Autowired - private QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - private QuestioningService questioningService; + private final QuestioningService questioningService; - @Autowired - UploadService uploadService; + private final UploadService uploadService; - @Autowired - private ModelMapper modelMapper; + private final ModelMapper modelMapper; @Operation(summary = "Search for a questioning event by questioning id") @GetMapping(value = Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index a326be4b..d60db240 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -10,10 +10,10 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -32,13 +32,11 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") @Slf4j +@RequiredArgsConstructor public class SurveyUnitController { - @Autowired - private SurveyUnitService surveyUnitService; - - @Autowired - private ModelMapper modelMapper; + private final SurveyUnitService surveyUnitService; + private final ModelMapper modelMapper; @Operation(summary = "Search for a survey units, paginated") @GetMapping(value = Constants.API_SURVEY_UNITS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java index 3e5ef5fc..e4cf778e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java @@ -11,8 +11,8 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -27,16 +27,14 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "5 - Moog", description = "Enpoints for moog") @Slf4j +@RequiredArgsConstructor public class UploadController { - @Autowired - UploadService moogUploadService; + private final UploadService moogUploadService; - @Autowired - QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - QuestioningService questioningService; + private final QuestioningService questioningService; @DeleteMapping(value = Constants.MOOG_API_UPLOADS_ID) public ResponseEntity deleteOneUpload(@PathVariable Long id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java index a0265d15..34a3ba1c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/EventOrderServiceImpl.java @@ -3,16 +3,16 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.EventOrderService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Slf4j +@RequiredArgsConstructor public class EventOrderServiceImpl implements EventOrderService { - @Autowired - EventOrderRepository eventOrderRepository; + private final EventOrderRepository eventOrderRepository; public EventOrder saveAndFlush(EventOrder order) { return eventOrderRepository.saveAndFlush(order); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java index 8dde7efe..f30f3e3d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java @@ -1,26 +1,25 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningAccreditationRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; @Service +@RequiredArgsConstructor public class QuestioningAccreditationServiceImpl implements QuestioningAccreditationService { - @Autowired - private QuestioningAccreditationRepository questioningAccreditationRepository; + private final QuestioningAccreditationRepository questioningAccreditationRepository; public List findByContactIdentifier(String id) { return questioningAccreditationRepository.findByIdContact(id); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java index aad5e901..12cee8a3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java @@ -6,20 +6,19 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.util.LastQuestioningEventComparator; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service +@RequiredArgsConstructor public class QuestioningEventServiceImpl implements QuestioningEventService { - @Autowired - LastQuestioningEventComparator lastQuestioningEventComparator; + private final LastQuestioningEventComparator lastQuestioningEventComparator; - @Autowired - QuestioningEventRepository questioningEventRepository; + private final QuestioningEventRepository questioningEventRepository; @Override public Optional findbyId(Long id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java index 70a34d43..cf5fbf5d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java @@ -1,14 +1,6 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; -import java.util.Optional; -import java.util.Set; - import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; @@ -17,24 +9,27 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Optional; +import java.util.Set; @Service +@RequiredArgsConstructor public class QuestioningServiceImpl implements QuestioningService { - @Autowired - private QuestioningRepository questioningRepository; + private final QuestioningRepository questioningRepository; - @Autowired - private SurveyUnitService surveyUnitService; + private final SurveyUnitService surveyUnitService; - @Autowired - private QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - private QuestioningAccreditationService questioningAccreditationService; + private final QuestioningAccreditationService questioningAccreditationService; - @Autowired - ApplicationConfig applicationConfig; + private final ApplicationConfig applicationConfig; @Override public Page findAll(Pageable pageable) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java index fabd6ed9..e655d04d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java @@ -1,28 +1,26 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; -import java.util.List; -import java.util.Optional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitAddressRepository; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; @Service @Slf4j +@RequiredArgsConstructor public class SurveyUnitServiceImpl implements SurveyUnitService { - @Autowired - private SurveyUnitRepository surveyUnitRepository; + private final SurveyUnitRepository surveyUnitRepository; - @Autowired - private SurveyUnitAddressRepository surveyUnitAddressRepository; + private final SurveyUnitAddressRepository surveyUnitAddressRepository; @Override public Optional findbyId(String idSu) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java index 75caf212..fcfabcb6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java @@ -17,28 +17,26 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service @Slf4j +@RequiredArgsConstructor public class UploadServiceImpl implements UploadService { - @Autowired - UploadRepository uploadRepository; + private final UploadRepository uploadRepository; - @Autowired - QuestioningEventService questioningEventService; + private final QuestioningEventService questioningEventService; - @Autowired - CampaignService campaignService; + private final CampaignService campaignService; + + private final QuestioningService questioningService; - @Autowired - QuestioningService questioningService; @Override public ResultUpload save(String idCampaign, UploadDto uploadDto) throws RessourceNotValidatedException { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/LastQuestioningEventComparator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/LastQuestioningEventComparator.java index bf62161f..8ba70685 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/LastQuestioningEventComparator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/LastQuestioningEventComparator.java @@ -1,19 +1,18 @@ package fr.insee.survey.datacollectionmanagement.questioning.util; -import java.util.Comparator; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.service.EventOrderService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +import java.util.Comparator; @Component +@RequiredArgsConstructor public class LastQuestioningEventComparator implements Comparator { - @Autowired - private EventOrderService eventOrderService; + private final EventOrderService eventOrderService; @Override public int compare(QuestioningEvent o1, QuestioningEvent o2) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java index f5da2b89..d5e55768 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java @@ -87,7 +87,7 @@ public ResponseEntity getSourceAccreditation(@PathVariable("id") String id) { }) @Transactional public ResponseEntity postSourceAccreditation(@PathVariable("id") String id, - @RequestBody @Valid SourceAccreditationDto sourceAccreditationDto) { + @Valid @RequestBody SourceAccreditationDto sourceAccreditationDto) { Optional optSource = null; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java index 5cc3b2f6..6396d3bf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/SourceAccreditationDto.java @@ -15,8 +15,9 @@ public class SourceAccreditationDto { @JsonIgnore private Long id; private Date creationDate; + @NotBlank(message = "creationAuthor can't be empty") private String creationAuthor; - @NotBlank + @NotBlank(message = "idUser can't be empty") private String idUser; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java index 6db17514..cf991a54 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.user.dto; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -11,8 +12,10 @@ public class UserEventDto { private Long id; + @NotBlank(message = "identifier can't be blank") private String identifier; private Date eventDate; + private String type; private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValid.java new file mode 100644 index 00000000..e115ea35 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValid.java @@ -0,0 +1,26 @@ +package fr.insee.survey.datacollectionmanagement.user.validation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Target({FIELD, PARAMETER, METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Constraint(validatedBy = UserEventTypeValidator.class) +public @interface UserEventTypeValid { + //error message + String message() default "Type missing or not recognized. Only CREATE, UPDATE, DELETE are valid"; + + //represents group of constraints + Class[] groups() default {}; + + //represents additional information about annotation + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java new file mode 100644 index 00000000..2d65f372 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java @@ -0,0 +1,23 @@ +package fr.insee.survey.datacollectionmanagement.user.validation; + +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.Arrays; + +public class UserEventTypeValidator implements ConstraintValidator { + + + @Override + public void initialize(UserEventTypeValid constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value == null) + return false; + return Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> value.equals(v)); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java index c05777c6..b3a614e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java @@ -16,7 +16,7 @@ @Constraint(validatedBy = UserRoleValidator.class) public @interface UserRoleValid { //error message - String message() default "Role missing or not recognized."; + String message() default "Role missing or not recognized. Only CREATE, UPDATE, DELETE"; //represents group of constraints Class[] groups() default {}; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java index f861b35b..545b193d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java @@ -1,6 +1,6 @@ package fr.insee.survey.datacollectionmanagement.user.validation; -import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; +import fr.insee.survey.datacollectionmanagement.user.domain.User; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; @@ -18,6 +18,6 @@ public void initialize(UserRoleValid constraintAnnotation) { public boolean isValid(String value, ConstraintValidatorContext context) { if(value == null) return false; - return Arrays.stream(UserEvent.UserEventType.values()).anyMatch( v -> value.equals(v)); + return Arrays.stream(User.UserRoleType.values()).anyMatch(v -> value.equals(v)); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java index fcae4c2c..bd7b4461 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java @@ -20,11 +20,11 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.jeasy.random.EasyRandom; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; @@ -32,62 +32,44 @@ @Component @Slf4j +@RequiredArgsConstructor public class Dataloader { + private final ContactRepository contactRepository; - @Autowired - private ContactRepository contactRepository; + private final AddressRepository addressRepository; - @Autowired - private AddressRepository addressRepository; + private final ContactEventRepository contactEventRepository; - @Autowired - private ContactEventRepository contactEventRepository; + private final OwnerRepository ownerRepository; - @Autowired - private OwnerRepository ownerRepository; + private final SupportRepository supportRepository; - @Autowired - private SupportRepository supportRepository; + private final SourceRepository sourceRepository; - @Autowired - private SourceRepository sourceRepository; + private final SurveyRepository surveyRepository; - @Autowired - private SurveyRepository surveyRepository; + private final SurveyUnitRepository surveyUnitRepository; - @Autowired - private SurveyUnitRepository surveyUnitRepository; + private final SurveyUnitAddressRepository surveyUnitAddressRepository; - @Autowired - private SurveyUnitAddressRepository surveyUnitAddressRepository; + private final OperatorServiceRepository operatorServiceRepository; - @Autowired - private OperatorServiceRepository operatorServiceRepository; + private final OperatorRepository operatorRepository; - @Autowired - private OperatorRepository operatorRepository; + private final QuestioningRepository questioningRepository; - @Autowired - private QuestioningRepository questioningRepository; + private final QuestioningAccreditationRepository questioningAccreditationRepository; - @Autowired - private QuestioningAccreditationRepository questioningAccreditationRepository; + private final CampaignRepository campaignRepository; - @Autowired - private CampaignRepository campaignRepository; + private final PartitioningRepository partitioningRepository; - @Autowired - private PartitioningRepository partitioningRepository; + private final EventOrderRepository orderRepository; - @Autowired - private EventOrderRepository orderRepository; + private final QuestioningEventRepository questioningEventRepository; - @Autowired - private QuestioningEventRepository questioningEventRepository; - - @Autowired - private ViewRepository viewRepository; + private final ViewRepository viewRepository; @PostConstruct public void init() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java index 164af1d2..7a469b12 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java @@ -20,11 +20,11 @@ import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.jeasy.random.EasyRandom; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @@ -34,61 +34,44 @@ @Component @Profile("poc") @Slf4j +@RequiredArgsConstructor public class DataloaderPoc { - @Autowired - private ContactRepository contactRepository; + private final ContactRepository contactRepository; - @Autowired - private AddressRepository addressRepository; + private final AddressRepository addressRepository; - @Autowired - private ContactEventRepository contactEventRepository; + private final ContactEventRepository contactEventRepository; - @Autowired - private OwnerRepository ownerRepository; + private final OwnerRepository ownerRepository; - @Autowired - private SupportRepository supportRepository; + private final SupportRepository supportRepository; - @Autowired - private SourceRepository sourceRepository; + private final SourceRepository sourceRepository; - @Autowired - private SurveyRepository surveyRepository; + private final SurveyRepository surveyRepository; - @Autowired - private SurveyUnitRepository surveyUnitRepository; + private final SurveyUnitRepository surveyUnitRepository; - @Autowired - private SurveyUnitAddressRepository surveyUnitAddressRepository; + private final SurveyUnitAddressRepository surveyUnitAddressRepository; - @Autowired - private OperatorServiceRepository operatorServiceRepository; + private final OperatorServiceRepository operatorServiceRepository; - @Autowired - private OperatorRepository operatorRepository; + private final OperatorRepository operatorRepository; - @Autowired - private QuestioningRepository questioningRepository; + private final QuestioningRepository questioningRepository; - @Autowired - private QuestioningAccreditationRepository questioningAccreditationRepository; + private final QuestioningAccreditationRepository questioningAccreditationRepository; - @Autowired - private CampaignRepository campaignRepository; + private final CampaignRepository campaignRepository; - @Autowired - private PartitioningRepository partitioningRepository; + private final PartitioningRepository partitioningRepository; - @Autowired - private EventOrderRepository orderRepository; + private final EventOrderRepository orderRepository; - @Autowired - private QuestioningEventRepository questioningEventRepository; + private final QuestioningEventRepository questioningEventRepository; - @Autowired - private ViewRepository viewRepository; + private final ViewRepository viewRepository; @PostConstruct public void init() { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/view/serviceImpl/ViewServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/view/serviceImpl/ViewServiceImpl.java index fa9a2bce..707e8539 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/view/serviceImpl/ViewServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/view/serviceImpl/ViewServiceImpl.java @@ -1,20 +1,19 @@ package fr.insee.survey.datacollectionmanagement.view.serviceImpl; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.List; @Service +@RequiredArgsConstructor public class ViewServiceImpl implements ViewService { - @Autowired - private ViewRepository viewRepository; + private final ViewRepository viewRepository; @Override public List findViewByIdentifier(String identifier) { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index b07783ca..6a283fd5 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -4,7 +4,6 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.metadata.repository.CampaignRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import net.minidev.json.JSONObject; @@ -41,14 +40,10 @@ class CampaignControllerTest { @Autowired - private MockMvc mockMvc; + MockMvc mockMvc; @Autowired - private CampaignService campaignService; - - @Autowired - private CampaignRepository campaignRepository; - + CampaignService campaignService; @Test diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java index ab756410..5aa24872 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java @@ -30,13 +30,13 @@ public class SourceControllerTest { @Autowired - private MockMvc mockMvc; + MockMvc mockMvc; @Autowired - private SourceService sourceService; + SourceService sourceService; @Autowired - private SourceRepository sourceRepository; + SourceRepository sourceRepository; @Test public void getSourceOk() throws Exception { From 03632efc93b8eb0fdcdc0894a8ae9132c8399c5d Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 13:55:33 +0100 Subject: [PATCH 021/111] ci: add code coverage analysis --- pom.xml | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/pom.xml b/pom.xml index fbe316a4..c0eaae8f 100644 --- a/pom.xml +++ b/pom.xml @@ -129,6 +129,46 @@ + + + + coverage + + + + org.jacoco + jacoco-maven-plugin + 0.8.11 + + + fr/insee/queen/api/service/dataset/*.class + + + + + prepare-agent + + prepare-agent + + + + report + + report + + + + XML + + + + + + + + + + From d6717ea61476158495c6c54507ff1b2267c121e4 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 14:03:35 +0100 Subject: [PATCH 022/111] ci: add sonar analysis --- .github/workflows/codeql-analysis.yml | 2 +- .github/workflows/sonar.yml | 39 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/sonar.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 8717b106..b9885fb9 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -1,4 +1,4 @@ -# For most projects, this workflow file will not need changing; you simply need + For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml new file mode 100644 index 00000000..5ee69ba4 --- /dev/null +++ b/.github/workflows/sonar.yml @@ -0,0 +1,39 @@ +name: Sonar Analysis + +on: + push: + branches: + - main + - upgrade + pull_request: + types: [opened, synchronize, reopened] +jobs: + build: + name: Build and analyze + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + - name: Set up JDK 21 + uses: actions/setup-java@v3 + with: + java-version: 21 + distribution: 'temurin' + - name: Cache SonarCloud packages + uses: actions/cache@v3 + with: + path: ~/.sonar/cache + key: ${{ runner.os }}-sonar + restore-keys: ${{ runner.os }}-sonar + - name: Cache Maven packages + uses: actions/cache@v3 + with: + path: ~/.m2 + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: ${{ runner.os }}-m2 + - name: Build and analyze + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + run: mvn clean verify -Pcoverage sonar:sonar -Dsonar.projectKey=InseeFr_Platine-Management-Back-Office --no-transfer-progress \ No newline at end of file From fabeb16900fa9b1e75656646e265d00d3e5b9f62 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 14:07:32 +0100 Subject: [PATCH 023/111] ci: fix conf jacoco --- pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pom.xml b/pom.xml index c0eaae8f..0ffc6c20 100644 --- a/pom.xml +++ b/pom.xml @@ -139,11 +139,6 @@ org.jacoco jacoco-maven-plugin 0.8.11 - - - fr/insee/queen/api/service/dataset/*.class - - prepare-agent From 6e24ebf1ec7c034cd1c542a4631f86c57f84bd75 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 14:19:15 +0100 Subject: [PATCH 024/111] ci: add sonar url and organization --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 0ffc6c20..1ca885cb 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,8 @@ 3.1.0 5.0.0 1.0.2 + inseefr + https://sonarcloud.io From ca97075c600546ae06be091471f77859e44f7592 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 23 Nov 2023 14:21:09 +0100 Subject: [PATCH 025/111] ci: delete code ql analysis --- .github/workflows/codeql-analysis.yml | 76 --------------------------- 1 file changed, 76 deletions(-) delete mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index b9885fb9..00000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,76 +0,0 @@ - For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [main] - pull_request: - # The branches below must be a subset of the branches above - branches: [main] - schedule: - - cron: "31 19 * * 2" - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: ["java"] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v3 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - - # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - # queries: security-extended,security-and-quality - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: actions/setup-java@v3 - with: - java-version: "21" - distribution: "temurin" - - name: Build with Maven - run: mvn -DskipTests package - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - # If the Autobuild fails above, remove it and uncomment the following three lines. - # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. - - # - run: | - # echo "Run, Build Application using script" - # ./location_of_script_within_repo/buildscript.sh - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 From f5a06f4f1c3498ea7424452b18fbfc939c602dfc Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 13:41:52 +0100 Subject: [PATCH 026/111] fix: sonar bugs --- pom.xml | 5 + .../config/CorsGlobalConfig.java | 2 +- .../{util => dataloader}/Dataloader.java | 127 +++++++-------- .../{util => dataloader}/DataloaderPoc.java | 2 +- .../query/controller/WebclientController.java | 10 +- .../service/impl/UploadServiceImpl.java | 48 +++--- .../user/controller/UserController.java | 47 +++--- .../user/controller/UserEventController.java | 7 +- .../user/dto/UserEventDto.java | 3 +- .../user/service/UserService.java | 6 +- .../user/service/impl/UserServiceImpl.java | 6 +- .../validation/UserEventTypeValidator.java | 2 +- .../user/validation/UserRoleValidator.java | 2 +- .../DataloaderTest.java | 15 +- .../controller/UserControllerTest.java | 144 ++++++++++++++++++ .../controller/UserEventControllerTest.java | 57 +++++++ 16 files changed, 356 insertions(+), 127 deletions(-) rename src/main/java/fr/insee/survey/datacollectionmanagement/{util => dataloader}/Dataloader.java (87%) rename src/main/java/fr/insee/survey/datacollectionmanagement/{util => dataloader}/DataloaderPoc.java (99%) rename src/test/java/fr/insee/survey/datacollectionmanagement/{config => dataloader}/DataloaderTest.java (97%) create mode 100644 src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java create mode 100644 src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java diff --git a/pom.xml b/pom.xml index 1ca885cb..dfc7f90f 100644 --- a/pom.xml +++ b/pom.xml @@ -141,6 +141,11 @@ org.jacoco jacoco-maven-plugin 0.8.11 + + + **/dataloader/**/*.class + + prepare-agent diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java index 928fec41..5c387d8f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java @@ -19,7 +19,7 @@ public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { - String ao = applicationConfig.getAllowedOrigin().isPresent() ? applicationConfig.getAllowedOrigin().get() : applicationConfig.getAllowedOrigin().orElse("*"); + String ao = applicationConfig.getAllowedOrigin().orElse("*"); registry.addMapping("/**") .allowedOrigins(ao) .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java similarity index 87% rename from src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java rename to src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java index bd7b4461..74440182 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java @@ -1,4 +1,4 @@ -package fr.insee.survey.datacollectionmanagement.util; +package fr.insee.survey.datacollectionmanagement.dataloader; import com.github.javafaker.Faker; import com.github.javafaker.Name; @@ -77,7 +77,7 @@ public void init() { Faker faker = new Faker(); EasyRandom generator = new EasyRandom(); - initOrder(); + initOrder(); // initContact(faker); // initMetadata(faker, generator); // initQuestionning(faker, generator); @@ -180,7 +180,7 @@ private void initOrder() { Long nbExistingOrders = orderRepository.count(); log.info("{} orders in database", nbExistingOrders); - if (nbExistingOrders !=8 ) { + if (nbExistingOrders != 8) { // Creating table order log.info("loading eventorder data"); orderRepository.deleteAll(); @@ -317,8 +317,8 @@ private void initMetadata(Faker faker, EasyRandom generator2) { while (sourceRepository.count() < 10) { Source source = new Source(); - - String nameSource = "LOAD"+String.valueOf((char)(sourceRepository.count() + 'A')); + + String nameSource = "LOAD" + String.valueOf((char) (sourceRepository.count() + 'A')); if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { @@ -361,7 +361,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { for (int k = 0; k < 12; k++) { Campaign campaign = new Campaign(); int month = k + 1; - String period = month<10? "M0" + month:"M"+month; + String period = month < 10 ? "M0" + month : "M" + month; campaign.setYear(year - j); campaign.setPeriod(PeriodEnum.valueOf(period)); campaign.setId(nameSource + (year - j) + period); @@ -400,13 +400,13 @@ private void initMetadata(Faker faker, EasyRandom generator2) { sourceRepository.save(source); ownerInsee.setSources(setSourcesInsee); ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(new Owner[] { + ownerRepository.saveAll(Arrays.asList(new Owner[]{ ownerInsee, ownerAgri })); supportInseeHdf.setSources(setSourcesSupportInsee); supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(new Support[] { + supportRepository.saveAll(Arrays.asList(new Support[]{ supportInseeHdf, supportSsne })); } @@ -549,62 +549,63 @@ private void initQuestioningEvents(Faker faker, EasyRandom generator) { // questioning events // everybody in INITLA Optional part = partitioningRepository.findById(qu.getIdPartitioning()); - Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); - qe.setType(TypeQuestioningEvent.INITLA); - qe.setDate(eventDate); - qe.setQuestioning(qu); - qeList.add(qe); - - int qeProfile = qeRan.nextInt(10); - - switch (qeProfile) { - case 0: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.REFUSAL, qu)); - break; - case 1: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PND, qu)); - break; - case 2: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - break; - case 3: - case 4: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - case 5: - case 6: - case 7: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - } - - qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); + if (part.isPresent()) { + Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); + qe.setType(TypeQuestioningEvent.INITLA); + qe.setDate(eventDate); + qe.setQuestioning(qu); + qeList.add(qe); + + int qeProfile = qeRan.nextInt(10); + + switch (qeProfile) { + case 0: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.REFUSAL, qu)); + break; + case 1: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.PND, qu)); + break; + case 2: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.FOLLOWUP, qu)); + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.FOLLOWUP, qu)); + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.PARTIELINT, qu)); + break; + case 3: + case 4: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.FOLLOWUP, qu)); + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.FOLLOWUP, qu)); + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.VALINT, qu)); + break; + case 5: + case 6: + case 7: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.PARTIELINT, qu)); + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.VALINT, qu)); + break; + } + qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); + } } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java similarity index 99% rename from src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java rename to src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 7a469b12..30b36ee5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/util/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -1,4 +1,4 @@ -package fr.insee.survey.datacollectionmanagement.util; +package fr.insee.survey.datacollectionmanagement.dataloader; import com.github.javafaker.Faker; import com.github.javafaker.Name; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index 2d5ebf45..84c84f51 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -158,7 +158,7 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que // save questioning and su questioningService.saveQuestioning(questioning); su.getQuestionings().add(questioning); - su = surveyUnitService.saveSurveyUnitAndAddress(su); + surveyUnitService.saveSurveyUnitAndAddress(su); questioningReturn.setIdPartitioning(idPartitioning); @@ -400,8 +400,12 @@ public ResponseEntity getMainContact( List listQa = questioning.getQuestioningAccreditations().stream() .filter(qa -> qa.isMain()).toList(); if (listQa != null && !listQa.isEmpty()) { - Contact c = contactService.findByIdentifier(listQa.get(0).getIdContact()).get(); - return ResponseEntity.status(HttpStatus.OK).body(convertToDto((c))); + Optional c = contactService.findByIdentifier(listQa.get(0).getIdContact()); + if(c.isPresent()) + return ResponseEntity.status(HttpStatus.OK).body(convertToDto((c.get()))); + else + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No contact found"); + } } return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No contact found"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java index fcfabcb6..f034f877 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java @@ -67,7 +67,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc if (setParts.isEmpty()) { throw new RessourceNotValidatedException("No partitionings found for campaign ", idCampaign); } - + Set questionings = questioningService.findBySurveyUnitIdSu(mmDto.getIdSu()); List listIdParts = campaignService.findById(idCampaign).get().getPartitionings().stream().map(Partitioning::getId).toList(); @@ -83,7 +83,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc qe.setPayload(objectMapper.readTree(jo.toString())); qe.setDate(today); liste.add(questioningEventService.saveQuestioningEvent(qe)); - if(quest.isPresent()){ + if (quest.isPresent()) { quest.get().getQuestioningEvents().add(qe); questioningService.saveQuestioning(quest.get()); } @@ -99,7 +99,7 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc return result; } up.setQuestioningEvents(liste); - up = saveAndFlush(up); + saveAndFlush(up); return result; } @@ -113,14 +113,17 @@ public Optional findById(long id) { public List findAllByIdCampaign(String idCampaign) { Optional campaign = campaignService.findById(idCampaign); + if (campaign.isPresent()) { - List partitioningIds = campaign.get().getPartitionings().stream().map(Partitioning::getId).toList(); + List partitioningIds = campaign.get().getPartitionings().stream().map(Partitioning::getId).toList(); - // Keeps the uploads which first managementMonitoringInfo belongs to the survey - return uploadRepository.findAll().stream().filter(upload -> !upload.getQuestioningEvents().isEmpty()) - .filter(upload -> partitioningIds.contains(upload.getQuestioningEvents().stream().findFirst().get().getQuestioning().getIdPartitioning() - )) - .toList(); + // Keeps the uploads which first managementMonitoringInfo belongs to the survey + return uploadRepository.findAll().stream().filter(upload -> !upload.getQuestioningEvents().isEmpty()) + .filter(upload -> partitioningIds.contains(upload.getQuestioningEvents().stream().findFirst().get().getQuestioning().getIdPartitioning() + )) + .toList(); + } + return Collections.emptyList(); } @@ -137,18 +140,27 @@ public Upload saveAndFlush(Upload up) { @Override public boolean checkUploadDate(String idCampaign, Date date) { Optional campaign = campaignService.findById(idCampaign); - Long timestamp = date.getTime(); - Long start = campaign.get().getPartitionings().stream().map(Partitioning::getOpeningDate) - .toList().stream() - .min(Comparator.comparing(Date::getTime)).get().getTime(); - Long end = campaign.get().getPartitionings().stream().map(Partitioning::getClosingDate) - .toList().stream() - .max(Comparator.comparing(Date::getTime)).get().getTime(); - return (start < timestamp && timestamp < end); + long timestamp = date.getTime(); + if (campaign.isPresent()) { + Optional openingDate = campaign.get().getPartitionings().stream().map(Partitioning::getOpeningDate) + .toList().stream() + .min(Comparator.comparing(Date::getTime)); + Optional closingDate = campaign.get().getPartitionings().stream().map(Partitioning::getClosingDate) + .toList().stream() + .max(Comparator.comparing(Date::getTime)); + if(openingDate.isPresent() && closingDate.isPresent()){ + long start = openingDate.get().getTime(); + long end = closingDate.get().getTime(); + return (start < timestamp && timestamp < end); + + } + + } + return false; } @Override public void removeEmptyUploads() { - uploadRepository.findByQuestioningEventsIsEmpty().forEach(u -> uploadRepository.delete(u)); + uploadRepository.findByQuestioningEventsIsEmpty().forEach(uploadRepository::delete); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 45e7c142..2fff5d6d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -5,9 +5,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; import fr.insee.survey.datacollectionmanagement.user.domain.User; -import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.dto.UserDto; -import fr.insee.survey.datacollectionmanagement.user.exception.RoleException; import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; import fr.insee.survey.datacollectionmanagement.user.service.UserService; import io.swagger.v3.oas.annotations.Operation; @@ -32,9 +30,10 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.text.ParseException; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -59,7 +58,7 @@ public class UserController { @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = UserController.UserPage.class))) }) - public ResponseEntity getUsers( + public ResponseEntity getUsers( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "identifier") String sort) { @@ -76,7 +75,7 @@ public ResponseEntity getUsers( @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity getUser(@PathVariable("id") String id) { + public ResponseEntity getUser(@PathVariable("id") String id) { Optional user = userService.findByIdentifier(id); try { if (user.isPresent()) @@ -96,7 +95,7 @@ public ResponseEntity getUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = UserDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto) { + public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto) { if (StringUtils.isBlank(userDto.getIdentifier()) || !userDto.getIdentifier().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and user identifier don't match"); } @@ -110,21 +109,16 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestB } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse user"); - } catch (RoleException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Role not recognized: only [" + Stream.of(User.UserRoleType.values()) - .map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); - } catch (NoSuchElementException e) { log.info("Creating user with the identifier {}", userDto.getIdentifier()); - user = convertToEntityNewContact(userDto); + user = convertToEntityNewUser(userDto); - User userCreate = userService.createUserEvent(user, null); + User userCreate = userService.createUser(user, null); return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).body(convertToDto(userCreate)); } log.info("Updating user with the identifier {}", userDto.getIdentifier()); - User userUpdate = userService.updateUserEvent(user, null); + User userUpdate = userService.updateUser(user, null); return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(userUpdate)); } @@ -137,11 +131,11 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestB @ApiResponse(responseCode = "400", description = "Bad Request") }) @Transactional - public ResponseEntity deleteUser(@PathVariable("id") String id) { + public ResponseEntity deleteUser(@PathVariable("id") String id) { try { Optional user = userService.findByIdentifier(id); if (user.isPresent()) { - userService.deleteContactAddressEvent(user.get()); + userService.deleteUserAndEvents(user.get()); sourceAccreditationService.findByUserIdentifier(id).stream().forEach(acc -> { Source source = sourceService.findById(acc.getSource().getId()).get(); @@ -169,7 +163,7 @@ public ResponseEntity deleteUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity getUserSources(@PathVariable("id") String id) { + public ResponseEntity getUserSources(@PathVariable("id") String id) { Optional user = userService.findByIdentifier(id); if (user.isPresent()) { List accreditedSources = userService.findAccreditedSources(id); @@ -180,30 +174,27 @@ public ResponseEntity getUserSources(@PathVariable("id") String id) { } - private User convertToEntity(UserDto userDto) throws ParseException, NoSuchElementException, RoleException { - User user = modelMapper.map(userDto, User.class); - - if (user.getRole() == null || Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> userDto.getRole().equals(v))) { - throw new RoleException("Role missing or not recognized. Only [" + Stream.of(User.UserRoleType.values()).map(User.UserRoleType::name).collect(Collectors.joining(", ")) + "] are possible"); - } + private User convertToEntity(UserDto userDto) throws ParseException, NoSuchElementException { Optional oldUser = userService.findByIdentifier(userDto.getIdentifier()); if (!oldUser.isPresent()) { throw new NoSuchElementException(); } + User user = modelMapper.map(userDto, User.class); + user.setRole(User.UserRoleType.valueOf(userDto.getRole().toUpperCase())); user.setUserEvents(oldUser.get().getUserEvents()); return user; } - private User convertToEntityNewContact(UserDto userDto) { + private User convertToEntityNewUser(UserDto userDto) { User user = modelMapper.map(userDto, User.class); + user.setRole(User.UserRoleType.valueOf(userDto.getRole().toUpperCase())); return user; } private UserDto convertToDto(User user) { - UserDto userDto = modelMapper.map(user, UserDto.class); - return userDto; + return modelMapper.map(user, UserDto.class); } class UserPage extends PageImpl { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java index f1bdcceb..03dab014 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java @@ -15,6 +15,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -22,6 +23,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -37,6 +39,7 @@ @Slf4j @Tag(name = "7-User", description = "Enpoints to create, update, delete and find users, their events and accreditations") @RequiredArgsConstructor +@Validated public class UserEventController { private final ModelMapper modelMapper; @@ -76,7 +79,7 @@ public ResponseEntity getUserUserEvents(@PathVariable("id") String identifier @ApiResponse(responseCode = "400", description = "Bad request"), @ApiResponse(responseCode = "404", description = "Not found") }) - public ResponseEntity postUserEvent(@RequestBody UserEventDto userEventDto) { + public ResponseEntity postUserEvent(@Valid @RequestBody UserEventDto userEventDto) { try { Optional optUser = userService.findByIdentifier(userEventDto.getIdentifier()); @@ -137,8 +140,6 @@ private UserEventDto convertToDto(UserEvent userEvent) { private UserEvent convertToEntity(UserEventDto userEventDto) throws EventException { UserEvent userEvent = modelMapper.map(userEventDto, UserEvent.class); - if (userEvent.getType() == null) - throw new EventException("User event not recognized"); return userEvent; } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java index cf991a54..f266060d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserEventDto.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.user.dto; import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.user.validation.UserEventTypeValid; import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -15,7 +16,7 @@ public class UserEventDto { @NotBlank(message = "identifier can't be blank") private String identifier; private Date eventDate; - + @UserEventTypeValid private String type; private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java index 34df6b61..604371ab 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java @@ -43,11 +43,11 @@ public interface UserService { */ public void deleteUser(String identifier); - public User createUserEvent(User user, JsonNode payload); + public User createUser(User user, JsonNode payload); - public User updateUserEvent(User user, JsonNode payload); + public User updateUser(User user, JsonNode payload); - public void deleteContactAddressEvent(User user); + public void deleteUserAndEvents(User user); List findAccreditedSources(String identifier); } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index c4613fc0..02ced26a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -48,7 +48,7 @@ public void deleteUser(String identifier) { @Override - public User createUserEvent(User user, JsonNode payload) { + public User createUser(User user, JsonNode payload) { UserEvent newUserEvent = userEventService.createUserEvent(user, UserEvent.UserEventType.CREATE, payload); @@ -57,7 +57,7 @@ public User createUserEvent(User user, JsonNode payload) { } @Override - public User updateUserEvent(User user, JsonNode payload) { + public User updateUser(User user, JsonNode payload) { User existingUser = findByIdentifier(user.getIdentifier()).get(); @@ -70,7 +70,7 @@ public User updateUserEvent(User user, JsonNode payload) { } @Override - public void deleteContactAddressEvent(User user) { + public void deleteUserAndEvents(User user) { deleteUser(user.getIdentifier()); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java index 2d65f372..dac2ba8f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserEventTypeValidator.java @@ -18,6 +18,6 @@ public void initialize(UserEventTypeValid constraintAnnotation) { public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) return false; - return Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> value.equals(v)); + return Arrays.stream(UserEvent.UserEventType.values()).anyMatch(v -> value.equalsIgnoreCase(v.name())); } } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java index 545b193d..a57b620d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValidator.java @@ -18,6 +18,6 @@ public void initialize(UserRoleValid constraintAnnotation) { public boolean isValid(String value, ConstraintValidatorContext context) { if(value == null) return false; - return Arrays.stream(User.UserRoleType.values()).anyMatch(v -> value.equals(v)); + return Arrays.stream(User.UserRoleType.values()).anyMatch(v -> value.equalsIgnoreCase(v.name())); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java similarity index 97% rename from src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java rename to src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java index 5f893961..65cd570f 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/config/DataloaderTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java @@ -1,4 +1,4 @@ -package fr.insee.survey.datacollectionmanagement.config; +package fr.insee.survey.datacollectionmanagement.dataloader; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; @@ -18,6 +18,8 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.*; import fr.insee.survey.datacollectionmanagement.questioning.repository.*; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import fr.insee.survey.datacollectionmanagement.user.domain.User; +import fr.insee.survey.datacollectionmanagement.user.service.UserService; import fr.insee.survey.datacollectionmanagement.view.domain.View; import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; @@ -84,6 +86,9 @@ public class DataloaderTest { @Autowired private ViewRepository viewRepository; + @Autowired + private UserService userService; + @PostConstruct public void init() throws ParseException { @@ -94,7 +99,15 @@ public void init() throws ParseException { initMetadata(); initQuestionning(faker); initView(); + initUser(); + + } + private void initUser() { + User user = new User(); + user.setIdentifier("USER1"); + user.setRole(User.UserRoleType.ASSISTANCE); + userService.createUser(user,null); } private void initOrder() { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java new file mode 100644 index 00000000..e0bfedf1 --- /dev/null +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -0,0 +1,144 @@ +package fr.insee.survey.datacollectionmanagement.user.controller.controller; + +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.user.domain.User; +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent.UserEventType; +import fr.insee.survey.datacollectionmanagement.user.repository.UserRepository; +import fr.insee.survey.datacollectionmanagement.user.service.UserEventService; +import fr.insee.survey.datacollectionmanagement.user.service.UserService; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@SpringBootTest +@ActiveProfiles("test") +public class UserControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserService userService; + + @Autowired + private UserEventService userEventService; + + @Autowired + private UserRepository userRepository; + + @Test + public void getUserNotFound() throws Exception { + String identifier = "CONT500"; + this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + + } + + @Test + public void getUserOk() throws Exception { + String identifier = "CONT1"; + this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.OK.value())); + + } + + @Test + public void getUsersOk() throws Exception { + JSONObject jo = new JSONObject(); + jo.put("totalElements", userRepository.count()); + jo.put("numberOfElements", userRepository.count()); + + this.mockMvc.perform(get(Constants.API_USERS_ALL)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(jo.toString(), false)); + } + + @Test + public void putUserCreateUpdateDelete() throws Exception { + String identifier = "TESTPUT"; + + // create user - status created + User user = initGestionnaire(identifier); + String jsonUser = createJson(user); + mockMvc.perform( + put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(content().json(jsonUser.toString(), false)); + User userFound = userService.findByIdentifier(identifier).get(); + assertEquals(user.getIdentifier(), userFound.getIdentifier()); + assertEquals(user.getRole(), userFound.getRole()); + + // update user - status ok + user.setRole(User.UserRoleType.ASSISTANCE); + String jsonUserUpdate = createJson(user); + mockMvc.perform(put(Constants.API_USERS_ID, identifier).content(jsonUserUpdate) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(content().json(jsonUserUpdate.toString(), false)); + User userFoundAfterUpdate = userService.findByIdentifier(identifier).get(); + assertEquals(User.UserRoleType.ASSISTANCE, userFoundAfterUpdate.getRole()); + List listUpdate = new ArrayList<>( + userEventService.findUserEventsByUser(userFoundAfterUpdate)); + assertEquals(listUpdate.size(), 2); + assertEquals(listUpdate.get(1).getType(), UserEventType.UPDATE); + + // delete user + mockMvc.perform(delete(Constants.API_USERS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + assertFalse(userService.findByIdentifier(identifier).isPresent()); + assertTrue(userEventService.findUserEventsByUser(userFoundAfterUpdate).isEmpty()); + + // delete user not found + mockMvc.perform(delete("/users/" + identifier).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()); + + } + + @Test + public void putUsersErrorId() throws Exception { + String identifier = "NEWONE"; + String otherIdentifier = "WRONG"; + User user = initGestionnaire(identifier); + String jsonUser = createJson(user); + mockMvc.perform(put(Constants.API_USERS_ID, otherIdentifier).content(jsonUser) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().string("id and user identifier don't match")); + + } + + private User initGestionnaire(String identifier) { + return initUser(identifier, User.UserRoleType.GESTIONNAIRE); + } + + private User initUser(String identifier, User.UserRoleType role) { + User userMock = new User(); + userMock.setIdentifier(identifier); + userMock.setRole(role); + return userMock; + } + + + private String createJson(User user) throws JSONException { + JSONObject jo = new JSONObject(); + jo.put("identifier", user.getIdentifier()); + jo.put("role", user.getRole().name()); + return jo.toString(); + } +} diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java new file mode 100644 index 00000000..9c7d6705 --- /dev/null +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java @@ -0,0 +1,57 @@ +package fr.insee.survey.datacollectionmanagement.user.controller.controller; + +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@SpringBootTest +@ActiveProfiles("test") +public class UserEventControllerTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void getUserEventOk() throws Exception { + String identifier = "USER1"; + + String json = createJsonUserEvent(identifier, null); + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); + } + + @Test + public void getUserEventNotFound() throws Exception { + String identifier = "CONT500"; + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + + } + + private String createJsonUserEvent(String identifier, JSONObject payload ) throws JSONException { + JSONObject jo = new JSONObject(); + JSONObject joPayload = new JSONObject(); + joPayload.put("identifier", identifier); + joPayload.put("type", UserEvent.UserEventType.CREATE.name()); + jo.put("payload", payload); + JSONArray ja = new JSONArray(); + ja.put(jo); + return ja.toString(); + } + +} From 9e5052805d4790dd1d5002284ad40beb9f06b05a Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 13:44:45 +0100 Subject: [PATCH 027/111] test: fix: user test --- .../user/controller/controller/UserControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java index e0bfedf1..d39f0a11 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -54,7 +54,7 @@ public void getUserNotFound() throws Exception { @Test public void getUserOk() throws Exception { - String identifier = "CONT1"; + String identifier = "USER1"; this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.OK.value())); From bdcf068eedf57889109c24f357d0b1a179dc3cd2 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 14:00:55 +0100 Subject: [PATCH 028/111] fix: sonar bugs --- .../contact/service/ContactService.java | 3 +- .../service/impl/ContactServiceImpl.java | 35 +++---- .../dataloader/Dataloader.java | 10 +- .../dataloader/DataloaderPoc.java | 8 +- .../QuestioningAccreditationController.java | 96 ++++++++++--------- .../query/controller/WebclientController.java | 3 +- 6 files changed, 85 insertions(+), 70 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index 3f11541d..1b5df172 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -4,6 +4,7 @@ import java.util.NoSuchElementException; import java.util.Optional; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @@ -56,7 +57,7 @@ public List searchListContactParameters(String identifier, String lastN public Contact createContactAddressEvent(Contact contact, JsonNode payload); - public Contact updateContactAddressEvent(Contact contact, JsonNode payload); + public Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException; public void deleteContactAddressEvent(Contact contact); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 053b88bb..027491bb 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; @@ -63,7 +64,7 @@ public List findByEmail(String email) { @Override public List searchListContactParameters(String identifier, String lastName, String firstName, - String email) { + String email) { List listContactContact = new ArrayList<>(); boolean alwaysEmpty = true; @@ -89,7 +90,7 @@ public List searchListContactParameters(String identifier, String lastN alwaysEmpty = false; } else listContactContact = listContactContact.stream() - .filter(c -> c.getFirstName().equalsIgnoreCase(firstName)) .toList(); + .filter(c -> c.getFirstName().equalsIgnoreCase(firstName)).toList(); } if (!StringUtils.isEmpty(email)) { @@ -116,22 +117,24 @@ public Contact createContactAddressEvent(Contact contact, JsonNode payload) { } @Override - public Contact updateContactAddressEvent(Contact contact, JsonNode payload) { - - Contact existingContact = findByIdentifier(contact.getIdentifier()).get(); - if (contact.getAddress() != null) { - if (existingContact.getAddress() != null) { - contact.getAddress().setId(existingContact.getAddress().getId()); + public Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException { + + Optional existingContact = findByIdentifier(contact.getIdentifier()); + if (existingContact.isPresent()) { + if (contact.getAddress() != null) { + if (existingContact.get().getAddress() != null) { + contact.getAddress().setId(existingContact.get().getAddress().getId()); + } + addressService.saveAddress(contact.getAddress()); } - addressService.saveAddress(contact.getAddress()); - } - Set setContactEventsContact = existingContact.getContactEvents(); - ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, - payload); - setContactEventsContact.add(contactEventUpdate); - contact.setContactEvents(setContactEventsContact); - return saveContact(contact); + Set setContactEventsContact = existingContact.get().getContactEvents(); + ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, + payload); + setContactEventsContact.add(contactEventUpdate); + contact.setContactEvents(setContactEventsContact); + return saveContact(contact); + } else throw new NotFoundException("Contact not found"); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java index 74440182..daee737a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java @@ -27,6 +27,7 @@ import org.jeasy.random.EasyRandom; import org.springframework.stereotype.Component; +import java.security.SecureRandom; import java.util.*; import java.util.concurrent.TimeUnit; @@ -285,6 +286,8 @@ private void initContact(Faker faker) { private void initMetadata(Faker faker, EasyRandom generator2) { int year = 2023; + Random qeRan = new SecureRandom(); + Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); @@ -328,7 +331,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { source.setPeriodicity(PeriodicityEnum.M); sourceRepository.save(source); Set setSurveys = new HashSet<>(); - Integer i = new Random().nextInt(); + Integer i = qeRan.nextInt(); if (i % 2 == 0) setSourcesInsee.add(source); else { @@ -428,7 +431,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { QuestioningAccreditation accreditation; Set questioningAccreditations; String fakeSiren; - Random qeRan = new Random(); + Random qeRan = new SecureRandom(); log.info("{} survey units exist in database", surveyUnitRepository.count()); @@ -537,10 +540,11 @@ private void initQuestionning(Faker faker, EasyRandom generator) { private void initQuestioningEvents(Faker faker, EasyRandom generator) { Long nbExistingQuestioningEvents = questioningEventRepository.count(); + Random qeRan = new SecureRandom(); + if (nbExistingQuestioningEvents == 0) { List listQu = questioningRepository.findAll(); - Random qeRan = new Random(); for (Questioning qu : listQu) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 30b36ee5..77336501 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -28,6 +28,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; +import java.security.SecureRandom; import java.util.*; import java.util.concurrent.TimeUnit; @@ -329,7 +330,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { source.setPeriodicity(PeriodicityEnum.M); sourceRepository.save(source); Set setSurveys = new HashSet<>(); - Integer i = new Random().nextInt(); + Integer i = new SecureRandom().nextInt(); if (i % 2 == 0) setSourcesInsee.add(source); else { @@ -429,7 +430,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { QuestioningAccreditation accreditation; Set questioningAccreditations; String fakeSiren; - Random qeRan = new Random(); + Random qeRan = new SecureRandom(); log.info("{} survey units exist in database", surveyUnitRepository.count()); @@ -538,10 +539,11 @@ private void initQuestionning(Faker faker, EasyRandom generator) { private void initQuestioningEvents(Faker faker, EasyRandom generator) { Long nbExistingQuestioningEvents = questioningEventRepository.count(); + Random qeRan = new SecureRandom(); + if (nbExistingQuestioningEvents == 0) { List listQu = questioningRepository.findAll(); - Random qeRan = new Random(); for (Questioning qu : listQu) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java index d8c6be3f..2dc4e8a0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java @@ -86,7 +86,7 @@ public ResponseEntity getQuestioningAccreditation(@PathVariable("id") Long id }) @Transactional public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long id, - @RequestBody QuestioningAccreditationDto questioningAccreditationDto) { + @RequestBody QuestioningAccreditationDto questioningAccreditationDto) { Optional optQuestioning = null; @@ -111,51 +111,55 @@ public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long i // save new accreditation or update existing one Set setExistingAccreditations = questioning.getQuestioningAccreditations(); Optional part = partitioningService.findById(questioning.getIdPartitioning()); - String idSu = questioning.getSurveyUnit().getIdSu(); - - List listContactAccreditations = setExistingAccreditations.stream() - .filter(acc -> acc.getIdContact().equals(idContact) - && acc.getQuestioning().getIdPartitioning().equals(part.get().getId()) - && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) - .toList(); - - if (listContactAccreditations.isEmpty()) { - // Create new accreditation - QuestioningAccreditation questioningAccreditation = convertToEntity(questioningAccreditationDto); - questioningAccreditation.setQuestioning(questioning); - setExistingAccreditations.add(questioningAccreditation); - questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); - questioningService.saveQuestioning(questioning); - - // create view - viewService.createView(idContact, questioning.getSurveyUnit().getIdSu(), - part.get().getCampaign().getId()); - - // location header - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) - .toUriString()); - - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(questioningAccreditation)); - - } else { - // update accreditation - QuestioningAccreditation questioningAccreditation = listContactAccreditations.get(0); - questioningAccreditationDto.setId(questioningAccreditation.getId()); - questioningAccreditation = convertToEntity(questioningAccreditationDto); - questioningAccreditation.setQuestioning(questioning); - questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); - - // view already exists - - // location header - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) - .toUriString()); - return ResponseEntity.status(HttpStatus.OK).headers(responseHeaders) - .body(convertToDto(questioningAccreditation)); - } + if (part.isPresent()) { + + String idSu = questioning.getSurveyUnit().getIdSu(); + + List listContactAccreditations = setExistingAccreditations.stream() + .filter(acc -> acc.getIdContact().equals(idContact) + && acc.getQuestioning().getIdPartitioning().equals(part.get().getId()) + && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) + .toList(); + + if (listContactAccreditations.isEmpty()) { + // Create new accreditation + QuestioningAccreditation questioningAccreditation = convertToEntity(questioningAccreditationDto); + questioningAccreditation.setQuestioning(questioning); + setExistingAccreditations.add(questioningAccreditation); + questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); + questioningService.saveQuestioning(questioning); + + // create view + viewService.createView(idContact, questioning.getSurveyUnit().getIdSu(), + part.get().getCampaign().getId()); + + // location header + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) + .toUriString()); + + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(questioningAccreditation)); + + + } else { + // update accreditation + QuestioningAccreditation questioningAccreditation = listContactAccreditations.get(0); + questioningAccreditationDto.setId(questioningAccreditation.getId()); + questioningAccreditation = convertToEntity(questioningAccreditationDto); + questioningAccreditation.setQuestioning(questioning); + questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); + + // view already exists + + // location header + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) + .toUriString()); + return ResponseEntity.status(HttpStatus.OK).headers(responseHeaders) + .body(convertToDto(questioningAccreditation)); + } + } else return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Partitioning not found"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index 84c84f51..e527b55e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.*; import fr.insee.survey.datacollectionmanagement.metadata.dto.*; import fr.insee.survey.datacollectionmanagement.metadata.service.*; @@ -188,7 +189,7 @@ private void createContactAndAccreditations(String idSu, Optional if (contactAccreditationDto.getAddress() != null) contact.setAddress(addressService.convertToEntity(contactAccreditationDto.getAddress())); contactService.updateContactAddressEvent(contact, node); - } catch (NoSuchElementException e) { + } catch (NoSuchElementException | NotFoundException e) { log.info("Creating contact with the identifier {}", contactAccreditationDto.getIdentifier()); contact = convertToEntityNewContact(contactAccreditationDto); if (contactAccreditationDto.getAddress() != null) From 44b19a133a77bcea12f0ee3b0057d71d043f863e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 14:01:43 +0100 Subject: [PATCH 029/111] Update pom.xml --- pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pom.xml b/pom.xml index dfc7f90f..1ca885cb 100644 --- a/pom.xml +++ b/pom.xml @@ -141,11 +141,6 @@ org.jacoco jacoco-maven-plugin 0.8.11 - - - **/dataloader/**/*.class - - prepare-agent From 2f26c1481b865a379b10bff1fcf22ad9878e59a0 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 14:06:03 +0100 Subject: [PATCH 030/111] Update ContactController.java --- .../contact/controller/ContactController.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index 84f07a57..b25a4b52 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -7,6 +7,7 @@ import fr.insee.survey.datacollectionmanagement.contact.dto.ContactFirstLoginDto; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; @@ -133,7 +134,12 @@ public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody } if (contactDto.getAddress() != null) contact.setAddress(addressService.convertToEntity(contactDto.getAddress())); - Contact contactUpdate = contactService.updateContactAddressEvent(contact, null); + Contact contactUpdate = null; + try { + contactUpdate = contactService.updateContactAddressEvent(contact, null); + } catch (NotFoundException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error when update contact"); + } return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(contactUpdate)); } From 458a5584da69b9ff6d26c425d48939b4e1501d79 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 24 Nov 2023 14:33:27 +0100 Subject: [PATCH 031/111] Update Dataloader.java --- .../dataloader/Dataloader.java | 595 +----------------- 1 file changed, 2 insertions(+), 593 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java index daee737a..625925d0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java @@ -1,181 +1,28 @@ package fr.insee.survey.datacollectionmanagement.dataloader; -import com.github.javafaker.Faker; -import com.github.javafaker.Name; -import fr.insee.survey.datacollectionmanagement.contact.domain.Address; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact.Gender; -import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; -import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; -import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; -import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; -import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; -import fr.insee.survey.datacollectionmanagement.metadata.domain.*; -import fr.insee.survey.datacollectionmanagement.metadata.repository.*; -import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; -import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; -import fr.insee.survey.datacollectionmanagement.questioning.domain.*; -import fr.insee.survey.datacollectionmanagement.questioning.repository.*; +import fr.insee.survey.datacollectionmanagement.questioning.domain.EventOrder; +import fr.insee.survey.datacollectionmanagement.questioning.repository.EventOrderRepository; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; -import fr.insee.survey.datacollectionmanagement.view.domain.View; -import fr.insee.survey.datacollectionmanagement.view.repository.ViewRepository; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.jeasy.random.EasyRandom; import org.springframework.stereotype.Component; -import java.security.SecureRandom; -import java.util.*; -import java.util.concurrent.TimeUnit; - @Component @Slf4j @RequiredArgsConstructor public class Dataloader { - private final ContactRepository contactRepository; - - private final AddressRepository addressRepository; - - private final ContactEventRepository contactEventRepository; - - private final OwnerRepository ownerRepository; - - private final SupportRepository supportRepository; - - private final SourceRepository sourceRepository; - - private final SurveyRepository surveyRepository; - - private final SurveyUnitRepository surveyUnitRepository; - - private final SurveyUnitAddressRepository surveyUnitAddressRepository; - - private final OperatorServiceRepository operatorServiceRepository; - - private final OperatorRepository operatorRepository; - - private final QuestioningRepository questioningRepository; - - private final QuestioningAccreditationRepository questioningAccreditationRepository; - - private final CampaignRepository campaignRepository; - - private final PartitioningRepository partitioningRepository; - private final EventOrderRepository orderRepository; - private final QuestioningEventRepository questioningEventRepository; - - private final ViewRepository viewRepository; @PostConstruct public void init() { - Faker faker = new Faker(); - EasyRandom generator = new EasyRandom(); - initOrder(); -// initContact(faker); -// initMetadata(faker, generator); -// initQuestionning(faker, generator); - // initView(); -// initSurveyUnitAddressAndOperators(faker); } - private void initSurveyUnitAddressAndOperators(Faker faker) { - if (surveyUnitAddressRepository.count() == 0) { - for (SurveyUnit su : surveyUnitRepository.findAll()) { - SurveyUnitAddress a = new SurveyUnitAddress(); - com.github.javafaker.Address fakeAddress = faker.address(); - - a.setCountryName(fakeAddress.country()); - a.setStreetNumber(fakeAddress.buildingNumber()); - a.setStreetName(fakeAddress.streetName()); - a.setZipCode(fakeAddress.zipCode()); - a.setCityName(fakeAddress.cityName()); - su.setSurveyUnitAddress(a); - surveyUnitRepository.save(su); - } - } - - if (operatorServiceRepository.count() == 0) { - Set setOpConj = new HashSet<>(); - OperatorService operatorServiceConj = new OperatorService(); - operatorServiceConj.setName("Conjoncture"); - operatorServiceConj.setMail("conjoncture@Cocorico.fr"); - for (int i = 0; i < 9; i++) { - setOpConj.add(createOperator(faker)); - } - operatorServiceConj.setOperators(setOpConj); - operatorServiceRepository.save(operatorServiceConj); - - Set setOpLogement = new HashSet<>(); - OperatorService operatorServiceLogement = new OperatorService(); - operatorServiceLogement.setName("Logement"); - operatorServiceLogement.setMail("logement@Cocorico.fr"); - operatorServiceRepository.save(operatorServiceLogement); - for (int i = 0; i < 9; i++) { - setOpLogement.add(createOperator(faker)); - } - operatorServiceLogement.setOperators(setOpLogement); - operatorServiceRepository.save(operatorServiceLogement); - - Set setOpEmploi = new HashSet<>(); - OperatorService operatorServiceEmploi = new OperatorService(); - operatorServiceEmploi.setName("Emploi"); - operatorServiceEmploi.setMail("emploi@Cocorico.fr"); - operatorServiceRepository.save(operatorServiceEmploi); - for (int i = 0; i < 9; i++) { - setOpEmploi.add(createOperator(faker)); - } - operatorServiceEmploi.setOperators(setOpEmploi); - operatorServiceRepository.save(operatorServiceEmploi); - - Set setOpPrix = new HashSet<>(); - OperatorService operatorServicePrix = new OperatorService(); - operatorServicePrix.setName("Prix"); - operatorServicePrix.setMail("prix@Cocorico.fr"); - operatorServiceRepository.save(operatorServicePrix); - for (int i = 0; i < 9; i++) { - setOpPrix.add(createOperator(faker)); - } - operatorServicePrix.setOperators(setOpPrix); - operatorServiceRepository.save(operatorServicePrix); - } - - if (operatorServiceRepository.count() == 0) { - for (SurveyUnit su : surveyUnitRepository.findAll()) { - SurveyUnitAddress a = new SurveyUnitAddress(); - com.github.javafaker.Address fakeAddress = faker.address(); - - a.setCountryName(fakeAddress.country()); - a.setStreetNumber(fakeAddress.buildingNumber()); - a.setStreetName(fakeAddress.streetName()); - a.setZipCode(fakeAddress.zipCode()); - a.setCityName(fakeAddress.cityName()); - su.setSurveyUnitAddress(a); - surveyUnitRepository.save(su); - } - } - - } - - private Operator createOperator(Faker faker) { - Operator operator = new Operator(); - Name n = faker.name(); - String name = n.lastName(); - String firstName = n.firstName(); - operator.setLastName(name); - operator.setFirstName(firstName); - operator.setPhoneNumber(faker.phoneNumber().phoneNumber()); - return operatorRepository.save(operator); - } - private void initOrder() { Long nbExistingOrders = orderRepository.count(); @@ -201,443 +48,5 @@ private void initOrder() { } } - private void initContact(Faker faker) { - - List listContact = new ArrayList<>(); - List
listAddresses = new ArrayList<>(); - Long nbExistingContacts = contactRepository.count(); - - log.info("{} contacts exist in database", nbExistingContacts); - - int nbContacts = 1000000; - - for (Long i = nbExistingContacts; i < nbContacts; i++) { - long start = System.currentTimeMillis(); - - final Contact c = new Contact(); - final Address a = new Address(); - - Name n = faker.name(); - String name = n.lastName(); - String firstName = n.firstName(); - com.github.javafaker.Address fakeAddress = faker.address(); - - a.setCountryName(fakeAddress.country()); - a.setStreetNumber(fakeAddress.buildingNumber()); - a.setStreetName(fakeAddress.streetName()); - a.setZipCode(fakeAddress.zipCode()); - a.setCityName(fakeAddress.cityName()); - // addressRepository.save(a); - listAddresses.add(a); - - c.setIdentifier(RandomStringUtils.randomAlphanumeric(7).toUpperCase()); - c.setLastName(name); - c.setFirstName(firstName); - c.setPhone(faker.phoneNumber().phoneNumber()); - c.setGender(Gender.valueOf(faker.demographic().sex())); - c.setFunction(faker.job().title()); - c.setComment(faker.beer().name()); - c.setEmail(firstName.toLowerCase() + "." + name.toLowerCase() + "@cocorico.fr"); - c.setAddress(a); - listContact.add(c); - // contactRepository.save(c); - - if ((i + 1) % 10000 == 0) { - addressRepository.saveAll(listAddresses); - contactRepository.saveAll(listContact); - listAddresses = new ArrayList<>(); - listContact = new ArrayList<>(); - long end = System.currentTimeMillis(); - - // log.info("It took {}ms to execute save() for 100 contacts.", (end - - // start)); - - log.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); - } - - } - - Long nbContactEvents = contactEventRepository.count(); - - for (Long j = nbContactEvents; j < 300; j++) { - Contact contact = contactRepository.findRandomContact(); - ContactEvent contactEvent = new ContactEvent(); - contactEvent.setType(ContactEventType.create); - contactEvent.setEventDate(new Date()); - contactEvent.setContact(contact); - contactEventRepository.save(contactEvent); - Set setContactEvents = new HashSet<>(); - setContactEvents.add(contactEvent); - contact.setContactEvents(setContactEvents); - contactRepository.save(contact); - } - // addressRepository.saveAll(listAddresses); - // contactRepository.saveAll(listContact); - // long end = System.currentTimeMillis(); - // - // log.info("It took {}ms to execute save() for {} contacts.", (end - start), - // (nbContacts - nbExistingContacts)); - - // log.info("It took {}ms to execute saveAll() for {} contacts.", (end - - // start), (nbContacts - nbExistingContacts)); - - } - - private void initMetadata(Faker faker, EasyRandom generator2) { - - int year = 2023; - Random qeRan = new SecureRandom(); - - - Calendar calendar = Calendar.getInstance(); - calendar.set(Calendar.YEAR, year); - calendar.set(Calendar.MONTH, Calendar.DECEMBER); - calendar.set(Calendar.DAY_OF_MONTH, 31); - Date dateEndOfYear = calendar.getTime(); - - Owner ownerInsee = new Owner(); - ownerInsee.setId("insee"); - ownerInsee.setLabel("Insee"); - Set setSourcesInsee = new HashSet<>(); - - Owner ownerAgri = new Owner(); - ownerAgri.setId("agri"); - ownerAgri.setLabel("SSM Agriculture"); - Set setSourcesSsp = new HashSet<>(); - - Support supportInseeHdf = new Support(); - supportInseeHdf.setId("inseehdf"); - supportInseeHdf.setLabel("Insee Hauts-de-France"); - Set setSourcesSupportInsee = new HashSet<>(); - - Support supportSsne = new Support(); - supportSsne.setId("ssne"); - supportSsne.setLabel("Insee Normandie - SSNE"); - Set setSourcesSupportSsne = new HashSet<>(); - - log.info("{} campaigns exist in database", campaignRepository.count()); - - while (sourceRepository.count() < 10) { - - Source source = new Source(); - - String nameSource = "LOAD" + String.valueOf((char) (sourceRepository.count() + 'A')); - - if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { - - source.setId(nameSource); - source.setLongWording("Have you ever heard about " + nameSource + " ?"); - source.setShortWording("Source about " + nameSource); - source.setPeriodicity(PeriodicityEnum.M); - sourceRepository.save(source); - Set setSurveys = new HashSet<>(); - Integer i = qeRan.nextInt(); - if (i % 2 == 0) - setSourcesInsee.add(source); - else { - setSourcesSsp.add(source); - } - - for (int j = 0; j < 4; j++) { - - Survey survey = new Survey(); - String id = nameSource + (year - j); - survey.setId(id); - survey.setYear(year - j); - survey.setLongObjectives("The purpose of this survey is to find out everything you can about " - + nameSource - + ". Your response is essential to ensure the quality and reliability of the results of this survey."); - survey.setShortObjectives("All about " + id); - survey.setCommunication("Communication around " + id); - survey.setSpecimenUrl("http://specimenUrl/" + id); - survey.setDiffusionUrl("http://diffusion/" + id); - survey.setCnisUrl("http://cnis/" + id); - survey.setNoticeUrl("http://notice/" + id); - survey.setVisaNumber(year + RandomStringUtils.randomAlphanumeric(6).toUpperCase()); - survey.setLongWording("Survey " + nameSource + " " + (year - j)); - survey.setShortWording(id); - survey.setSampleSize(Integer.parseInt(RandomStringUtils.randomNumeric(5))); - setSurveys.add(survey); - surveyRepository.save(survey); - Set setCampaigns = new HashSet<>(); - - for (int k = 0; k < 12; k++) { - Campaign campaign = new Campaign(); - int month = k + 1; - String period = month < 10 ? "M0" + month : "M" + month; - campaign.setYear(year - j); - campaign.setPeriod(PeriodEnum.valueOf(period)); - campaign.setId(nameSource + (year - j) + period); - campaign.setCampaignWording( - "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); - setCampaigns.add(campaign); - campaignRepository.save(campaign); - Set setParts = new HashSet<>(); - - for (int l = 0; l < 3; l++) { - - Partitioning part = new Partitioning(); - part.setId(nameSource + (year - j) + "M" + month + "-00" + l); - Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); - Date closingDate = faker.date().between(openingDate, dateEndOfYear); - Date returnDate = faker.date().between(openingDate, closingDate); - Date today = new Date(); - - part.setOpeningDate(openingDate); - part.setClosingDate(closingDate); - part.setReturnDate(returnDate); - setParts.add(part); - part.setCampaign(campaign); - partitioningRepository.save(part); - } - campaign.setSurvey(survey); - campaign.setPartitionings(setParts); - campaignRepository.save(campaign); - - } - survey.setSource(source); - survey.setCampaigns(setCampaigns); - surveyRepository.save(survey); - } - source.setSurveys(setSurveys); - sourceRepository.save(source); - ownerInsee.setSources(setSourcesInsee); - ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(new Owner[]{ - ownerInsee, ownerAgri - })); - - supportInseeHdf.setSources(setSourcesSupportInsee); - supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(new Support[]{ - supportInseeHdf, supportSsne - })); - } - - } - - } - - private void initQuestionning(Faker faker, EasyRandom generator) { - - Long nbExistingQuestionings = questioningRepository.count(); - - log.info("{} questionings exist in database", nbExistingQuestionings); - - long start = System.currentTimeMillis(); - Questioning qu; - QuestioningEvent qe; - Set setQuestioning; - QuestioningAccreditation accreditation; - Set questioningAccreditations; - String fakeSiren; - Random qeRan = new SecureRandom(); - - log.info("{} survey units exist in database", surveyUnitRepository.count()); - - for (Long i = surveyUnitRepository.count(); i < 500000; i++) { - SurveyUnit su = new SurveyUnit(); - fakeSiren = RandomStringUtils.randomNumeric(9); - - su.setIdSu(fakeSiren); - su.setIdentificationName(faker.company().name()); - su.setIdentificationCode(fakeSiren); - surveyUnitRepository.save(su); - - } - for (Long i = nbExistingQuestionings; i < 500000; i++) { - qu = new Questioning(); - qe = new QuestioningEvent(); - List qeList = new ArrayList<>(); - questioningAccreditations = new HashSet<>(); - - setQuestioning = new HashSet<>(); - qu.setModelName("m" + RandomStringUtils.randomNumeric(2)); - qu.setIdPartitioning(partitioningRepository.findRandomPartitioning().getId()); - SurveyUnit su = surveyUnitRepository.findRandomSurveyUnit(); - qu.setSurveyUnit(su); - questioningRepository.save(qu); - setQuestioning.add(qu); - su.setQuestionings(setQuestioning); - - // questioning events - // everybody in INITLA - Optional part = partitioningRepository.findById(qu.getIdPartitioning()); - Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); - qe.setType(TypeQuestioningEvent.INITLA); - qe.setDate(eventDate); - qe.setQuestioning(qu); - qeList.add(qe); - - int qeProfile = qeRan.nextInt(10); - - switch (qeProfile) { - case 0: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.REFUSAL, qu)); - break; - case 1: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PND, qu)); - break; - case 2: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - break; - case 3: - case 4: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - case 5: - case 6: - case 7: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - } - - qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); - - for (int j = 0; j < 4; j++) { - accreditation = new QuestioningAccreditation(); - accreditation.setIdContact(contactRepository.findRandomIdentifierContact()); - accreditation.setQuestioning(qu); - questioningAccreditations.add(accreditation); - questioningAccreditationRepository.save(accreditation); - } - qu.setQuestioningAccreditations(questioningAccreditations); - questioningRepository.save(qu); - if (i % 100 == 0) { - long end = System.currentTimeMillis(); - log.info("It took {}ms to execute save() for 100 questionings.", (end - start)); - start = System.currentTimeMillis(); - } - - } - } - - private void initQuestioningEvents(Faker faker, EasyRandom generator) { - - Long nbExistingQuestioningEvents = questioningEventRepository.count(); - Random qeRan = new SecureRandom(); - - - if (nbExistingQuestioningEvents == 0) { - List listQu = questioningRepository.findAll(); - - for (Questioning qu : listQu) { - - QuestioningEvent qe = new QuestioningEvent(); - List qeList = new ArrayList<>(); - // questioning events - // everybody in INITLA - Optional part = partitioningRepository.findById(qu.getIdPartitioning()); - if (part.isPresent()) { - Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); - qe.setType(TypeQuestioningEvent.INITLA); - qe.setDate(eventDate); - qe.setQuestioning(qu); - qeList.add(qe); - - int qeProfile = qeRan.nextInt(10); - - switch (qeProfile) { - case 0: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.REFUSAL, qu)); - break; - case 1: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PND, qu)); - break; - case 2: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - break; - case 3: - case 4: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - case 5: - case 6: - case 7: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - } - - qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); - } - } - } - - } - - private void initView() { - if (viewRepository.count() == 0) { - - List listAccreditations = questioningAccreditationRepository.findAll(); - listAccreditations.stream().forEach(a -> { - Partitioning p = partitioningRepository.findById(a.getQuestioning().getIdPartitioning()).orElse(null); - View view = new View(); - view.setIdentifier(contactRepository.findById(a.getIdContact()).orElse(null).getIdentifier()); - view.setCampaignId(p.getCampaign().getId()); - view.setIdSu(a.getQuestioning().getSurveyUnit().getIdSu()); - viewRepository.save(view); - }); - - Iterable listContacts = contactRepository.findAll(); - for (Contact contact : listContacts) { - if (viewRepository.findByIdentifier(contact.getIdentifier()).isEmpty()) { - View view = new View(); - view.setIdentifier(contact.getIdentifier()); - viewRepository.save(view); - - } - } - } - } } From fa35d057da93feb9af4e9723c45bd9ab54b9db21 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 09:10:07 +0100 Subject: [PATCH 032/111] refactor: dataloader poc --- .../dataloader/DataloaderPoc.java | 155 +++++------------- 1 file changed, 37 insertions(+), 118 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 77336501..a6c93842 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -24,7 +24,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; -import org.jeasy.random.EasyRandom; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @@ -74,17 +73,19 @@ public class DataloaderPoc { private final ViewRepository viewRepository; + static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + static SecureRandom rnd = new SecureRandom(); + @PostConstruct public void init() { Faker faker = new Faker(); - EasyRandom generator = new EasyRandom(); -// initOrder(); -// initContact(faker); -// initMetadata(faker, generator); - initQuestionning(faker, generator); - // initView(); + initOrder(); + initContact(faker); + initMetadata(faker); + initQuestionning(faker); + initView(); initSurveyUnitAddressAndOperators(faker); } @@ -231,7 +232,7 @@ private void initContact(Faker faker) { // addressRepository.save(a); listAddresses.add(a); - c.setIdentifier(RandomStringUtils.randomAlphanumeric(7).toUpperCase()); + c.setIdentifier(randomString(7).toUpperCase()); c.setLastName(name); c.setFirstName(firstName); c.setPhone(faker.phoneNumber().phoneNumber()); @@ -241,7 +242,6 @@ private void initContact(Faker faker) { c.setEmail(firstName.toLowerCase() + "." + name.toLowerCase() + "@cocorico.fr"); c.setAddress(a); listContact.add(c); - // contactRepository.save(c); if ((i + 1) % 10000 == 0) { addressRepository.saveAll(listAddresses); @@ -250,9 +250,6 @@ private void initContact(Faker faker) { listContact = new ArrayList<>(); long end = System.currentTimeMillis(); - // log.info("It took {}ms to execute save() for 100 contacts.", (end - - // start)); - log.info("It took {}ms to execute saveAll() for 10000 contacts.", (end - start)); } @@ -272,19 +269,11 @@ private void initContact(Faker faker) { contact.setContactEvents(setContactEvents); contactRepository.save(contact); } - // addressRepository.saveAll(listAddresses); - // contactRepository.saveAll(listContact); - // long end = System.currentTimeMillis(); - // - // log.info("It took {}ms to execute save() for {} contacts.", (end - start), - // (nbContacts - nbExistingContacts)); - // log.info("It took {}ms to execute saveAll() for {} contacts.", (end - - // start), (nbContacts - nbExistingContacts)); } - private void initMetadata(Faker faker, EasyRandom generator2) { + private void initMetadata(Faker faker) { int year = 2023; @@ -319,8 +308,8 @@ private void initMetadata(Faker faker, EasyRandom generator2) { while (sourceRepository.count() < 10) { Source source = new Source(); - - String nameSource = "LOAD"+String.valueOf((char)(sourceRepository.count() + 'A')); + + String nameSource = "LOAD" + sourceRepository.count() + 'A'; if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { @@ -330,7 +319,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { source.setPeriodicity(PeriodicityEnum.M); sourceRepository.save(source); Set setSurveys = new HashSet<>(); - Integer i = new SecureRandom().nextInt(); + Integer i = rnd.nextInt(); if (i % 2 == 0) setSourcesInsee.add(source); else { @@ -352,7 +341,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { survey.setDiffusionUrl("http://diffusion/" + id); survey.setCnisUrl("http://cnis/" + id); survey.setNoticeUrl("http://notice/" + id); - survey.setVisaNumber(year + RandomStringUtils.randomAlphanumeric(6).toUpperCase()); + survey.setVisaNumber(year + randomString(6).toUpperCase()); survey.setLongWording("Survey " + nameSource + " " + (year - j)); survey.setShortWording(id); survey.setSampleSize(Integer.parseInt(RandomStringUtils.randomNumeric(5))); @@ -363,7 +352,7 @@ private void initMetadata(Faker faker, EasyRandom generator2) { for (int k = 0; k < 12; k++) { Campaign campaign = new Campaign(); int month = k + 1; - String period = month<10? "M0" + month:"M"+month; + String period = month < 10 ? "M0" + month : "M" + month; campaign.setYear(year - j); campaign.setPeriod(PeriodEnum.valueOf(period)); campaign.setId(nameSource + (year - j) + period); @@ -380,7 +369,6 @@ private void initMetadata(Faker faker, EasyRandom generator2) { Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); Date closingDate = faker.date().between(openingDate, dateEndOfYear); Date returnDate = faker.date().between(openingDate, closingDate); - Date today = new Date(); part.setOpeningDate(openingDate); part.setClosingDate(closingDate); @@ -402,22 +390,18 @@ private void initMetadata(Faker faker, EasyRandom generator2) { sourceRepository.save(source); ownerInsee.setSources(setSourcesInsee); ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(new Owner[] { - ownerInsee, ownerAgri - })); + ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); supportInseeHdf.setSources(setSourcesSupportInsee); supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(new Support[] { - supportInseeHdf, supportSsne - })); + supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); } } } - private void initQuestionning(Faker faker, EasyRandom generator) { + private void initQuestionning(Faker faker) { Long nbExistingQuestionings = questioningRepository.count(); @@ -430,7 +414,6 @@ private void initQuestionning(Faker faker, EasyRandom generator) { QuestioningAccreditation accreditation; Set questioningAccreditations; String fakeSiren; - Random qeRan = new SecureRandom(); log.info("{} survey units exist in database", surveyUnitRepository.count()); @@ -468,7 +451,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { qe.setQuestioning(qu); qeList.add(qe); - int qeProfile = qeRan.nextInt(10); + int qeProfile = rnd.nextInt(10); switch (qeProfile) { case 0: @@ -492,8 +475,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); break; - case 3: - case 4: + case 3, 4: qeList.add(new QuestioningEvent( faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); @@ -504,9 +486,7 @@ private void initQuestionning(Faker faker, EasyRandom generator) { faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; - case 5: - case 6: - case 7: + case 5, 6, 7: qeList.add(new QuestioningEvent( faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); @@ -514,9 +494,15 @@ private void initQuestionning(Faker faker, EasyRandom generator) { faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; + default: + qeList.add(new QuestioningEvent( + faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + TypeQuestioningEvent.PARTIELINT, qu)); + break; + } - qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); + qeList.stream().forEach(questioningEventRepository::save); for (int j = 0; j < 4; j++) { accreditation = new QuestioningAccreditation(); @@ -536,82 +522,6 @@ private void initQuestionning(Faker faker, EasyRandom generator) { } } - private void initQuestioningEvents(Faker faker, EasyRandom generator) { - - Long nbExistingQuestioningEvents = questioningEventRepository.count(); - Random qeRan = new SecureRandom(); - - - if (nbExistingQuestioningEvents == 0) { - List listQu = questioningRepository.findAll(); - - for (Questioning qu : listQu) { - - QuestioningEvent qe = new QuestioningEvent(); - List qeList = new ArrayList<>(); - // questioning events - // everybody in INITLA - Optional part = partitioningRepository.findById(qu.getIdPartitioning()); - Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); - qe.setType(TypeQuestioningEvent.INITLA); - qe.setDate(eventDate); - qe.setQuestioning(qu); - qeList.add(qe); - - int qeProfile = qeRan.nextInt(10); - - switch (qeProfile) { - case 0: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.REFUSAL, qu)); - break; - case 1: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PND, qu)); - break; - case 2: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - break; - case 3: - case 4: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - case 5: - case 6: - case 7: - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.PARTIELINT, qu)); - qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), - TypeQuestioningEvent.VALINT, qu)); - break; - } - - qeList.stream().forEach(questEvent -> questioningEventRepository.save(questEvent)); - - } - } - - } private void initView() { if (viewRepository.count() == 0) { @@ -638,4 +548,13 @@ private void initView() { } } + + String randomString(int len) { + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) + sb.append(AB.charAt(rnd.nextInt(AB.length()))); + return sb.toString(); + } + + } From 00304d62ac4eed614048dc05bfe157dac444d200 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 09:40:44 +0100 Subject: [PATCH 033/111] refactor: dataloaderpoc --- .../dataloader/DataloaderPoc.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index a6c93842..3b13c1a1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -22,7 +22,6 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @@ -74,6 +73,9 @@ public class DataloaderPoc { private final ViewRepository viewRepository; static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + static final String NUMBERS = "0123456789"; + static SecureRandom rnd = new SecureRandom(); @PostConstruct @@ -344,7 +346,7 @@ private void initMetadata(Faker faker) { survey.setVisaNumber(year + randomString(6).toUpperCase()); survey.setLongWording("Survey " + nameSource + " " + (year - j)); survey.setShortWording(id); - survey.setSampleSize(Integer.parseInt(RandomStringUtils.randomNumeric(5))); + survey.setSampleSize(Integer.parseInt(randomNumeric(5))); setSurveys.add(survey); surveyRepository.save(survey); Set setCampaigns = new HashSet<>(); @@ -419,7 +421,7 @@ private void initQuestionning(Faker faker) { for (Long i = surveyUnitRepository.count(); i < 500000; i++) { SurveyUnit su = new SurveyUnit(); - fakeSiren = RandomStringUtils.randomNumeric(9); + fakeSiren = randomNumeric(9); su.setIdSu(fakeSiren); su.setIdentificationName(faker.company().name()); @@ -434,7 +436,7 @@ private void initQuestionning(Faker faker) { questioningAccreditations = new HashSet<>(); setQuestioning = new HashSet<>(); - qu.setModelName("m" + RandomStringUtils.randomNumeric(2)); + qu.setModelName("m" + randomNumeric(2)); qu.setIdPartitioning(partitioningRepository.findRandomPartitioning().getId()); SurveyUnit su = surveyUnitRepository.findRandomSurveyUnit(); qu.setSurveyUnit(su); @@ -556,5 +558,12 @@ String randomString(int len) { return sb.toString(); } + String randomNumeric(int len) { + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) + sb.append(NUMBERS.charAt(rnd.nextInt(AB.length()))); + return sb.toString(); + } + } From f220b13b0d6c9c41fd82687cc2c50834958c4360 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 10:20:02 +0100 Subject: [PATCH 034/111] refactor: improve exception in user service --- .../user/controller/UserController.java | 8 +++++++- .../user/service/UserService.java | 3 ++- .../user/service/impl/UserServiceImpl.java | 5 +++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 2fff5d6d..8b16b783 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.user.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; @@ -118,7 +119,12 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody } log.info("Updating user with the identifier {}", userDto.getIdentifier()); - User userUpdate = userService.updateUser(user, null); + User userUpdate = null; + try { + userUpdate = userService.updateUser(user, null); + } catch (NotFoundException e) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Problem when saving user"); + } return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(userUpdate)); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java index 604371ab..ed50b0d7 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.user.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -45,7 +46,7 @@ public interface UserService { public User createUser(User user, JsonNode payload); - public User updateUser(User user, JsonNode payload); + public User updateUser(User user, JsonNode payload) throws NotFoundException; public void deleteUserAndEvents(User user); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index 02ced26a..7f95557e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.user.service.impl; import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; import fr.insee.survey.datacollectionmanagement.user.domain.User; @@ -57,9 +58,9 @@ public User createUser(User user, JsonNode payload) { } @Override - public User updateUser(User user, JsonNode payload) { + public User updateUser(User user, JsonNode payload) throws NotFoundException { - User existingUser = findByIdentifier(user.getIdentifier()).get(); + User existingUser = findByIdentifier(user.getIdentifier()).orElseThrow(() -> new NotFoundException("user not found")); Set setUserEventsUser = existingUser.getUserEvents(); UserEvent userEventUpdate = userEventService.createUserEvent(user, UserEvent.UserEventType.UPDATE, From 805736d76631a063d163befa88c252c17dc436db Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 10:20:25 +0100 Subject: [PATCH 035/111] refactor: add validatoin to contact domain dto --- .../contact/controller/ContactController.java | 5 +- .../controller/ContactEventController.java | 59 ++++++++----------- .../contact/dto/ContactDto.java | 4 ++ .../contact/dto/ContactEventDto.java | 7 ++- .../contact/dto/ContactFirstLoginDto.java | 2 + .../validation/ContactEventTypeValid.java | 26 ++++++++ .../validation/ContactEventTypeValidator.java | 23 ++++++++ .../validation/ContactGenderValid.java | 26 ++++++++ .../validation/ContactGenderValidator.java | 23 ++++++++ 9 files changed, 137 insertions(+), 38 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValid.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValidator.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValid.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index b25a4b52..eda9c0cc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -19,6 +19,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -29,6 +30,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -45,6 +47,7 @@ @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") @Slf4j @RequiredArgsConstructor +@Validated public class ContactController { private final ContactService contactService; @@ -109,7 +112,7 @@ public ResponseEntity getContact(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody ContactDto contactDto) { + public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody @Valid ContactDto contactDto) { if (StringUtils.isBlank(contactDto.getIdentifier()) || !contactDto.getIdentifier().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and contact identifier don't match"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index 5e4e6734..3e6d688b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -3,11 +3,9 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; -import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; import fr.insee.survey.datacollectionmanagement.contact.dto.ContactEventDto; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; -import fr.insee.survey.datacollectionmanagement.exception.EventException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; @@ -15,6 +13,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.data.domain.PageImpl; @@ -23,6 +22,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -30,14 +30,14 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; @RestController(value = "contactEvents") @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " - + "|| @AuthorizeMethodDecider.isWebClient() "+ "|| @AuthorizeMethodDecider.isRespondent() " + + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isRespondent() " + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") @RequiredArgsConstructor +@Validated public class ContactEventController { private final ContactEventService contactEventService; @@ -77,33 +77,27 @@ public ResponseEntity getContactContactEvents(@PathVariable("id") String iden @ApiResponse(responseCode = "400", description = "Bad request"), @ApiResponse(responseCode = "404", description = "Not found") }) - public ResponseEntity postContactEvent(@RequestBody ContactEventDto contactEventDto) { - try { - - Optional optContact = contactService.findByIdentifier(contactEventDto.getIdentifier()); - if (optContact.isPresent()) { - Contact contact = optContact.get(); - ContactEvent contactEvent = convertToEntity(contactEventDto); - ContactEvent newContactEvent = contactEventService.saveContactEvent(contactEvent); - Set setContactEvents = contact.getContactEvents(); - setContactEvents.add(newContactEvent); - contact.setContactEvents(setContactEvents); - contactService.saveContact(contact); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(newContactEvent)); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); - } catch (EventException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Event not recognized: only [" + Stream.of(ContactEventType.values()) - .map(ContactEventType::name).collect(Collectors.joining(", ")) + "] are possible"); - } - + public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto contactEventDto) { + + Optional optContact = contactService.findByIdentifier(contactEventDto.getIdentifier()); + if (optContact.isPresent()) { + Contact contact = optContact.get(); + ContactEvent contactEvent = convertToEntity(contactEventDto); + ContactEvent newContactEvent = contactEventService.saveContactEvent(contactEvent); + Set setContactEvents = contact.getContactEvents(); + setContactEvents.add(newContactEvent); + contact.setContactEvents(setContactEvents); + contactService.saveContact(contact); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(newContactEvent)); + } else + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); } + @Operation(summary = "Delete a contact event") @DeleteMapping(value = Constants.API_CONTACTEVENTS_ID, produces = "application/json") @ApiResponses(value = { @@ -136,11 +130,8 @@ private ContactEventDto convertToDto(ContactEvent contactEvent) { return ceDto; } - private ContactEvent convertToEntity(ContactEventDto contactEventDto) throws EventException { - ContactEvent contactEvent = modelMapper.map(contactEventDto, ContactEvent.class); - if (contactEvent.getType() == null) - throw new EventException("Contact event not recognized"); - return contactEvent; + private ContactEvent convertToEntity(ContactEventDto contactEventDto) { + return modelMapper.map(contactEventDto, ContactEvent.class); } class ContactEventPage extends PageImpl { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java index 6d157baa..5f167ee6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java @@ -1,6 +1,8 @@ package fr.insee.survey.datacollectionmanagement.contact.dto; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import fr.insee.survey.datacollectionmanagement.contact.validation.ContactGenderValid; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -8,8 +10,10 @@ @Setter public class ContactDto{ + @NotBlank(message = "Id can't be empty") private String identifier; private String externalId; + @ContactGenderValid private Contact.Gender civility; private String lastName; private String firstName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java index cb1f603b..a84cf5b7 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java @@ -1,12 +1,12 @@ package fr.insee.survey.datacollectionmanagement.contact.dto; -import java.util.Date; - import com.fasterxml.jackson.databind.JsonNode; - +import fr.insee.survey.datacollectionmanagement.contact.validation.ContactEventTypeValid; import lombok.Getter; import lombok.Setter; +import java.util.Date; + @Getter @Setter public class ContactEventDto { @@ -14,6 +14,7 @@ public class ContactEventDto { private Long id; private String identifier; private Date eventDate; + @ContactEventTypeValid private String type; private JsonNode payload; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java index 61735601..aacbf99d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.contact.dto; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import fr.insee.survey.datacollectionmanagement.contact.validation.ContactGenderValid; import lombok.Getter; import lombok.Setter; @@ -10,6 +11,7 @@ public class ContactFirstLoginDto{ private String identifier; private String externalId; + @ContactGenderValid private Contact.Gender civility; private String lastName; private String firstName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValid.java new file mode 100644 index 00000000..da18c277 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValid.java @@ -0,0 +1,26 @@ +package fr.insee.survey.datacollectionmanagement.contact.validation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Target({FIELD, PARAMETER, METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Constraint(validatedBy = ContactEventTypeValidator.class) +public @interface ContactEventTypeValid { + //error message + String message() default "Type missing or not recognized. Only create, update, merged, firstConnect, reinitPassword are valid"; + + //represents group of constraints + Class[] groups() default {}; + + //represents additional information about annotation + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValidator.java new file mode 100644 index 00000000..f2de33f6 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactEventTypeValidator.java @@ -0,0 +1,23 @@ +package fr.insee.survey.datacollectionmanagement.contact.validation; + +import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.Arrays; + +public class ContactEventTypeValidator implements ConstraintValidator { + + + @Override + public void initialize(ContactEventTypeValid constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value == null) + return false; + return Arrays.stream(ContactEvent.ContactEventType.values()).anyMatch(v -> value.equalsIgnoreCase(v.name())); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValid.java new file mode 100644 index 00000000..5be66de4 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValid.java @@ -0,0 +1,26 @@ +package fr.insee.survey.datacollectionmanagement.contact.validation; + +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; + +@Target({FIELD, PARAMETER, METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Constraint(validatedBy = ContactGenderValidator.class) +public @interface ContactGenderValid { + //error message + String message() default "Type missing or not recognized. Only Female, Male, Undefined are valid"; + + //represents group of constraints + Class[] groups() default {}; + + //represents additional information about annotation + Class[] payload() default {}; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java new file mode 100644 index 00000000..5116f4d6 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java @@ -0,0 +1,23 @@ +package fr.insee.survey.datacollectionmanagement.contact.validation; + +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +import java.util.Arrays; + +public class ContactGenderValidator implements ConstraintValidator { + + + @Override + public void initialize(ContactGenderValid constraintAnnotation) { + ConstraintValidator.super.initialize(constraintAnnotation); + } + + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (value == null) + return false; + return Arrays.stream(Contact.Gender.values()).anyMatch(v -> value.equalsIgnoreCase(v.name())); + } +} \ No newline at end of file From 976fbcfb5e87514de621187ff46fa1d001ef30d3 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 11:24:05 +0100 Subject: [PATCH 036/111] build: spring boot 3.2.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1ca885cb..a22fe2d9 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.springframework.boot spring-boot-starter-parent - 3.1.5 + 3.2.0 fr.insee.survey From 45e9f8f295a253472f860cde88718b654c96b332 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 27 Nov 2023 11:35:12 +0100 Subject: [PATCH 037/111] refactor: validation for contact dto --- .../contact/controller/ContactController.java | 8 ++++---- .../datacollectionmanagement/contact/dto/ContactDto.java | 3 +-- .../query/controller/WebclientController.java | 2 +- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index eda9c0cc..62973541 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -160,7 +160,7 @@ public ResponseEntity deleteContact(@PathVariable("id") String id) { if (contact.isPresent()) { contactService.deleteContactAddressEvent(contact.get()); - viewService.findViewByIdentifier(id).stream().forEach(c -> viewService.deleteView(c)); + viewService.findViewByIdentifier(id).stream().forEach(viewService::deleteView); questioningAccreditationService.findByContactIdentifier(id).stream().forEach(acc -> { Questioning questioning = questioningService.findbyId(acc.getQuestioning().getId()).get(); Set newSet = questioning.getQuestioningAccreditations(); @@ -182,7 +182,7 @@ public ResponseEntity deleteContact(@PathVariable("id") String id) { private ContactDto convertToDto(Contact contact) { ContactDto contactDto = modelMapper.map(contact, ContactDto.class); - contactDto.setCivility(contact.getGender()); + contactDto.setCivility(contact.getGender().name()); return contactDto; } @@ -196,7 +196,7 @@ private ContactFirstLoginDto convertToFirstLoginDto(Contact contact) { private Contact convertToEntity(ContactDto contactDto) throws ParseException, NoSuchElementException { Contact contact = modelMapper.map(contactDto, Contact.class); - contact.setGender(contactDto.getCivility()); + contact.setGender(Contact.Gender.valueOf(contactDto.getCivility())); Optional oldContact = contactService.findByIdentifier(contactDto.getIdentifier()); if (oldContact.isEmpty()) { throw new NoSuchElementException(); @@ -210,7 +210,7 @@ private Contact convertToEntity(ContactDto contactDto) throws ParseException, No private Contact convertToEntityNewContact(ContactDto contactDto) { Contact contact = modelMapper.map(contactDto, Contact.class); - contact.setGender(contactDto.getCivility()); + contact.setGender(Contact.Gender.valueOf(contactDto.getCivility())); return contact; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java index 5f167ee6..172a55f5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java @@ -1,6 +1,5 @@ package fr.insee.survey.datacollectionmanagement.contact.dto; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.validation.ContactGenderValid; import jakarta.validation.constraints.NotBlank; import lombok.Getter; @@ -14,7 +13,7 @@ public class ContactDto{ private String identifier; private String externalId; @ContactGenderValid - private Contact.Gender civility; + private String civility; private String lastName; private String firstName; private String function; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index e527b55e..bb8411a8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -589,7 +589,7 @@ private SupportDto convertToDto(Support support) { private ContactDto convertToDto(Contact contact) { ContactDto contactDto = modelMapper.map(contact, ContactDto.class); - contactDto.setCivility(contact.getGender()); + contactDto.setCivility(contact.getGender().name()); return contactDto; } From b494786e3abf4b9de509fa33f6ff57e111d3df22 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 4 Dec 2023 16:08:05 +0100 Subject: [PATCH 038/111] fix: replacer @data lombok with @getter @setter in entities --- .../contact/domain/Address.java | 7 +- .../contact/domain/Contact.java | 17 +-- .../contact/domain/ContactEvent.java | 7 +- .../exception/ApiError.java | 42 +++++ .../exception/ApiExceptionComponent.java | 56 +++++++ .../exception/ExceptionControllerAdvice.java | 144 ++++++++++++++++++ .../metadata/domain/Campaign.java | 5 +- .../metadata/domain/CampaignEvent.java | 16 +- .../metadata/domain/Owner.java | 15 +- .../metadata/domain/Partitioning.java | 6 +- .../metadata/domain/Source.java | 7 +- .../metadata/domain/Support.java | 15 +- .../metadata/domain/Survey.java | 5 +- .../questioning/domain/EventOrder.java | 7 +- .../questioning/domain/Operator.java | 6 +- .../questioning/domain/OperatorService.java | 7 +- .../questioning/domain/Questioning.java | 10 +- .../domain/QuestioningAccreditation.java | 9 +- .../questioning/domain/QuestioningEvent.java | 6 +- .../questioning/domain/SurveyUnit.java | 6 +- .../user/domain/SourceAccreditation.java | 3 +- .../user/domain/UserEvent.java | 3 +- 22 files changed, 310 insertions(+), 89 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java index 4ad81cc0..7152d0b2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java @@ -1,14 +1,15 @@ package fr.insee.survey.datacollectionmanagement.contact.domain; - import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; @Entity -@Data +@Getter +@Setter public class Address { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java index 0580d58e..1f8ae525 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java @@ -1,12 +1,10 @@ package fr.insee.survey.datacollectionmanagement.contact.domain; -import java.util.Set; - - import jakarta.persistence.*; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.ToString; +import lombok.Getter; +import lombok.Setter; + +import java.util.Set; @Entity @Table(indexes = { @@ -14,7 +12,8 @@ @Index(name = "lnfn_index", columnList = "lastName, firstName"), @Index(name = "email_index", columnList = "email") }) -@Data +@Getter +@Setter public class Contact { public enum Gender { @@ -35,13 +34,9 @@ public enum Gender { private boolean emailVerify; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Address address; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set contactEvents; @Enumerated(EnumType.STRING) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index cb3b2836..dd1d1efe 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -9,7 +9,8 @@ import java.util.Date; @Entity -@Data +@Getter +@Setter @NoArgsConstructor public class ContactEvent { @@ -21,14 +22,12 @@ public enum ContactEventType { @GeneratedValue private Long id; private Date eventDate; - @NonNull + @JdbcTypeCode(SqlTypes.INTEGER) @Enumerated(EnumType.ORDINAL) private ContactEventType type; @ManyToOne - @EqualsAndHashCode.Exclude - @ToString.Exclude private Contact contact; @JdbcTypeCode(SqlTypes.JSON) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java new file mode 100644 index 00000000..dfff8572 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java @@ -0,0 +1,42 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.http.HttpStatus; + +import java.util.Date; + +/** + * Default API Error object returned as JSON response to client + */ +@Data +@AllArgsConstructor +public class ApiError { + private Integer code; + private String path; + private String message; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy hh:mm:ss") + private Date timestamp; + + /** + * @param status http status for this error + * @param path origin request path + * @param timestamp timestamp of the generated error + * @param errorMessage error message + */ + public ApiError (HttpStatus status, String path, Date timestamp, String errorMessage) { + if (errorMessage == null || errorMessage.isEmpty()) { + errorMessage = status.getReasonPhrase(); + } + createApiError(status.value(), path, timestamp, errorMessage); + } + + private void createApiError(int code, String path, Date timestamp, String errorMessage) { + this.code = code; + this.path = path; + this.message = errorMessage; + this.timestamp = timestamp; + } +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java new file mode 100644 index 00000000..1dab632a --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java @@ -0,0 +1,56 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +import org.springframework.boot.web.error.ErrorAttributeOptions; +import org.springframework.boot.web.servlet.error.ErrorAttributes; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; + +import java.util.Date; +import java.util.Map; + + +/** + * Component used to build APIError objects + */ +@Component +public class ApiExceptionComponent { + + private final ErrorAttributes errorAttributes; + + public ApiExceptionComponent(ErrorAttributes errorAttributes) { + this.errorAttributes = errorAttributes; + } + + /** + * + * @param request origin request + * @param status status from exception + * @param errorMessage error message + * @return error object used for JSON response + */ + public ApiError buildApiErrorObject(WebRequest request, HttpStatus status, String errorMessage) { + String path = getPath(request); + Date timestamp = getTimeStamp(request); + return new ApiError(status, path, timestamp, errorMessage); + } + + /** + * @param request origin request + * @return get timestamp from error attributes + */ + private Date getTimeStamp(WebRequest request) { + Map attributes = errorAttributes.getErrorAttributes(request, ErrorAttributeOptions.defaults()); + return ((Date) attributes.get("timestamp")); + } + + /** + * + * @param request origin request + * @return get path from origin request + */ + private String getPath(WebRequest request) { + return ((ServletWebRequest) request).getRequest().getRequestURI(); + } +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java new file mode 100644 index 00000000..07042ddc --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java @@ -0,0 +1,144 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import jakarta.validation.ConstraintViolationException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.NoHandlerFoundException; + +/** + * Handle API exceptions for project + * Do not work on exceptions occuring before/outside controllers scope + */ +@ControllerAdvice +@Slf4j +@RequiredArgsConstructor +public class ExceptionControllerAdvice { + + private final ApiExceptionComponent errorComponent; + + private static final String ERROR_OCCURRED_LABEL = "An error has occurred"; + + /** + * Global method to process the catched exception + * + * @param ex Exception catched + * @param status status linked with this exception + * @param request request initiating the exception + * @return the apierror object with linked status code + */ + private ResponseEntity processException(Exception ex, HttpStatus status, WebRequest request) { + return processException(ex, status, request, null); + } + + /** + * Global method to process the catched exception + * + * @param ex Exception catched + * @param status status linked with this exception + * @param request request initiating the exception + * @param overrideErrorMessage message overriding default error message from exception + * @return the apierror object with linked status code + */ + private ResponseEntity processException(Exception ex, HttpStatus status, WebRequest request, String overrideErrorMessage) { + String errorMessage = ex.getMessage(); + if (overrideErrorMessage != null) { + errorMessage = overrideErrorMessage; + } + ApiError error = errorComponent.buildApiErrorObject(request, status, errorMessage); + return new ResponseEntity<>(error, status); + } + + @ExceptionHandler(NoHandlerFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + @ResponseBody + public void noHandlerFoundException(NoHandlerFoundException e, WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.NOT_FOUND, request); + } + + @ExceptionHandler(AccessDeniedException.class) + @ResponseStatus(HttpStatus.FORBIDDEN) + @ResponseBody + public void accessDeniedException(AccessDeniedException e, WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.FORBIDDEN, request); + } + + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseBody + public void handleMethodArgumentNotValid( + MethodArgumentNotValidException e, + WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.BAD_REQUEST, request, "Invalid parameters"); + } + + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + @ExceptionHandler(ConstraintViolationException.class) + @ResponseBody + public void handleConstraintViolation( + ConstraintViolationException e, + WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.BAD_REQUEST, request, e.getMessage()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + @ResponseBody + public void handleHttpMessageNotReadableException( + HttpMessageNotReadableException e, WebRequest request) { + log.error(e.getMessage(), e); + + Throwable rootCause = e.getRootCause(); + + String errorMessage = "Error when deserializing JSON"; + if (rootCause instanceof JsonParseException parseException) { + String location = parseException.getLocation() != null ? "[line: " + parseException.getLocation().getLineNr() + ", column: " + parseException.getLocation().getColumnNr() + "]" : ""; + errorMessage = "Error with JSON syntax. Check that your json is well formatted: " + parseException.getOriginalMessage() + " " + location; + } + if (rootCause instanceof JsonMappingException mappingException) { + String location = mappingException.getLocation() != null ? "[line: " + mappingException.getLocation().getLineNr() + ", column: " + mappingException.getLocation().getColumnNr() + "]" : ""; + errorMessage = "Error when deserializing JSON. Check that your JSON properties are of the expected types " + location; + } + processException(e, HttpStatus.BAD_REQUEST, request, errorMessage); + } + + @ExceptionHandler(NotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + @ResponseBody + public void notFoundException(NotFoundException e, WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.NOT_FOUND, request); + } + + + @ExceptionHandler(HttpClientErrorException.class) + @ResponseBody + public void exceptions(HttpClientErrorException e, WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.valueOf(e.getStatusCode().value()), request, ERROR_OCCURRED_LABEL); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ResponseBody + public void exceptions(Exception e, WebRequest request) { + log.error(e.getMessage(), e); + processException(e, HttpStatus.INTERNAL_SERVER_ERROR, request, ERROR_OCCURRED_LABEL); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java index 819bb0d2..26a15a1d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Campaign.java @@ -7,7 +7,8 @@ import java.util.Set; @Entity -@Data +@Getter +@Setter @NoArgsConstructor @Table(indexes = { @Index(name = "year_index", columnList = "year_value"), @@ -30,8 +31,6 @@ public class Campaign { private String campaignWording; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set partitionings; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java index 29a60f67..4443a213 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java @@ -1,20 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Date; - - import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.ToString; +import lombok.*; + +import java.util.Date; @Entity -@Data +@Getter +@Setter @NoArgsConstructor public class CampaignEvent { @@ -27,8 +23,6 @@ public class CampaignEvent { private Date date; @ManyToOne - @EqualsAndHashCode.Exclude - @ToString.Exclude private Campaign campaign; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java index 26311e66..f63ce85c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Owner.java @@ -1,17 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Set; - - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.ToString; +import lombok.Getter; +import lombok.Setter; + +import java.util.Set; @Entity -@Data +@Getter +@Setter public class Owner { @Id @@ -22,8 +21,6 @@ public class Owner { private String logo; @OneToMany - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set sources; } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java index 53b81b38..29c661a2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Partitioning.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; import jakarta.persistence.*; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import java.util.Date; @Entity -@Data +@Getter +@Setter @Table(indexes = { @Index(name = "campainId_index", columnList = "campaign_id") }) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java index 1da027d0..8e47519a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Source.java @@ -8,7 +8,8 @@ import java.util.Set; @Entity -@Data +@Getter +@Setter @NoArgsConstructor public class Source { @@ -23,13 +24,9 @@ public class Source { private Boolean mandatoryMySurveys; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set surveys; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set sourceAccreditations; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java index 7918fbaa..101bc512 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Support.java @@ -1,17 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import java.util.Set; - - import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.ToString; +import lombok.Getter; +import lombok.Setter; + +import java.util.Set; @Entity -@Data +@Getter +@Setter public class Support { @Id @@ -27,8 +26,6 @@ public class Support { private String zipCode; @OneToMany - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set sources; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java index b989f3d2..2d65b999 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/Survey.java @@ -6,7 +6,8 @@ import java.util.Set; @Entity -@Data +@Getter +@Setter @NoArgsConstructor @Table(indexes = { @Index(name = "surveyyear_index", columnList = "year_value"), @@ -36,8 +37,6 @@ public class Survey { private String communication; @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set campaigns; @ManyToOne diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java index 35703e54..13fd490c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/EventOrder.java @@ -1,13 +1,14 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; - import jakarta.persistence.Entity; import jakarta.persistence.Id; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; @Entity -@Data +@Getter +@Setter public class EventOrder { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java index d73f6e17..50b4c959 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java @@ -4,10 +4,12 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; @Entity -@Data +@Getter +@Setter public class Operator { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java index 47cc3bbc..e0f2bd21 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java @@ -4,14 +4,13 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.ToString; +import lombok.*; import java.util.Set; @Entity -@Data +@Getter +@Setter public class OperatorService { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java index ab4cadba..9d34e72e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java @@ -6,8 +6,8 @@ import java.util.Set; @Entity -@Data -@NoArgsConstructor +@Getter +@Setter@NoArgsConstructor @Table(indexes = { @Index(name = "idPartitioning_index", columnList = "idPartitioning") }) @@ -23,18 +23,12 @@ public class Questioning { private String idPartitioning; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set questioningAccreditations; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @EqualsAndHashCode.Exclude - @ToString.Exclude private Set questioningEvents; @ManyToOne(fetch = FetchType.EAGER) - @EqualsAndHashCode.Exclude - @ToString.Exclude @NonNull private SurveyUnit surveyUnit; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java index 7ac37774..4c310bab 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java @@ -1,15 +1,13 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; import jakarta.persistence.*; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.NonNull; +import lombok.*; import java.util.Date; @Entity -@Data +@Getter +@Setter @NoArgsConstructor @Table(indexes = { @Index(name = "idContact_index", columnList = "idContact"), @@ -28,7 +26,6 @@ public class QuestioningAccreditation { private String idContact; @ManyToOne - @EqualsAndHashCode.Exclude private Questioning questioning; @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java index c6936438..20664cb4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java @@ -4,14 +4,16 @@ import com.fasterxml.jackson.databind.JsonNode; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import jakarta.persistence.*; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; import java.util.Date; @Entity -@Data +@Getter +@Setter public class QuestioningEvent { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java index df63bcbf..97f8aa66 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; import jakarta.persistence.*; -import lombok.Data; +import lombok.Getter; +import lombok.Setter; import java.util.Set; @Entity -@Data +@Getter +@Setter @Table(indexes = { @Index(name = "identificationName_index", columnList = "identificationName"), @Index(name = "identificationCode_index", columnList = "identificationCode") }) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java index 928294da..fbba76cd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java @@ -11,7 +11,8 @@ import java.util.Date; @Entity -@Getter@Setter +@Getter +@Setter @NoArgsConstructor public class SourceAccreditation { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index e8c9ca4f..ef808a7b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -9,7 +9,8 @@ import java.util.Date; @Entity -@Getter@Setter +@Getter +@Setter @NoArgsConstructor public class UserEvent { From 02de5b40e8363423de84da20faf266b72d8d74ad Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 10:14:30 +0100 Subject: [PATCH 039/111] refactor: handle exceptions with controller advice --- .../contact/controller/AddressController.java | 71 +++++----- .../contact/controller/ContactController.java | 63 ++++----- .../controller/ContactEventController.java | 61 ++++----- .../contact/service/AddressService.java | 9 +- .../contact/service/ContactEventService.java | 15 +- .../contact/service/ContactService.java | 16 +-- .../service/impl/AddressServiceImpl.java | 7 +- .../service/impl/ContactEventServiceImpl.java | 6 +- .../service/impl/ContactServiceImpl.java | 32 ++--- .../exception/NotFoundException.java | 2 +- .../controller/CampaignController.java | 63 +++------ .../controller/MetadataController.java | 13 +- .../metadata/controller/OwnerController.java | 22 ++- .../controller/PartitioningController.java | 45 +++--- .../metadata/controller/SourceController.java | 47 +++---- .../controller/SupportController.java | 24 ++-- .../metadata/controller/SurveyController.java | 40 ++---- .../metadata/service/CampaignService.java | 7 +- .../metadata/service/OwnerService.java | 9 +- .../metadata/service/PartitioningService.java | 7 +- .../metadata/service/SourceService.java | 9 +- .../metadata/service/SupportService.java | 10 +- .../metadata/service/SurveyService.java | 10 +- .../service/impl/CampaignServiceImpl.java | 44 +++--- .../service/impl/OwnerServiceImpl.java | 19 +-- .../service/impl/PartioningServiceImpl.java | 15 +- .../service/impl/SourceServiceImpl.java | 38 +++--- .../service/impl/SupportServiceImpl.java | 22 +-- .../service/impl/SurveyServiceImpl.java | 42 +++--- .../controller/MonitoringController.java | 12 +- .../query/controller/MoogController.java | 6 +- .../QuestioningAccreditationController.java | 128 ++++++++---------- .../controller/QuestioningController.java | 41 +----- .../controller/SearchContactController.java | 11 +- .../query/controller/WebclientController.java | 86 ++++++------ .../query/repository/MoogRepository.java | 14 +- .../CheckHabilitationServiceImplOidc.java | 12 +- .../query/service/impl/MoogServiceImpl.java | 44 +++--- .../service/impl/MySurveysServiceImpl.java | 46 +++---- .../impl/SearchContactServiceImpl.java | 8 +- .../QuestioningEventController.java | 78 +++++------ .../controller/SurveyUnitController.java | 32 ++--- .../controller/UploadController.java | 7 +- .../QuestioningAccreditationService.java | 12 +- .../service/QuestioningEventService.java | 11 +- .../service/QuestioningService.java | 10 +- .../service/SurveyUnitService.java | 8 +- .../questioning/service/UploadService.java | 3 +- .../QuestioningAccreditationServiceImpl.java | 6 +- .../impl/QuestioningEventServiceImpl.java | 11 +- .../service/impl/QuestioningServiceImpl.java | 14 +- .../service/impl/SurveyUnitServiceImpl.java | 24 ++-- .../service/impl/UploadServiceImpl.java | 56 ++++---- .../SourceAccreditationController.java | 33 +---- .../user/controller/UserController.java | 83 ++++-------- .../user/controller/UserEventController.java | 85 +++++------- .../service/SourceAccreditationService.java | 3 +- .../user/service/UserEventService.java | 3 +- .../user/service/UserService.java | 3 +- .../impl/SourceAccreditationServiceImpl.java | 6 +- .../service/impl/UserEventServiceImpl.java | 6 +- .../user/service/impl/UserServiceImpl.java | 8 +- .../controller/AddressControllerTest.java | 8 +- .../controller/ContactControllerTest.java | 15 +- .../controller/CampaignControllerTest.java | 10 +- .../controller/SourceControllerTest.java | 38 +++--- .../controller/SurveyControllerTest.java | 33 +++-- ...estionningAccreditationControllerTest.java | 4 +- .../controller/SurveyUnitControllerTest.java | 20 +-- .../controller/UserControllerTest.java | 9 +- 70 files changed, 767 insertions(+), 1048 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index d720d5be..20afcb52 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -28,7 +28,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -57,18 +56,15 @@ public class AddressController { + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") public ResponseEntity getContactAddress(@PathVariable("id") String id) { + Contact contact = contactService.findByIdentifier(id); try { - Optional contact = contactService.findByIdentifier(id); - if (contact.isPresent()) { - if (contact.get().getAddress() != null) - return ResponseEntity.status(HttpStatus.OK) - .body(addressService.convertToDto(contact.get().getAddress())); - else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Address does not exist"); - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); + if (contact.getAddress() != null) + return ResponseEntity.status(HttpStatus.OK) + .body(addressService.convertToDto(contact.getAddress())); + else { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Address does not exist"); } + } catch (Exception e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); } @@ -87,38 +83,33 @@ public ResponseEntity getContactAddress(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found") }) public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto) { - Optional optContact = contactService.findByIdentifier(id); - if (optContact.isPresent()) { - HttpStatus httpStatus; - Address addressUpdate; - Contact contact = optContact.get(); - Address address = addressService.convertToEntity(addressDto); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); - - if (contact.getAddress() != null) { - log.info("Update address for the contact {} ", id); - address.setId(contact.getAddress().getId()); - addressUpdate = addressService.saveAddress(address); - httpStatus = HttpStatus.OK; - } else { - log.info("Create address for the contact {} ", id); - addressUpdate = addressService.saveAddress(address); - contact.setAddress(addressUpdate); - contactService.saveContact(contact); - httpStatus = HttpStatus.CREATED; - } - - ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, - null); - contactEventService.saveContactEvent(contactEventUpdate); - return ResponseEntity.status(httpStatus).headers(responseHeaders) - .body(addressService.convertToDto(addressUpdate)); - + Contact contact = contactService.findByIdentifier(id); + HttpStatus httpStatus; + Address addressUpdate; + Address address = addressService.convertToEntity(addressDto); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); + + if (contact.getAddress() != null) { + log.info("Update address for the contact {} ", id); + address.setId(contact.getAddress().getId()); + addressUpdate = addressService.saveAddress(address); + httpStatus = HttpStatus.OK; } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); + log.info("Create address for the contact {} ", id); + addressUpdate = addressService.saveAddress(address); + contact.setAddress(addressUpdate); + contactService.saveContact(contact); + httpStatus = HttpStatus.CREATED; } + ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, + null); + contactEventService.saveContactEvent(contactEventUpdate); + return ResponseEntity.status(httpStatus).headers(responseHeaders) + .body(addressService.convertToDto(addressUpdate)); + + } class AddressPage extends PageImpl { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index 62973541..d505630c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -37,7 +37,6 @@ import java.text.ParseException; import java.util.List; import java.util.NoSuchElementException; -import java.util.Optional; import java.util.Set; @RestController @@ -78,23 +77,15 @@ public ResponseEntity getContacts( } @Operation(summary = "Search for a contact by its id") - @GetMapping(value = Constants.API_CONTACTS_ID, produces = "application/json") + @GetMapping(value = Constants.API_CONTACTS_ID) @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ContactFirstLoginDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) public ResponseEntity getContact(@PathVariable("id") String id) { - Optional contact = contactService.findByIdentifier(StringUtils.upperCase(id)); + Contact contact = contactService.findByIdentifier(StringUtils.upperCase(id)); try { - if (contact.isPresent()) - return ResponseEntity.ok().body(convertToFirstLoginDto(contact.get())); - else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); + return ResponseEntity.ok().body(convertToFirstLoginDto(contact)); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -125,7 +116,7 @@ public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody contact = convertToEntity(contactDto); } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse contact"); - } catch (NoSuchElementException e) { + } catch (NotFoundException e) { log.info("Creating contact with the identifier {}", contactDto.getIdentifier()); contact = convertToEntityNewContact(contactDto); if (contactDto.getAddress() != null) @@ -156,25 +147,22 @@ public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody @Transactional public ResponseEntity deleteContact(@PathVariable("id") String id) { try { - Optional contact = contactService.findByIdentifier(id); - if (contact.isPresent()) { - contactService.deleteContactAddressEvent(contact.get()); - - viewService.findViewByIdentifier(id).stream().forEach(viewService::deleteView); - questioningAccreditationService.findByContactIdentifier(id).stream().forEach(acc -> { - Questioning questioning = questioningService.findbyId(acc.getQuestioning().getId()).get(); - Set newSet = questioning.getQuestioningAccreditations(); - newSet.removeIf(a -> a.getId().equals(acc.getId())); - questioning.setQuestioningAccreditations(newSet); - questioningService.saveQuestioning(questioning); - questioningAccreditationService.deleteAccreditation(acc); - - }); - log.info("Delete contact {}", id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact deleted"); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); - } + Contact contact = contactService.findByIdentifier(id); + contactService.deleteContactAddressEvent(contact); + + viewService.findViewByIdentifier(id).stream().forEach(viewService::deleteView); + questioningAccreditationService.findByContactIdentifier(id).stream().forEach(acc -> { + Questioning questioning = questioningService.findbyId(acc.getQuestioning().getId()); + Set newSet = questioning.getQuestioningAccreditations(); + newSet.removeIf(a -> a.getId().equals(acc.getId())); + questioning.setQuestioningAccreditations(newSet); + questioningService.saveQuestioning(questioning); + questioningAccreditationService.deleteAccreditation(acc); + + }); + log.info("Delete contact {}", id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact deleted"); + } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -197,13 +185,10 @@ private ContactFirstLoginDto convertToFirstLoginDto(Contact contact) { private Contact convertToEntity(ContactDto contactDto) throws ParseException, NoSuchElementException { Contact contact = modelMapper.map(contactDto, Contact.class); contact.setGender(Contact.Gender.valueOf(contactDto.getCivility())); - Optional oldContact = contactService.findByIdentifier(contactDto.getIdentifier()); - if (oldContact.isEmpty()) { - throw new NoSuchElementException(); - } - contact.setComment(oldContact.get().getComment()); - contact.setAddress(oldContact.get().getAddress()); - contact.setContactEvents(oldContact.get().getContactEvents()); + Contact oldContact = contactService.findByIdentifier(contactDto.getIdentifier()); + contact.setComment(oldContact.getComment()); + contact.setAddress(oldContact.getAddress()); + contact.setContactEvents(oldContact.getContactEvents()); return contact; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index 3e6d688b..6bd5cf13 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -27,7 +27,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -54,16 +53,12 @@ public class ContactEventController { @ApiResponse(responseCode = "400", description = "Internal servor error") }) public ResponseEntity getContactContactEvents(@PathVariable("id") String identifier) { + Contact contact = contactService.findByIdentifier(identifier); try { + return ResponseEntity.status(HttpStatus.OK) + .body(contact.getContactEvents().stream().map(this::convertToDto) + .toList()); - Optional optContact = contactService.findByIdentifier(identifier); - if (optContact.isPresent()) { - return ResponseEntity.status(HttpStatus.OK) - .body(optContact.get().getContactEvents().stream().map(this::convertToDto) - .toList()); - - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -79,22 +74,19 @@ public ResponseEntity getContactContactEvents(@PathVariable("id") String iden }) public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto contactEventDto) { - Optional optContact = contactService.findByIdentifier(contactEventDto.getIdentifier()); - if (optContact.isPresent()) { - Contact contact = optContact.get(); - ContactEvent contactEvent = convertToEntity(contactEventDto); - ContactEvent newContactEvent = contactEventService.saveContactEvent(contactEvent); - Set setContactEvents = contact.getContactEvents(); - setContactEvents.add(newContactEvent); - contact.setContactEvents(setContactEvents); - contactService.saveContact(contact); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(newContactEvent)); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); + Contact contact = contactService.findByIdentifier(contactEventDto.getIdentifier()); + ContactEvent contactEvent = convertToEntity(contactEventDto); + ContactEvent newContactEvent = contactEventService.saveContactEvent(contactEvent); + Set setContactEvents = contact.getContactEvents(); + setContactEvents.add(newContactEvent); + contact.setContactEvents(setContactEvents); + contactService.saveContact(contact); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(newContactEvent)); + } @@ -106,18 +98,15 @@ public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto co @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity deleteContactEvent(@PathVariable("id") Long id) { + ContactEvent contactEvent = contactEventService.findById(id); + try { - Optional optContactEvent = contactEventService.findById(id); - if (optContactEvent.isPresent()) { - ContactEvent contactEvent = optContactEvent.get(); - Contact contact = contactEvent.getContact(); - contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent)) - .collect(Collectors.toSet())); - contactService.saveContact(contact); - contactEventService.deleteContactEvent(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted"); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact event does not exist"); + Contact contact = contactEvent.getContact(); + contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent)) + .collect(Collectors.toSet())); + contactService.saveContact(contact); + contactEventService.deleteContactEvent(id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/AddressService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/AddressService.java index 13f49cc2..9af53e06 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/AddressService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/AddressService.java @@ -1,18 +1,15 @@ package fr.insee.survey.datacollectionmanagement.contact.service; -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.contact.domain.Address; +import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import fr.insee.survey.datacollectionmanagement.contact.domain.Address; -import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; - @Service public interface AddressService { - public Optional
findById(Long id); + public Address findById(Long id); public Page
findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactEventService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactEventService.java index 26a6d8a7..4e39b430 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactEventService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactEventService.java @@ -1,24 +1,21 @@ package fr.insee.survey.datacollectionmanagement.contact.service; -import java.util.Optional; -import java.util.Set; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - import com.fasterxml.jackson.databind.JsonNode; - import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.Set; @Service public interface ContactEventService { public Page findAll(Pageable pageable); - public Optional findById(Long id); + public ContactEvent findById(Long id); public ContactEvent saveContactEvent(ContactEvent contactEvent); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index 1b5df172..7bc4f422 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -1,17 +1,13 @@ package fr.insee.survey.datacollectionmanagement.contact.service; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; - +import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import com.fasterxml.jackson.databind.JsonNode; - -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import java.util.List; @Service public interface ContactService { @@ -26,11 +22,11 @@ public interface ContactService { /** * Find a contact by its identifier. - * + * * @param identifier - * @return Optional contact found + * @return contact found */ - public Optional findByIdentifier(String identifier) ; + public Contact findByIdentifier(String identifier) ; /** * Update an existing contact and its address, or creates a new one diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java index dd623268..6cfb866b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/AddressServiceImpl.java @@ -4,14 +4,13 @@ import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; import fr.insee.survey.datacollectionmanagement.contact.repository.AddressRepository; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import lombok.RequiredArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Optional; - @Service @RequiredArgsConstructor public class AddressServiceImpl implements AddressService { @@ -21,8 +20,8 @@ public class AddressServiceImpl implements AddressService { private final ModelMapper modelMapper; @Override - public Optional
findById(Long id) { - return addressRepository.findById(id); + public Address findById(Long id) { + return addressRepository.findById(id).orElseThrow(() -> new NotFoundException(String.format("Address %s not found", id))); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java index 35775827..63d15226 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactEventServiceImpl.java @@ -6,13 +6,13 @@ import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; import fr.insee.survey.datacollectionmanagement.contact.repository.ContactEventRepository; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Date; -import java.util.Optional; import java.util.Set; @Service @@ -27,8 +27,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findById(Long id) { - return contactEventRepository.findById(id); + public ContactEvent findById(Long id) { + return contactEventRepository.findById(id).orElseThrow(()->new NotFoundException(String.format("ContactEvent %s not found", id))); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 027491bb..d52de717 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -33,8 +33,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findByIdentifier(String identifier) { - return contactRepository.findById(identifier); + public Contact findByIdentifier(String identifier) { + return contactRepository.findById(identifier).orElseThrow(() -> new NotFoundException(String.format("Contact %s not found", identifier))); } @Override @@ -70,7 +70,7 @@ public List searchListContactParameters(String identifier, String lastN boolean alwaysEmpty = true; if (!StringUtils.isEmpty(identifier)) { - listContactContact = Arrays.asList(findByIdentifier(identifier).get()); + listContactContact = Arrays.asList(findByIdentifier(identifier)); alwaysEmpty = false; } @@ -119,22 +119,20 @@ public Contact createContactAddressEvent(Contact contact, JsonNode payload) { @Override public Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException { - Optional existingContact = findByIdentifier(contact.getIdentifier()); - if (existingContact.isPresent()) { - if (contact.getAddress() != null) { - if (existingContact.get().getAddress() != null) { - contact.getAddress().setId(existingContact.get().getAddress().getId()); - } - addressService.saveAddress(contact.getAddress()); + Contact existingContact = findByIdentifier(contact.getIdentifier()); + if (contact.getAddress() != null) { + if (existingContact.getAddress() != null) { + contact.getAddress().setId(existingContact.getAddress().getId()); } + addressService.saveAddress(contact.getAddress()); + } - Set setContactEventsContact = existingContact.get().getContactEvents(); - ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, - payload); - setContactEventsContact.add(contactEventUpdate); - contact.setContactEvents(setContactEventsContact); - return saveContact(contact); - } else throw new NotFoundException("Contact not found"); + Set setContactEventsContact = existingContact.getContactEvents(); + ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, + payload); + setContactEventsContact.add(contactEventUpdate); + contact.setContactEvents(setContactEventsContact); + return saveContact(contact); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java index a9abb02f..c3860788 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotFoundException.java @@ -1,6 +1,6 @@ package fr.insee.survey.datacollectionmanagement.exception; -public class NotFoundException extends Exception { +public class NotFoundException extends RuntimeException { public NotFoundException(String errorMessage) { super(errorMessage); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 584b4a47..d46d02d9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -36,7 +36,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -86,14 +85,12 @@ public ResponseEntity getSources( @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getCampaignsBySurvey(@PathVariable("id") String id) { + + Survey survey = surveyService.findById(id); + try { - Optional survey = surveyService.findById(id); - if (!survey.isPresent()) { - log.warn("Survey {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey does not exist"); - } return ResponseEntity.ok() - .body(survey.get().getCampaigns().stream().map(s -> convertToDto(s)).toList()); + .body(survey.getCampaigns().stream().map(s -> convertToDto(s)).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -107,13 +104,10 @@ public ResponseEntity getCampaignsBySurvey(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getCampaign(@PathVariable("id") String id) { + Campaign campaign = campaignService.findById(StringUtils.upperCase(id)); + try { - Optional campaign = campaignService.findById(StringUtils.upperCase(id)); - if (!campaign.isPresent()) { - log.warn("campaign {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("campaign does not exist"); - } - return ResponseEntity.ok().body(convertToDto(campaign.get())); + return ResponseEntity.ok().body(convertToDto(campaign)); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -131,25 +125,21 @@ public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody if (StringUtils.isBlank(campaignDto.getId()) || !campaignDto.getId().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idCampaign don't match"); } - Campaign campaign; - if (!surveyService.findById(campaignDto.getSurveyId()).isPresent()) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Survey does not exist"); - } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(campaignDto.getId()).toUriString()); HttpStatus httpStatus; - if (campaignService.findById(id).isPresent()) { - log.info("Update campaign with the id {}", campaignDto.getId()); + try { campaignService.findById(id); + log.info("Update campaign with the id {}", campaignDto.getId()); httpStatus = HttpStatus.OK; - } else { + } catch (NotFoundException e) { log.info("Create campaign with the id {}", campaignDto.getId()); httpStatus = HttpStatus.CREATED; } - campaign = campaignService.insertOrUpdateCampaign(convertToEntity(campaignDto)); + Campaign campaign = campaignService.insertOrUpdateCampaign(convertToEntity(campaignDto)); Survey survey = campaign.getSurvey(); survey.getCampaigns().add(campaign); surveyService.insertOrUpdateSurvey(survey); @@ -166,29 +156,22 @@ public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Transactional public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr.insee.survey.datacollectionmanagement.exception.NotFoundException { - try { - if (campaignService.isCampaignOngoing(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign is still ongoing and can't be deleted"); - } - } catch (NotFoundException e) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Campaign does not exist"); + if (campaignService.isCampaignOngoing(id)) { + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign is still ongoing and can't be deleted"); } + Campaign campaign = campaignService.findById(id); try { - Optional campaign = campaignService.findById(id); - if (!campaign.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Campaign does not exist"); - } int nbQuestioningDeleted = 0; - Survey survey = campaign.get().getSurvey(); - survey.getCampaigns().remove(campaign.get()); + Survey survey = campaign.getSurvey(); + survey.getCampaigns().remove(campaign); surveyService.insertOrUpdateSurvey(survey); List uploadsCamp = uploadService.findAllByIdCampaign(id); campaignService.deleteCampaignById(id); - Set listPartitionings = campaign.get().getPartitionings(); + Set listPartitionings = campaign.getPartitionings(); - int nbViewDeleted = viewService.deleteViewsOfOneCampaign(campaign.get()); + int nbViewDeleted = viewService.deleteViewsOfOneCampaign(campaign); for (Partitioning partitioning : listPartitionings) { nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); @@ -199,7 +182,6 @@ public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr nbQuestioningDeleted, nbViewDeleted, uploadsCamp.size()); return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Campaign deleted"); } catch (Exception e) { - e.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } } @@ -211,12 +193,9 @@ public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr @ApiResponse(responseCode = "404", description = "Not found") }) public ResponseEntity isOnGoingCampaign(@PathVariable("id") String id) { - try { - boolean isOnGoing = campaignService.isCampaignOngoing(id); - return ResponseEntity.ok().body(new OnGoingDto(isOnGoing)); - } catch (NotFoundException e) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Campaign does not exist"); - } + boolean isOnGoing = campaignService.isCampaignOngoing(id); + return ResponseEntity.ok().body(new OnGoingDto(isOnGoing)); + } private CampaignDto convertToDto(Campaign campaign) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java index ad8494b1..f748cfb1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/MetadataController.java @@ -13,7 +13,6 @@ import org.springframework.web.bind.annotation.*; import java.util.Date; -import java.util.Optional; @RestController @Slf4j @@ -37,18 +36,14 @@ public JSONCollectionWrapper displayCampaignInProgress() { @PutMapping(value = Constants.MOOG_API_CAMPAIGNS_ID) public void updateCampaignInProgressMoog(@PathVariable("id") String id, @RequestBody CampaignMoogDto campaignMoogDto) { log.info("Updating Moog campaign with id " + id); - Optional campaign = campaignService.findById(id); - if(!campaign.isPresent()) - { - - } - campaign.get().getPartitionings().stream().forEach(p->{ + Campaign campaign = campaignService.findById(id); + campaign.getPartitionings().stream().forEach(p->{ p.setClosingDate(new Date(campaignMoogDto.getCollectionEndDate())); p.setOpeningDate(new Date(campaignMoogDto.getCollectionStartDate())); partitioningService.insertOrUpdatePartitioning(p); }); - campaign.get().setCampaignWording(campaignMoogDto.getLabel()); - campaignService.insertOrUpdateCampaign(campaign.get()); + campaign.setCampaignWording(campaignMoogDto.getLabel()); + campaignService.insertOrUpdateCampaign(campaign); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index 9f848953..ac8fb154 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.dto.OwnerDto; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; @@ -22,7 +23,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; @RestController @CrossOrigin @@ -61,13 +61,8 @@ public ResponseEntity getOwners( @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getOwner(@PathVariable("id") String id) { - Optional owner = ownerService.findById(id); - if (!owner.isPresent()) { - log.warn("Owner {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("owner does not exist"); - } - owner = ownerService.findById(id); - return ResponseEntity.ok().body(convertToDto(owner.orElse(null))); + Owner owner = ownerService.findById(id); + return ResponseEntity.ok().body(convertToDto(owner)); } @@ -88,15 +83,18 @@ public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody Ow ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(ownerDto.getId()).toUriString()); HttpStatus httpStatus; - log.warn("Update owner with the id {}", ownerDto.getId()); - Optional ownerBase = ownerService.findById(id); - httpStatus = HttpStatus.OK; + try { + Owner ownerBase = ownerService.findById(id); + log.warn("Update owner with the id {}", ownerDto.getId()); + httpStatus = HttpStatus.OK; - if (!ownerBase.isPresent()) { + } + catch (NotFoundException e){ log.info("Create owner with the id {}", ownerDto.getId()); httpStatus = HttpStatus.CREATED; } + Owner owner = ownerService.insertOrUpdateOwner(convertToEntity(ownerDto)); return ResponseEntity.status(httpStatus).headers(responseHeaders).body(convertToDto(owner)); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index ff5ff1e8..7d1038fd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.PartitioningDto; @@ -29,7 +30,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -56,14 +56,10 @@ public class PartitioningController { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getPartitioningsByCampaign(@PathVariable("id") String id) { + Campaign campaign = campaignService.findById(id); try { - Optional campaign = campaignService.findById(id); - if (campaign.isEmpty()) { - log.warn("Campaign {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("campaign does not exist"); - } return ResponseEntity.ok() - .body(campaign.get().getPartitionings().stream().map(this::convertToDto) + .body(campaign.getPartitionings().stream().map(this::convertToDto) .toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); @@ -79,13 +75,9 @@ public ResponseEntity getPartitioningsByCampaign(@PathVariable("id") String i @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getPartitioning(@PathVariable("id") String id) { + Partitioning partitioning = partitioningService.findById(StringUtils.upperCase(id)); try { - Optional partitioning = partitioningService.findById(StringUtils.upperCase(id)); - if (!partitioning.isPresent()) { - log.warn("Partitioning {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("partitioning does not exist"); - } - return ResponseEntity.ok().body(convertToDto(partitioning.get())); + return ResponseEntity.ok().body(convertToDto(partitioning)); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); @@ -101,28 +93,27 @@ public ResponseEntity getPartitioning(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity putPartitioning(@PathVariable("id") String id, - @RequestBody PartitioningDto partitioningDto) { + @RequestBody PartitioningDto partitioningDto) { if (StringUtils.isBlank(partitioningDto.getId()) || !partitioningDto.getId().equalsIgnoreCase(id)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idPartitioning don't match"); } Partitioning partitioning; - if (!campaignService.findById(partitioningDto.getCampaignId()).isPresent()) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign does not exist"); - } + HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(partitioningDto.getId()).toUriString()); HttpStatus httpStatus; - if (partitioningService.findById(id).isPresent()) { - log.info("Update partitioning with the id {}", partitioningDto.getId()); + try { partitioningService.findById(id); + log.info("Update partitioning with the id {}", partitioningDto.getId()); httpStatus = HttpStatus.OK; - } else { + } catch (NotFoundException e) { log.info("Create partitioning with the id {}", partitioningDto.getId()); httpStatus = HttpStatus.CREATED; } + partitioning = partitioningService.insertOrUpdatePartitioning(convertToEntity(partitioningDto)); Campaign campaign = partitioning.getCampaign(); campaign.getPartitionings().add(partitioning); @@ -139,18 +130,16 @@ public ResponseEntity putPartitioning(@PathVariable("id") String id, }) @Transactional public ResponseEntity deletePartitioning(@PathVariable("id") String id) { + Partitioning partitioning = partitioningService.findById(id); + try { - Optional partitioning = partitioningService.findById(id); - if (!partitioning.isPresent()) { - log.warn("Partitioning {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Partitioning does not exist"); - } - Campaign campaign = partitioning.get().getCampaign(); - campaign.getPartitionings().remove(partitioning.get()); + + Campaign campaign = partitioning.getCampaign(); + campaign.getPartitionings().remove(partitioning); campaignService.insertOrUpdateCampaign(campaign); partitioningService.deletePartitioningById(id); - int nbQuestioningDeleted = questioningService.deleteQuestioningsOfOnePartitioning(partitioning.get()); + int nbQuestioningDeleted = questioningService.deleteQuestioningsOfOnePartitioning(partitioning); log.info("Partitioning {} deleted - {} questionings deleted", id, nbQuestioningDeleted); return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Partitioning deleted"); } catch (Exception e) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index b4ca8fc9..8e2c1a40 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -34,7 +35,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -80,13 +80,9 @@ public ResponseEntity getSources( @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getSource(@PathVariable("id") String id) { - Optional source = sourceService.findById(StringUtils.upperCase(id)); - if (!source.isPresent()) { - log.warn("Source {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("source does not exist"); - } + Source source = sourceService.findById(StringUtils.upperCase(id)); source = sourceService.findById(StringUtils.upperCase(id)); - return ResponseEntity.ok().body(convertToDto(source.orElse(null))); + return ResponseEntity.ok().body(convertToDto(source)); } @@ -107,21 +103,22 @@ public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody S responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(SourceCompleteDto.getId()).toUriString()); HttpStatus httpStatus; - - if (sourceService.findById(id).isPresent()) { + try { + sourceService.findById(id); log.warn("Update source with the id {}", SourceCompleteDto.getId()); httpStatus = HttpStatus.OK; - } else { + } catch (NotFoundException e) { log.info("Create source with the id {}", SourceCompleteDto.getId()); httpStatus = HttpStatus.CREATED; } + source = sourceService.insertOrUpdateSource(convertToEntity(SourceCompleteDto)); if (source.getOwner() != null && httpStatus.equals(HttpStatus.CREATED)) ownerService.addSourceFromOwner(source.getOwner(), source); - if (source.getSupport()!=null&& httpStatus.equals(HttpStatus.CREATED)) + if (source.getSupport() != null && httpStatus.equals(HttpStatus.CREATED)) supportService.addSourceFromSupport(source.getSupport(), source); - + return ResponseEntity.status(httpStatus).headers(responseHeaders).body(convertToDto(source)); } @@ -135,24 +132,21 @@ public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody S @Transactional public ResponseEntity deleteSource(@PathVariable("id") String id) { int nbQuestioningDeleted = 0, nbViewDeleted = 0; + Source source = sourceService.findById(id); + try { - Optional source = sourceService.findById(id); - if (!source.isPresent()) { - log.warn("Source {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("source does not exist"); - } - if (source.get().getOwner() != null) - ownerService.removeSourceFromOwner(source.get().getOwner(), source.get()); + if (source.getOwner() != null) + ownerService.removeSourceFromOwner(source.getOwner(), source); - if (source.get().getSupport()!=null) - supportService.removeSourceFromSupport(source.get().getSupport(), source.get()); + if (source.getSupport() != null) + supportService.removeSourceFromSupport(source.getSupport(), source); sourceService.deleteSourceById(id); List listCampaigns = new ArrayList<>(); List listPartitionings = new ArrayList<>(); - source.get().getSurveys().stream().forEach(su -> listCampaigns.addAll(su.getCampaigns())); - source.get().getSurveys().stream().forEach( + source.getSurveys().stream().forEach(su -> listCampaigns.addAll(su.getCampaigns())); + source.getSurveys().stream().forEach( su -> su.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings()))); for (Campaign campaign : listCampaigns) { @@ -178,14 +172,11 @@ public ResponseEntity deleteSource(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getSourcesByOwner(@PathVariable("id") String id) { + Owner owner = ownerService.findById(id); try { - Optional owner = ownerService.findById(id); - if (!owner.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("owner does not exist"); - } return ResponseEntity.ok() - .body(owner.get().getSources().stream().map(this::convertToDto).toList()); + .body(owner.getSources().stream().map(this::convertToDto).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index aaaf3e9a..70286ff4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.dto.SupportDto; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; @@ -13,7 +14,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -23,7 +23,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; @RestController @CrossOrigin @@ -62,13 +61,8 @@ public ResponseEntity getSupports( @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getSupport(@PathVariable("id") String id) { - Optional support = supportService.findById(id); - if (!support.isPresent()) { - log.warn("Support {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("support does not exist"); - } - support = supportService.findById(id); - return ResponseEntity.ok().body(convertToDto(support.orElse(null))); + Support support = supportService.findById(id); + return ResponseEntity.ok().body(convertToDto(support)); } @@ -88,16 +82,18 @@ public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(supportDto.getId()).toUriString()); HttpStatus httpStatus; + Support supportBase; + try { + supportBase = supportService.findById(id); + log.info("Update support with the id {}", supportDto.getId()); + httpStatus = HttpStatus.OK; - log.warn("Update support with the id {}", supportDto.getId()); - Optional supportBase = supportService.findById(id); - httpStatus = HttpStatus.OK; - - if (!supportBase.isPresent()) { + } catch (NotFoundException e) { log.info("Create support with the id {}", supportDto.getId()); httpStatus = HttpStatus.CREATED; } + Support support = supportService.insertOrUpdateSupport(convertToEntity(supportDto)); return ResponseEntity.status(httpStatus).headers(responseHeaders).body(convertToDto(support)); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index db50a36d..38a7c519 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; @@ -33,7 +34,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -62,14 +62,10 @@ public class SurveyController { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { - + Source source = sourceService.findById(id); try { - Optional source = sourceService.findById(id); - if (!source.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("source does not exist"); - } return ResponseEntity.ok() - .body(source.get().getSurveys().stream().map(this::convertToDto).toList()); + .body(source.getSurveys().stream().map(this::convertToDto).toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -84,13 +80,9 @@ public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getSurvey(@PathVariable("id") String id) { + Survey survey = surveyService.findById(StringUtils.upperCase(id)); try { - Optional survey = surveyService.findById(StringUtils.upperCase(id)); - if (!survey.isPresent()) { - log.warn("Survey {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey does not exist"); - } - return ResponseEntity.ok().body(convertToDto(survey.get())); + return ResponseEntity.ok().body(convertToDto(survey)); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); @@ -115,11 +107,11 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody S ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(surveyDto.getId()).toUriString()); HttpStatus httpStatus; - if (surveyService.findById(id).isPresent()) { + try { + surveyService.findById(id); log.info("Update survey with the id {}", surveyDto.getId()); httpStatus = HttpStatus.OK; - - } else { + } catch (NotFoundException e) { log.info("Creating survey with the id {}", surveyDto.getId()); httpStatus = HttpStatus.CREATED; } @@ -140,26 +132,22 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody S }) @Transactional public ResponseEntity deleteSurvey(@PathVariable("id") String id) { + Survey survey = surveyService.findById(id); try { - Optional survey = surveyService.findById(id); - if (!survey.isPresent()) { - log.warn("Survey {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Survey does not exist"); - } int nbQuestioningDeleted = 0; int nbViewDeleted = 0; - Source source = survey.get().getSource(); - source.getSurveys().remove(survey.get()); + Source source = survey.getSource(); + source.getSurveys().remove(survey); sourceService.insertOrUpdateSource(source); surveyService.deleteSurveyById(id); List listPartitionings = new ArrayList<>(); - survey.get().getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings())); + survey.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings())); - for (Campaign campaign : survey.get().getCampaigns()) { + for (Campaign campaign : survey.getCampaigns()) { viewService.findViewByCampaignId(campaign.getId()).stream() .forEach(v -> viewService.deleteView(v)); } @@ -168,7 +156,7 @@ public ResponseEntity deleteSurvey(@PathVariable("id") String id) { .forEach(q -> questioningService.deleteQuestioning(q.getId())); } - for (Campaign campaign : survey.get().getCampaigns()) { + for (Campaign campaign : survey.getCampaigns()) { nbViewDeleted += viewService.deleteViewsOfOneCampaign(campaign); } for (Partitioning partitioning : listPartitionings) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java index e1dfb192..46ea6fd4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/CampaignService.java @@ -1,6 +1,5 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignMoogDto; @@ -10,14 +9,13 @@ import java.util.Collection; import java.util.List; -import java.util.Optional; @Service public interface CampaignService { Collection getCampaigns(); - Optional findById(String idCampaign); + Campaign findById(String idCampaign); List findbyPeriod(String period); @@ -37,7 +35,6 @@ public interface CampaignService { * Check if a campaign is ongoing, which means checks if all the partitiongs of the campaign are ongoing * @param idCampaign id of the campaign * @return true - * @throws NotFoundException if the campaign does not exist */ - boolean isCampaignOngoing(String idCampaign) throws NotFoundException; + boolean isCampaignOngoing(String idCampaign) ; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/OwnerService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/OwnerService.java index 586d2daf..2485f242 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/OwnerService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/OwnerService.java @@ -1,16 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.Optional; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; public interface OwnerService { - Optional findById(String owner); + Owner findById(String owner); Page findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/PartitioningService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/PartitioningService.java index ea26e73f..88d46070 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/PartitioningService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/PartitioningService.java @@ -1,13 +1,12 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.Date; -import java.util.Optional; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import java.util.Date; + public interface PartitioningService { - Optional findById(String id); + Partitioning findById(String id); Partitioning insertOrUpdatePartitioning(Partitioning partitioning); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SourceService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SourceService.java index d3494073..b676baf3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SourceService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SourceService.java @@ -1,16 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.Optional; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; public interface SourceService { - Optional findById(String source); + Source findById(String source); Page findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SupportService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SupportService.java index 0a773848..b10b3e59 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SupportService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SupportService.java @@ -1,17 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.Optional; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; -import lombok.NonNull; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; public interface SupportService { - Optional findById(String support); + Support findById(String support); Page findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java index 69db9ff3..acdbb305 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java @@ -1,19 +1,17 @@ package fr.insee.survey.datacollectionmanagement.metadata.service; -import java.util.List; -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; +import java.util.List; public interface SurveyService { List findByYear(int year); - Optional findById(String id); + Survey findById(String id); Page findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java index 815c249e..4f160827 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/CampaignServiceImpl.java @@ -56,8 +56,8 @@ public List findbyPeriod(String period) { } @Override - public Optional findById(String idCampaign) { - return campaignRepository.findById(idCampaign); + public Campaign findById(String idCampaign) { + return campaignRepository.findById(idCampaign).orElseThrow(() -> new NotFoundException(String.format("Campaign %s not found", idCampaign))); } @Override @@ -77,14 +77,16 @@ public Page findAll(Pageable pageable) { @Override public Campaign insertOrUpdateCampaign(Campaign campaign) { - Optional campaignBase = findById(campaign.getId()); - if (!campaignBase.isPresent()) { + try { + Campaign campaignBase = findById(campaign.getId()); + log.info("Update campaign with the id {}", campaign.getId()); + campaign.setPartitionings(campaignBase.getPartitionings()); + + } catch (NotFoundException e) { log.info("Create campaign with the id {}", campaign.getId()); - return campaignRepository.save(campaign); } - log.info("Update campaign with the id {}", campaign.getId()); - campaign.setPartitionings(campaignBase.get().getPartitionings()); return campaignRepository.save(campaign); + } @Override @@ -94,15 +96,16 @@ public void deleteCampaignById(String id) { @Override public Campaign addPartitionigToCampaign(Campaign campaign, Partitioning partitioning) { - Optional campaignBase = findById(campaign.getId()); - if (campaignBase.isPresent() && isPartitioningPresent(partitioning, campaignBase.get())) { - campaign.setPartitionings(campaignBase.get().getPartitionings()); - } else { - Set partitionings = (!campaignBase.isPresent()) ? new HashSet<>() - : campaignBase.get().getPartitionings(); - partitionings.add(partitioning); - campaign.setPartitionings(partitionings); + Set partitionings; + try { + Campaign campaignBase = findById(campaign.getId()); + partitionings = campaignBase.getPartitionings(); + if (!isPartitioningPresent(partitioning, campaignBase)) + partitionings.add(partitioning); + } catch (NotFoundException e) { + partitionings = Set.of(partitioning); } + campaign.setPartitionings(partitionings); return campaign; } @@ -116,16 +119,13 @@ private boolean isPartitioningPresent(Partitioning p, Campaign c) { } @Override - public boolean isCampaignOngoing(String idCampaign) throws NotFoundException { - Optional camp = findById(idCampaign); + public boolean isCampaignOngoing(String idCampaign) { + Campaign camp = findById(idCampaign); - if (camp.isEmpty()) { - throw new NotFoundException("Campaign does not exist"); - } Date now = new Date(); int nbOnGoingParts = 0; - for (Partitioning part : camp.get().getPartitionings()) { + for (Partitioning part : camp.getPartitionings()) { if (partitioningService.isOnGoing(part, now)) { nbOnGoingParts++; log.info("Partitiong {} of campaign {} is ongoing", part.getId(), idCampaign); @@ -133,7 +133,7 @@ public boolean isCampaignOngoing(String idCampaign) throws NotFoundException { log.info("Partitiong {} of campaign {} is closed", part.getId(), idCampaign); } } - return !camp.get().getPartitionings().isEmpty() && nbOnGoingParts == camp.get().getPartitionings().size(); + return !camp.getPartitionings().isEmpty() && nbOnGoingParts == camp.getPartitionings().size(); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java index 659bf6ce..80bd7a8c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/OwnerServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.repository.OwnerRepository; @@ -10,8 +11,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Optional; - @Service @Slf4j @RequiredArgsConstructor @@ -19,8 +18,8 @@ public class OwnerServiceImpl implements OwnerService { private final OwnerRepository ownerRepository; - public Optional findById(String owner) { - return ownerRepository.findById(owner); + public Owner findById(String owner) { + return ownerRepository.findById(owner).orElseThrow(() -> new NotFoundException(String.format("Owner %s not found", owner))); } @Override @@ -30,13 +29,17 @@ public Page findAll(Pageable pageable) { @Override public Owner insertOrUpdateOwner(Owner owner) { - Optional ownerBase = findById(owner.getId()); - if (!ownerBase.isPresent()) { + + try { + Owner ownerBase = findById(owner.getId()); + log.info("Update owner with the id {}", owner.getId()); + owner.setSources(ownerBase.getSources()); + } catch (NotFoundException e) { log.info("Create owner with the id {}", owner.getId()); return ownerRepository.save(owner); } - log.info("Update owner with the id {}", owner.getId()); - owner.setSources(ownerBase.get().getSources()); + + return ownerRepository.save(owner); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java index e964adf6..e1972d07 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/PartioningServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.repository.PartitioningRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; @@ -8,7 +9,6 @@ import org.springframework.stereotype.Service; import java.util.Date; -import java.util.Optional; @Service @Slf4j @@ -18,19 +18,14 @@ public class PartioningServiceImpl implements PartitioningService { private final PartitioningRepository partitioningRepository; @Override - public Optional findById(String id) { - return partitioningRepository.findById(id); + public Partitioning findById(String id) { + return partitioningRepository.findById(id). + orElseThrow(() -> new NotFoundException(String.format("Partitioning %s not found", id))); } @Override public Partitioning insertOrUpdatePartitioning(Partitioning partitioning) { - Optional campaignBase = findById(partitioning.getId()); - if (!campaignBase.isPresent()) { - log.info("Create partitioning with the id {}", partitioning.getId()); - return partitioningRepository.save(partitioning); - } - log.info("Update partitioning with the id {}", partitioning.getId()); return partitioningRepository.save(partitioning); } @@ -43,6 +38,6 @@ public void deletePartitioningById(String id) { @Override public boolean isOnGoing(Partitioning part, Date date) { - return part.getClosingDate().compareTo(date)>0 && part.getOpeningDate().compareTo(date)<0; + return part.getClosingDate().compareTo(date) > 0 && part.getOpeningDate().compareTo(date) < 0; } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java index 244b34a3..1f8f483b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SourceServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; @@ -10,8 +11,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.HashSet; -import java.util.Optional; import java.util.Set; @Service @@ -21,8 +20,8 @@ public class SourceServiceImpl implements SourceService { private final SourceRepository sourceRepository; - public Optional findById(String source) { - return sourceRepository.findById(source); + public Source findById(String source) { + return sourceRepository.findById(source).orElseThrow(() -> new NotFoundException(String.format("Source %s not found", source))); } @Override @@ -32,13 +31,15 @@ public Page findAll(Pageable pageable) { @Override public Source insertOrUpdateSource(Source source) { - Optional sourceBase = findById(source.getId()); - if (!sourceBase.isPresent()) { + try { + Source sourceBase = findById(source.getId()); + log.info("Update source with the id {}", source.getId()); + source.setSurveys(sourceBase.getSurveys()); + } catch (NotFoundException e) { log.info("Create source with the id {}", source.getId()); return sourceRepository.save(source); + } - log.info("Update source with the id {}", source.getId()); - source.setSurveys(sourceBase.get().getSurveys()); return sourceRepository.save(source); } @@ -50,20 +51,21 @@ public void deleteSourceById(String id) { @Override public Source addSurveyToSource(Source source, Survey survey) { - Optional sourceBase = findById(source.getId()); - if (sourceBase.isPresent() && isSurveyPresent(survey, sourceBase.get())) { - source.setSurveys(sourceBase.get().getSurveys()); - - } else { + Set surveys; + try { + Source sourceBase = findById(source.getId()); + surveys = sourceBase.getSurveys(); + if (!isSurveyPresent(survey, sourceBase)) { + surveys.add(survey); + } + } catch (NotFoundException e) { + surveys = Set.of(survey); - Set surveys = (!sourceBase.isPresent()) ? new HashSet<>() - : sourceBase.get().getSurveys(); - surveys.add(survey); - source.setSurveys(surveys); } + source.setSurveys(surveys); return source; } - + private boolean isSurveyPresent(Survey su, Source s) { for (Survey survey : s.getSurveys()) { if (survey.getId().equals(su.getId())) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java index b9cbe718..cfc3513b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SupportServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.repository.SupportRepository; @@ -10,17 +11,16 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Optional; - @Service @Slf4j @RequiredArgsConstructor public class SupportServiceImpl implements SupportService { - private final SupportRepository supportRepository; + private final SupportRepository supportRepository; + + public Support findById(String support) { - public Optional findById(String support) { - return supportRepository.findById(support); + return supportRepository.findById(support).orElseThrow(() -> new NotFoundException(String.format("Support %s not found", support))); } @Override @@ -30,14 +30,16 @@ public Page findAll(Pageable pageable) { @Override public Support insertOrUpdateSupport(Support support) { - Optional supportBase = findById(support.getId()); - if (!supportBase.isPresent()) { + try { + Support supportBase = findById(support.getId()); + log.info("Update support with the id {}", support.getId()); + support.setSources(supportBase.getSources()); + + } catch (NotFoundException e) { log.info("Create support with the id {}", support.getId()); - return supportRepository.save(support); } - log.info("Update support with the id {}", support.getId()); - support.setSources(supportBase.get().getSources()); return supportRepository.save(support); + } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java index f088daad..049e66e4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; @@ -10,9 +11,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.HashSet; import java.util.List; -import java.util.Optional; import java.util.Set; @Service @@ -28,8 +27,9 @@ public List findByYear(int year) { } @Override - public Optional findById(String id) { - return surveyRepository.findById(id); + public Survey findById(String id) { + return surveyRepository.findById(id) + .orElseThrow(() -> new NotFoundException(String.format("Survey %s not found", id))); } @Override @@ -39,14 +39,15 @@ public Page findAll(Pageable pageable) { @Override public Survey insertOrUpdateSurvey(Survey survey) { - Optional surveyBase = findById(survey.getId()); - if (!surveyBase.isPresent()) { + try { + Survey surveyBase = findById(survey.getId()); + log.info("Update survey with the id {}", survey.getId()); + survey.setCampaigns(surveyBase.getCampaigns()); + } catch (NotFoundException e) { log.info("Create survey with the id {}", survey.getId()); - return surveyRepository.save(survey); } - log.info("Update survey with the id {}", survey.getId()); - survey.setCampaigns(surveyBase.get().getCampaigns()); return surveyRepository.save(survey); + } @Override @@ -57,20 +58,23 @@ public void deleteSurveyById(String id) { @Override public Survey addCampaignToSurvey(Survey survey, Campaign campaign) { - Optional surveyBase = findById(survey.getId()); - if (surveyBase.isPresent() && isCampaignPresent(campaign, surveyBase.get())) { - survey.setCampaigns(surveyBase.get().getCampaigns()); - - } else { + Set campaigns; + try { + Survey surveyBase = findById(survey.getId()); + campaigns = surveyBase.getCampaigns(); + if(!isCampaignPresent(campaign, surveyBase)) { + campaigns.add(campaign); + } + } + catch (NotFoundException e){ + campaigns = Set.of(campaign); - Set campaigns = (!surveyBase.isPresent()) ? new HashSet<>() - : surveyBase.get().getCampaigns(); - campaigns.add(campaign); - survey.setCampaigns(campaigns); } + survey.setCampaigns(campaigns); return survey; + } - + private boolean isCampaignPresent(Campaign c, Survey s) { for (Campaign camp : s.getCampaigns()) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java index ef6897e9..a75cf1cc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MonitoringController.java @@ -15,9 +15,6 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; -import java.util.NoSuchElementException; -import java.util.Optional; - @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " @@ -46,13 +43,10 @@ public JSONCollectionWrapper getDataToFollowUp(@PathVariable St @GetMapping(value = "/api/temp/moog/campaigns/{idCampaign}/monitoring/progress", produces = "application/json") public JSONCollectionWrapper getDataForProgressTemp(@PathVariable String idCampaign) { log.info("Request GET for monitoring moog progress table for campaign : {}", idCampaign); - Optional campaign = campaignService.findById(idCampaign); - if (campaign.isEmpty()) { - throw new NoSuchElementException("campaign does not exist"); - } - log.info("{} partitionings found", campaign.get().getPartitionings().stream().map(Partitioning::getId) + Campaign campaign = campaignService.findById(idCampaign); + log.info("{} partitionings found", campaign.getPartitionings().stream().map(Partitioning::getId) .toList().size()); - campaign.get().getPartitionings().forEach(part -> log.info("{} partitionig found", part.getId())); + campaign.getPartitionings().forEach(part -> log.info("{} partitionig found", part.getId())); return null; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java index bcc9f8b7..eaaa405b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java @@ -33,7 +33,6 @@ import java.util.List; import java.util.Map; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -80,9 +79,8 @@ public ResponseEntity moogSearch(@RequestParam(required = false) String filte @ApiResponse(responseCode = "404", description = "Not found") }) public ResponseEntity getMoogMail(@PathVariable("id") String contactId) { - Optional contact = contactService.findByIdentifier(contactId); - return contact.isPresent() ? ResponseEntity.ok().body(contact.get().getEmail()) - : ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact not found"); + Contact contact = contactService.findByIdentifier(contactId); + return ResponseEntity.ok().body(contact.getEmail()); } @GetMapping(path = Constants.API_MOOG_EVENTS, produces = "application/json") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java index 2dc4e8a0..d8b1a2bf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningAccreditationController.java @@ -29,7 +29,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; import java.util.Set; @RestController @@ -62,15 +61,13 @@ public class QuestioningAccreditationController { }) public ResponseEntity getQuestioningAccreditation(@PathVariable("id") Long id) { + Questioning optQuestioning = questioningService.findbyId(id); + try { - Optional optQuestioning = questioningService.findbyId(id); - if (optQuestioning.isPresent()) - return new ResponseEntity<>( - optQuestioning.get().getQuestioningAccreditations().stream().map(this::convertToDto) - .toList(), - HttpStatus.OK); - else - return new ResponseEntity<>("Questioning does not exist", HttpStatus.NOT_FOUND); + return new ResponseEntity<>( + optQuestioning.getQuestioningAccreditations().stream().map(this::convertToDto) + .toList(), HttpStatus.OK); + } catch (Exception e) { return new ResponseEntity("Error", HttpStatus.INTERNAL_SERVER_ERROR); } @@ -88,78 +85,65 @@ public ResponseEntity getQuestioningAccreditation(@PathVariable("id") Long id public ResponseEntity postQuestioningAccreditation(@PathVariable("id") Long id, @RequestBody QuestioningAccreditationDto questioningAccreditationDto) { - Optional optQuestioning = null; + Questioning questioning = questioningService.findbyId(id); String idContact = questioningAccreditationDto.getIdContact(); + contactService.findByIdentifier(idContact); - // Check if questioning exists - try { - optQuestioning = questioningService.findbyId(id); - if (optQuestioning.isEmpty()) - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Questioning does not exist"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - Questioning questioning = optQuestioning.get(); - // Check if contact exists - if (contactService.findByIdentifier(idContact).isEmpty()) - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Contact does not exist"); HttpHeaders responseHeaders = new HttpHeaders(); // save new accreditation or update existing one Set setExistingAccreditations = questioning.getQuestioningAccreditations(); - Optional part = partitioningService.findById(questioning.getIdPartitioning()); - if (part.isPresent()) { - - String idSu = questioning.getSurveyUnit().getIdSu(); - - List listContactAccreditations = setExistingAccreditations.stream() - .filter(acc -> acc.getIdContact().equals(idContact) - && acc.getQuestioning().getIdPartitioning().equals(part.get().getId()) - && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) - .toList(); - - if (listContactAccreditations.isEmpty()) { - // Create new accreditation - QuestioningAccreditation questioningAccreditation = convertToEntity(questioningAccreditationDto); - questioningAccreditation.setQuestioning(questioning); - setExistingAccreditations.add(questioningAccreditation); - questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); - questioningService.saveQuestioning(questioning); - - // create view - viewService.createView(idContact, questioning.getSurveyUnit().getIdSu(), - part.get().getCampaign().getId()); - - // location header - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) - .toUriString()); - - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(questioningAccreditation)); - - - } else { - // update accreditation - QuestioningAccreditation questioningAccreditation = listContactAccreditations.get(0); - questioningAccreditationDto.setId(questioningAccreditation.getId()); - questioningAccreditation = convertToEntity(questioningAccreditationDto); - questioningAccreditation.setQuestioning(questioning); - questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); - - // view already exists - - // location header - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) - .toUriString()); - return ResponseEntity.status(HttpStatus.OK).headers(responseHeaders) - .body(convertToDto(questioningAccreditation)); - } - } else return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Partitioning not found"); + Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); + + String idSu = questioning.getSurveyUnit().getIdSu(); + + List listContactAccreditations = setExistingAccreditations.stream() + .filter(acc -> acc.getIdContact().equals(idContact) + && acc.getQuestioning().getIdPartitioning().equals(part.getId()) + && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) + .toList(); + + if (listContactAccreditations.isEmpty()) { + // Create new accreditation + QuestioningAccreditation questioningAccreditation = convertToEntity(questioningAccreditationDto); + questioningAccreditation.setQuestioning(questioning); + setExistingAccreditations.add(questioningAccreditation); + questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); + questioningService.saveQuestioning(questioning); + + // create view + viewService.createView(idContact, questioning.getSurveyUnit().getIdSu(), + part.getCampaign().getId()); + + // location header + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) + .toUriString()); + + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(questioningAccreditation)); + + + } else { + // update accreditation + QuestioningAccreditation questioningAccreditation = listContactAccreditations.get(0); + questioningAccreditationDto.setId(questioningAccreditation.getId()); + questioningAccreditation = convertToEntity(questioningAccreditationDto); + questioningAccreditation.setQuestioning(questioning); + questioningAccreditationService.saveQuestioningAccreditation(questioningAccreditation); + + // view already exists + + // location header + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().path(questioningAccreditation.getId().toString()) + .toUriString()); + return ResponseEntity.status(HttpStatus.OK).headers(responseHeaders) + .body(convertToDto(questioningAccreditation)); + } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java index b5c87896..781b38b4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/QuestioningController.java @@ -25,8 +25,6 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.util.Optional; - @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " @@ -53,15 +51,9 @@ public class QuestioningController { }) public ResponseEntity getQuestioning(@PathVariable("id") Long id) { - Optional optQuestioning = null; + Questioning questioning = questioningService.findbyId(id); try { - optQuestioning = questioningService.findbyId(id); - if (optQuestioning.isPresent()) - return new ResponseEntity<>(convertToDto(optQuestioning.get()), HttpStatus.OK); - else { - log.warn("Questioning {} does not exist", id); - return new ResponseEntity<>("Not Found", HttpStatus.NOT_FOUND); - } + return new ResponseEntity<>(convertToDto(questioning), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity("Error", HttpStatus.BAD_REQUEST); } @@ -74,19 +66,11 @@ public ResponseEntity getQuestioning(@PathVariable("id") Long id) { @ApiResponse(responseCode = "404", description = "NotFound") }) public ResponseEntity postQuestioning(@RequestBody QuestioningDto questioningDto) { - Optional optSu = surveyUnitService.findbyId(questioningDto.getSurveyUnitId()); - - if (!optSu.isPresent()) { - log.warn("survey unit {} does not exist", questioningDto.getSurveyUnitId()); - return new ResponseEntity<>("survey unit does not exist", HttpStatus.NOT_FOUND); - } + SurveyUnit su = surveyUnitService.findbyId(questioningDto.getSurveyUnitId()); + ; + partitioningService.findById(questioningDto.getIdPartitioning()); - SurveyUnit su = optSu.get(); - if (!partitioningService.findById(questioningDto.getIdPartitioning()).isPresent()) { - log.warn("partitioning {} does not exist", questioningDto.getIdPartitioning()); - return new ResponseEntity<>("partitioning does not exist", HttpStatus.NOT_FOUND); - } Questioning questioning = convertToEntity(questioningDto); questioning.setSurveyUnit(su); questioning = questioningService.saveQuestioning(questioning); @@ -106,19 +90,8 @@ public ResponseEntity postQuestioning(@RequestBody QuestioningDto questioning @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity getQuestioningsBySurveyUnit(@PathVariable("id") String id) { - try { - Optional optSu = surveyUnitService.findbyId(StringUtils.upperCase(id)); - if (optSu.isPresent()) - return new ResponseEntity<>( - optSu.get().getQuestionings().stream().map(this::convertToDto).toList(), - HttpStatus.OK); - else { - log.warn("survey unit {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey unit does not exist"); - } - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + SurveyUnit su = surveyUnitService.findbyId(StringUtils.upperCase(id)); + return new ResponseEntity<>(su.getQuestionings().stream().map(this::convertToDto).toList(), HttpStatus.OK); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 30a015e2..dfb7c019 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -34,7 +34,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -113,12 +112,12 @@ public ResponseEntity getContactAccreditations(@PathVariable("id") String id) List accreditations = questioningAccreditationService.findByContactIdentifier(id); for (QuestioningAccreditation questioningAccreditation : accreditations) { Questioning questioning = questioningAccreditation.getQuestioning(); - Optional part = partitioningService.findById(questioning.getIdPartitioning()); + Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); - listAccreditations.add(new AccreditationDetailDto(part.get().getCampaign().getSurvey().getSource().getId(), - part.get().getCampaign().getSurvey().getSource().getShortWording(), - part.get().getCampaign().getSurvey().getYear(), part.get().getCampaign().getPeriod(), - part.get().getId(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), + listAccreditations.add(new AccreditationDetailDto(part.getCampaign().getSurvey().getSource().getId(), + part.getCampaign().getSurvey().getSource().getShortWording(), + part.getCampaign().getSurvey().getYear(), part.getCampaign().getPeriod(), + part.getId(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), questioningAccreditation.isMain())); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index bb8411a8..3caa08ce 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -108,12 +108,8 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Missing fields"); } - Optional part = partitioningService.findById(idPartitioning); + Partitioning part = partitioningService.findById(idPartitioning); - if (!part.isPresent()) { - log.warn("Partitioning {} does not exist", idPartitioning); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Partitioning does not exist"); - } QuestioningWebclientDto questioningReturn = new QuestioningWebclientDto(); SurveyUnit su; @@ -122,10 +118,12 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que su = convertToEntity(questioningWebclientDto.getSurveyUnit()); // Create su if not exists or update - Optional optSuBase = surveyUnitService.findbyId(idSu); - if (optSuBase.isPresent()) { - su.setQuestionings(optSuBase.get().getQuestionings()); - } else { + try{ + SurveyUnit optSuBase = surveyUnitService.findbyId(idSu); + su.setQuestionings(optSuBase.getQuestionings()); + + } + catch (NotFoundException e){ log.warn("survey unit {} does not exist - Creation of the survey unit", idSu); su.setQuestionings(new HashSet<>()); @@ -152,7 +150,7 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que } - for (ContactAccreditationDto contactAccreditationDto : questioningWebclientDto.getContacts()){ + for (ContactAccreditationDto contactAccreditationDto : questioningWebclientDto.getContacts()) { createContactAndAccreditations(idSu, part, questioning, contactAccreditationDto); } @@ -168,7 +166,7 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que List listContactAccreditationDto = new ArrayList<>(); questioning.getQuestioningAccreditations().stream() .forEach(acc -> listContactAccreditationDto - .add(convertToDto(contactService.findByIdentifier(acc.getIdContact()).get(), acc.isMain()))); + .add(convertToDto(contactService.findByIdentifier(acc.getIdContact()), acc.isMain()))); questioningReturn.setContacts(listContactAccreditationDto); @@ -179,7 +177,7 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que } - private void createContactAndAccreditations(String idSu, Optional part, Questioning questioning, ContactAccreditationDto contactAccreditationDto) throws JsonProcessingException { + private void createContactAndAccreditations(String idSu, Partitioning part, Questioning questioning, ContactAccreditationDto contactAccreditationDto) throws JsonProcessingException { // Create contact if not exists or update JsonNode node = addWebclientAuthorNode(); @@ -201,12 +199,12 @@ private void createContactAndAccreditations(String idSu, Optional Set setExistingAccreditations = (questioning .getQuestioningAccreditations() != null) ? questioning.getQuestioningAccreditations() - : new HashSet<>(); + : new HashSet<>(); List listContactAccreditations = setExistingAccreditations.stream() .filter(acc -> acc.getIdContact().equals(contactAccreditationDto.getIdentifier()) - && acc.getQuestioning().getIdPartitioning().equals(part.get().getId()) + && acc.getQuestioning().getIdPartitioning().equals(part.getId()) && acc.getQuestioning().getSurveyUnit().getIdSu().equals(idSu)) .toList(); @@ -222,7 +220,7 @@ private void createContactAndAccreditations(String idSu, Optional // create view viewService.createView(contactAccreditationDto.getIdentifier(), questioning.getSurveyUnit().getIdSu(), - part.get().getCampaign().getId()); + part.getCampaign().getId()); questioning.getQuestioningAccreditations().add(questioningAccreditation); } else { @@ -240,9 +238,8 @@ private void createContactAndAccreditations(String idSu, Optional @ApiResponse(responseCode = "404", description = "Not found"), }) public ResponseEntity getQuestioning(@RequestParam(required = true) String modelName, - @RequestParam(required = true) String idPartitioning, - @RequestParam(required = true) String idSurveyUnit) - { + @RequestParam(required = true) String idPartitioning, + @RequestParam(required = true) String idSurveyUnit) { QuestioningWebclientDto questioningWebclientDto = new QuestioningWebclientDto(); @@ -260,7 +257,7 @@ public ResponseEntity getQuestioning(@RequestParam(required = true) String mo List listContactAccreditationDto = new ArrayList<>(); questioning.getQuestioningAccreditations().stream() .forEach(acc -> listContactAccreditationDto - .add(convertToDto(contactService.findByIdentifier(acc.getIdContact()).get(), acc.isMain()))); + .add(convertToDto(contactService.findByIdentifier(acc.getIdContact()), acc.isMain()))); questioningWebclientDto.setContacts(listContactAccreditationDto); return ResponseEntity.status(httpStatus).body(questioningWebclientDto); @@ -275,18 +272,16 @@ public ResponseEntity getQuestioning(@RequestParam(required = true) String mo }) public ResponseEntity getMetadata(@PathVariable("id") String id) { MetadataDto metadataDto = new MetadataDto(); + Partitioning part = partitioningService.findById(StringUtils.upperCase(id)); + try { - Optional part = partitioningService.findById(StringUtils.upperCase(id)); - if (!part.isPresent()) { - log.warn("partitioning {} does not exist", id); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("partitioning does not exist"); - } - metadataDto.setPartitioningDto(convertToDto(part.get())); - metadataDto.setCampaignDto(convertToDto(part.get().getCampaign())); - metadataDto.setSurveyDto(convertToDto(part.get().getCampaign().getSurvey())); - metadataDto.setSourceDto(convertToDto(part.get().getCampaign().getSurvey().getSource())); - metadataDto.setOwnerDto(convertToDto(part.get().getCampaign().getSurvey().getSource().getOwner())); - metadataDto.setSupportDto(convertToDto(part.get().getCampaign().getSurvey().getSource().getSupport())); + + metadataDto.setPartitioningDto(convertToDto(part)); + metadataDto.setCampaignDto(convertToDto(part.getCampaign())); + metadataDto.setSurveyDto(convertToDto(part.getCampaign().getSurvey())); + metadataDto.setSourceDto(convertToDto(part.getCampaign().getSurvey().getSource())); + metadataDto.setOwnerDto(convertToDto(part.getCampaign().getSurvey().getSource().getOwner())); + metadataDto.setSupportDto(convertToDto(part.getCampaign().getSurvey().getSource().getSupport())); return ResponseEntity.ok().body(metadataDto); } catch (Exception e) { @@ -304,7 +299,7 @@ public ResponseEntity getMetadata(@PathVariable("id") String id) { }) @Transactional public ResponseEntity putMetadata(@PathVariable("id") String id, - @RequestBody MetadataDto metadataDto) { + @RequestBody MetadataDto metadataDto) { try { if (StringUtils.isBlank(metadataDto.getPartitioningDto().getId()) || !metadataDto.getPartitioningDto().getId().equalsIgnoreCase(id)) { @@ -317,16 +312,17 @@ public ResponseEntity putMetadata(@PathVariable("id") String id, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(id).toUriString()); HttpStatus httpStatus; - if (partitioningService.findById(id).isPresent()) { - log.info("Update partitioning with the id {}", id); + try { partitioningService.findById(id); + log.info("Update partitioning with the id {}", id); httpStatus = HttpStatus.OK; - } else { + } catch (NotFoundException e) { log.info("Create partitioning with the id {}", id); httpStatus = HttpStatus.CREATED; } + Owner owner = convertToEntity(metadataDto.getOwnerDto()); Support support = convertToEntity(metadataDto.getSupportDto()); Source source = convertToEntity(metadataDto.getSourceDto()); @@ -401,11 +397,9 @@ public ResponseEntity getMainContact( List listQa = questioning.getQuestioningAccreditations().stream() .filter(qa -> qa.isMain()).toList(); if (listQa != null && !listQa.isEmpty()) { - Optional c = contactService.findByIdentifier(listQa.get(0).getIdContact()); - if(c.isPresent()) - return ResponseEntity.status(HttpStatus.OK).body(convertToDto((c.get()))); - else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No contact found"); + Contact c = contactService.findByIdentifier(listQa.get(0).getIdContact()); + return ResponseEntity.status(HttpStatus.OK).body(convertToDto((c))); + } } @@ -426,7 +420,7 @@ public ResponseEntity getMainContact( @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity getState(@PathVariable("idPartitioning") String idPartitioning, - @PathVariable("idSu") String idSu) { + @PathVariable("idSu") String idSu) { Questioning questioning = questioningService.findByIdPartitioningAndSurveyUnitIdSu( idPartitioning, idSu); @@ -513,7 +507,7 @@ private JsonNode addWebclientAuthorNode() throws JsonProcessingException { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity isToExtract(@PathVariable("idPartitioning") String idPartitioning, - @PathVariable("idSu") String idSu) { + @PathVariable("idSu") String idSu) { Questioning questioning = questioningService.findByIdPartitioningAndSurveyUnitIdSu( idPartitioning, idSu); @@ -560,12 +554,10 @@ private Contact convertToEntity(ContactAccreditationDto contactAccreditationDto) Contact contact = modelMapper.map(contactAccreditationDto, Contact.class); contact.setGender(contactAccreditationDto.getCivility()); - Optional oldContact = contactService.findByIdentifier(contactAccreditationDto.getIdentifier()); - if (!oldContact.isPresent()) - throw new NoSuchElementException(); - contact.setComment(oldContact.get().getComment()); - contact.setAddress(oldContact.get().getAddress()); - contact.setContactEvents(oldContact.get().getContactEvents()); + Contact oldContact = contactService.findByIdentifier(contactAccreditationDto.getIdentifier()); + contact.setComment(oldContact.getComment()); + contact.setAddress(oldContact.getAddress()); + contact.setContactEvents(oldContact.getContactEvents()); return contact; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java index b1eb2c1f..01bc3f14 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/repository/MoogRepository.java @@ -2,9 +2,11 @@ import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.query.dto.MoogExtractionRowDto; import fr.insee.survey.datacollectionmanagement.query.dto.MoogQuestioningEventDto; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; @@ -12,10 +14,10 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; -import java.util.Optional; @Repository @RequiredArgsConstructor +@Slf4j public class MoogRepository { private final JdbcTemplate jdbcTemplate; @@ -101,7 +103,6 @@ public MoogExtractionRowDto mapRow(ResultSet rs, int rowNum) throws SQLException MoogExtractionRowDto ev = new MoogExtractionRowDto(); ev.setAddress("addresse non connue"); - Optional
address = addressService.findById(rs.getLong("address")); ev.setStatus(rs.getString("status")); ev.setDateInfo(rs.getString("dateinfo")); @@ -109,9 +110,14 @@ public MoogExtractionRowDto mapRow(ResultSet rs, int rowNum) throws SQLException ev.setIdContact(rs.getString("id_contact")); ev.setLastname(rs.getString("lastname")); ev.setFirstname(rs.getString("firstname")); - if (address.isPresent()) { - ev.setAddress(address.get().toStringMoog()); + try { + Address address = addressService.findById(rs.getLong("address")); + ev.setAddress(address.toStringMoog()); } + catch (NotFoundException e){ + log.info("Address not found"); + } + ev.setBatchNumber(rs.getString("batch_num")); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java index d9465825..7a6b39a8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/CheckHabilitationServiceImplOidc.java @@ -4,6 +4,7 @@ import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; import fr.insee.survey.datacollectionmanagement.constants.AuthConstants; import fr.insee.survey.datacollectionmanagement.constants.CheckHabilitationsRoles; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import fr.insee.survey.datacollectionmanagement.user.domain.User; import fr.insee.survey.datacollectionmanagement.user.service.UserService; @@ -14,7 +15,6 @@ import org.springframework.stereotype.Service; import java.util.List; -import java.util.Optional; @Service @RequiredArgsConstructor @@ -56,15 +56,17 @@ public boolean checkHabilitation(String role, String idSu, String campaignId, Au log.warn("User {} - internal user habilitation not found in token - Check habilitation:false", userId); return false; } - - Optional user = userService.findByIdentifier(userId); - if (user.isEmpty()) { + User user; + try { + user = userService.findByIdentifier(userId); + } catch (NotFoundException e) { log.warn("User '{}' doesn't exists", userId); return false; } + if (isUserInRole(authUser.getRoles(), applicationConfig.getRoleInternalUser())) { - String userRole = user.get().getRole().toString(); + String userRole = user.getRole().toString(); if (userRole.equals(User.UserRoleType.ASSISTANCE.toString())) { log.warn("User '{}' has assistance profile - check habilitation: false", userId); return false; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java index 64f60c44..562d5aef 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MoogServiceImpl.java @@ -56,28 +56,22 @@ public List transformListViewToListMoogSearchDto(List listV List listResult = new ArrayList<>(); for (View view : listView) { MoogSearchDto moogSearchDto = new MoogSearchDto(); - Optional c = contactService.findByIdentifier(view.getIdentifier()); - Optional camp = campaignService.findById(view.getCampaignId()); - if (!camp.isPresent()) { - throw new NoSuchElementException("campaign does not exist"); - } - if (!c.isPresent()) { - throw new NoSuchElementException("contact does not exist"); - } - MoogCampaign moogCampaign = new MoogCampaign(); + Contact c = contactService.findByIdentifier(view.getIdentifier()); + Campaign camp = campaignService.findById(view.getCampaignId()); + MoogCampaign moogCampaign = new MoogCampaign(); moogCampaign.setId(view.getCampaignId()); - moogCampaign.setLabel(camp.get().getCampaignWording()); + moogCampaign.setLabel(camp.getCampaignWording()); moogCampaign - .setCollectionEndDate(camp.get().getPartitionings().iterator().next().getClosingDate().getTime()); + .setCollectionEndDate(camp.getPartitionings().iterator().next().getClosingDate().getTime()); moogCampaign - .setCollectionStartDate(camp.get().getPartitionings().iterator().next().getOpeningDate().getTime()); + .setCollectionStartDate(camp.getPartitionings().iterator().next().getOpeningDate().getTime()); moogSearchDto.setIdContact(view.getIdentifier()); - moogSearchDto.setAddress(c.get().getAddress().getZipCode().concat(" ").concat(c.get().getAddress().getCityName())); + moogSearchDto.setAddress(c.getAddress().getZipCode().concat(" ").concat(c.getAddress().getCityName())); moogSearchDto.setIdSu(view.getIdSu()); moogSearchDto.setCampaign(moogCampaign); - moogSearchDto.setFirstName(c.get().getFirstName()); - moogSearchDto.setLastname(c.get().getLastName()); - moogSearchDto.setSource(camp.get().getSurvey().getSource().getId()); + moogSearchDto.setFirstName(c.getFirstName()); + moogSearchDto.setLastname(c.getLastName()); + moogSearchDto.setSource(camp.getSurvey().getSource().getId()); listResult.add(moogSearchDto); } return listResult; @@ -88,15 +82,12 @@ public List getMoogEvents(String campaign, String idSu) List moogEvents = moogRepository.getEventsByIdSuByCampaign(campaign, idSu); - Optional camp = campaignService.findById(campaign); - if (!camp.isPresent()) { - throw new NoSuchElementException("campaign does not exist"); - } + Campaign camp = campaignService.findById(campaign); MoogCampaign moogCampaign = new MoogCampaign(); moogCampaign.setId(campaign); - moogCampaign.setLabel(camp.get().getCampaignWording()); - moogCampaign.setCollectionEndDate(camp.get().getPartitionings().iterator().next().getClosingDate().getTime()); - moogCampaign.setCollectionStartDate(camp.get().getPartitionings().iterator().next().getOpeningDate().getTime()); + moogCampaign.setLabel(camp.getCampaignWording()); + moogCampaign.setCollectionEndDate(camp.getPartitionings().iterator().next().getClosingDate().getTime()); + moogCampaign.setCollectionStartDate(camp.getPartitionings().iterator().next().getOpeningDate().getTime()); MoogSearchDto surveyUnit = new MoogSearchDto(); surveyUnit.setCampaign(moogCampaign); moogEvents.stream().forEach(e -> e.setSurveyUnit(surveyUnit)); @@ -115,11 +106,8 @@ public Collection getSurveyUnitsToFollowUp(String idCampai @Override public String getReadOnlyUrl(String idCampaign, String surveyUnitId) throws NotFoundException { - Optional campaign = campaignService.findById(idCampaign); - if (!campaign.isPresent()) { - throw new NotFoundException("Campaign not found"); - } - Set setParts = campaign.get().getPartitionings(); + Campaign campaign = campaignService.findById(idCampaign); + Set setParts = campaign.getPartitionings(); Questioning questioning = null; for (Partitioning part : setParts){ Questioning qTemp = questioningService.findByIdPartitioningAndSurveyUnitIdSu(part.getId(), surveyUnitId); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java index 95dbff83..aa55bd8c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/MySurveysServiceImpl.java @@ -43,29 +43,28 @@ public List getListMySurveys(String id) { for (QuestioningAccreditation questioningAccreditation : accreditations) { MyQuestioningDto surveyDto = new MyQuestioningDto(); Questioning questioning = questioningAccreditation.getQuestioning(); - Optional part = partitioningService.findById(questioning.getIdPartitioning()); - if (part.isPresent()) { - Survey survey = part.get().getCampaign().getSurvey(); - String surveyUnitId = questioning.getSurveyUnit().getIdSu(); - surveyDto.setSurveyWording(survey.getLongWording()); - surveyDto.setSurveyObjectives(survey.getLongObjectives()); - surveyDto.setAccessUrl( - questioningService.getAccessUrl(questioning, surveyUnitId)); - surveyDto.setIdentificationCode(surveyUnitId); - surveyDto.setOpeningDate(new Timestamp(part.get().getOpeningDate().getTime())); - surveyDto.setClosingDate(new Timestamp(part.get().getClosingDate().getTime())); - surveyDto.setReturnDate(new Timestamp(part.get().getReturnDate().getTime())); - surveyDto.setMandatoryMySurveys(part.get().getCampaign().getSurvey().getSource().getMandatoryMySurveys()); - - Optional questioningEvent = questioningEventService.getLastQuestioningEvent( - questioning, TypeQuestioningEvent.MY_QUESTIONINGS_EVENTS); - if (questioningEvent.isPresent()) { - surveyDto.setQuestioningStatus(questioningEvent.get().getType().name()); - surveyDto.setQuestioningDate(new Timestamp(questioningEvent.get().getDate().getTime())); - } else { - log.debug("No questioningEvents found for questioning {} for identifier {}", - questioning.getId(), id); - } + Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); + Survey survey = part.getCampaign().getSurvey(); + String surveyUnitId = questioning.getSurveyUnit().getIdSu(); + surveyDto.setSurveyWording(survey.getLongWording()); + surveyDto.setSurveyObjectives(survey.getLongObjectives()); + surveyDto.setAccessUrl( + questioningService.getAccessUrl(questioning, surveyUnitId)); + surveyDto.setIdentificationCode(surveyUnitId); + surveyDto.setOpeningDate(new Timestamp(part.getOpeningDate().getTime())); + surveyDto.setClosingDate(new Timestamp(part.getClosingDate().getTime())); + surveyDto.setReturnDate(new Timestamp(part.getReturnDate().getTime())); + surveyDto.setMandatoryMySurveys(part.getCampaign().getSurvey().getSource().getMandatoryMySurveys()); + + Optional questioningEvent = questioningEventService.getLastQuestioningEvent( + questioning, TypeQuestioningEvent.MY_QUESTIONINGS_EVENTS); + if (questioningEvent.isPresent()) { + surveyDto.setQuestioningStatus(questioningEvent.get().getType().name()); + surveyDto.setQuestioningDate(new Timestamp(questioningEvent.get().getDate().getTime())); + } else { + log.debug("No questioningEvents found for questioning {} for identifier {}", + questioning.getId(), id); + } listSurveys.add(surveyDto); @@ -76,5 +75,4 @@ public List getListMySurveys(String id) { } - } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 8086bf4e..2559fa23 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -121,7 +121,7 @@ public List searchContactCrossDomain( listView = listView.stream() .filter(v -> lastName - .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getLastName())) + .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getLastName())) .toList(); } @@ -136,7 +136,7 @@ public List searchContactCrossDomain( listView = listView.stream() .filter(v -> firstName - .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getFirstName())) + .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getFirstName())) .toList(); } @@ -150,7 +150,7 @@ public List searchContactCrossDomain( } else if (!alwaysEmpty) listView = listView.stream().filter( - v -> email.equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).get().getEmail())) + v -> email.equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getEmail())) .toList(); } @@ -198,7 +198,7 @@ public List transformListViewDaoToDto(List listView) { for (View v : listView) { SearchContactDto searchContact = new SearchContactDto(); - Contact c = contactService.findByIdentifier(v.getIdentifier()).get(); + Contact c = contactService.findByIdentifier(v.getIdentifier()); searchContact.setIdentifier(c.getIdentifier()); searchContact.setFirstName(c.getFirstName()); searchContact.setLastName(c.getLastName()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java index c5f94c86..9d30c2dc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestioningEventController.java @@ -30,7 +30,6 @@ import java.text.ParseException; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -59,18 +58,12 @@ public class QuestioningEventController { @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity findQuestioningEventsByQuestioning(@PathVariable("id") Long id) { - try { - Optional questioning = questioningService.findbyId(id); - if (questioning.isPresent()) { - Set setQe = questioning.get().getQuestioningEvents(); - return ResponseEntity.status(HttpStatus.OK) - .body(setQe.stream() - .map(this::convertToDto).toList()); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("questioning not found"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + Questioning questioning = questioningService.findbyId(id); + Set setQe = questioning.getQuestioningEvents(); + return ResponseEntity.status(HttpStatus.OK) + .body(setQe.stream() + .map(this::convertToDto).toList()); + } @Operation(summary = "Create a questioning event") @@ -80,24 +73,22 @@ public ResponseEntity findQuestioningEventsByQuestioning(@PathVariable("id") @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity postQuestioningEvent(@Parameter(description = "questioning id") Long id, - @RequestBody QuestioningEventDto questioningEventDto) { + @RequestBody QuestioningEventDto questioningEventDto) { + Questioning questioning = questioningService.findbyId(id); + try { - Optional optQuestioning = questioningService.findbyId(id); - if (optQuestioning.isPresent()) { - Questioning questioning = optQuestioning.get(); - QuestioningEvent questioningEvent = convertToEntity(questioningEventDto); - QuestioningEvent newQuestioningEvent = questioningEventService.saveQuestioningEvent(questioningEvent); - Set setQuestioningEvents = questioning.getQuestioningEvents(); - setQuestioningEvents.add(newQuestioningEvent); - questioning.setQuestioningEvents(setQuestioningEvents); - questioningService.saveQuestioning(questioning); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(newQuestioningEvent)); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Questioning does not exist"); + QuestioningEvent questioningEvent = convertToEntity(questioningEventDto); + QuestioningEvent newQuestioningEvent = questioningEventService.saveQuestioningEvent(questioningEvent); + Set setQuestioningEvents = questioning.getQuestioningEvents(); + setQuestioningEvents.add(newQuestioningEvent); + questioning.setQuestioningEvents(setQuestioningEvents); + questioningService.saveQuestioning(questioning); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(newQuestioningEvent)); + } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -112,21 +103,20 @@ public ResponseEntity postQuestioningEvent(@Parameter(description = "question @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity deleteQuestioningEvent(@PathVariable("id") Long id) { + QuestioningEvent questioningEvent = questioningEventService.findbyId(id); + try { - Optional questioningEvent = questioningEventService.findbyId(id); - if (questioningEvent.isPresent()) { - Upload upload = (questioningEvent.get().getUpload() != null ? questioningEvent.get().getUpload() : null); - Questioning quesitoning = questioningEvent.get().getQuestioning(); - quesitoning.setQuestioningEvents(quesitoning.getQuestioningEvents().stream() - .filter(qe -> !qe.equals(questioningEvent.get())).collect(Collectors.toSet())); - questioningService.saveQuestioning(quesitoning); - questioningEventService.deleteQuestioningEvent(id); - if(upload!=null && questioningEventService.findbyIdUpload(upload.getId()).size()==0 ){ - uploadService.delete(upload); - } - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Questioning event deleted"); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Questioning event does not exist"); + Upload upload = (questioningEvent.getUpload() != null ? questioningEvent.getUpload() : null); + Questioning quesitoning = questioningEvent.getQuestioning(); + quesitoning.setQuestioningEvents(quesitoning.getQuestioningEvents().stream() + .filter(qe -> !qe.equals(questioningEvent)).collect(Collectors.toSet())); + questioningService.saveQuestioning(quesitoning); + questioningEventService.deleteQuestioningEvent(id); + if (upload != null && questioningEventService.findbyIdUpload(upload.getId()).size() == 0) { + uploadService.delete(upload); + } + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Questioning event deleted"); + } catch (Exception e) { return new ResponseEntity("Error", HttpStatus.BAD_REQUEST); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index d60db240..bf69bd01 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.dto.SurveyUnitDto; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; @@ -24,7 +25,6 @@ import java.text.ParseException; import java.util.List; -import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -63,16 +63,8 @@ public Page getSurveyUnits( @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { - - try { - Optional surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); - if (surveyUnit.isPresent()) - return ResponseEntity.status(HttpStatus.OK).body(convertToDto(surveyUnit.get())); - else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey unit not found"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); + return ResponseEntity.status(HttpStatus.OK).body(convertToDto(surveyUnit)); } @@ -100,13 +92,16 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse survey unit"); } - - if (surveyUnitService.findbyId(surveyUnitDto.getIdSu()).isPresent()) + try{ + surveyUnitService.findbyId(surveyUnitDto.getIdSu()); responseStatus = HttpStatus.OK; - else { + + } + catch (NotFoundException e){ log.info("Creating survey with the id {}", surveyUnitDto.getIdSu()); responseStatus = HttpStatus.CREATED; } + return ResponseEntity.status(responseStatus) .body(convertToDto(surveyUnitService.saveSurveyUnitAndAddress(surveyUnit))); @@ -120,18 +115,17 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity deleteSurveyUnit(@PathVariable("id") String id) { + SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); + try { - Optional surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); - if (surveyUnit.isPresent()) { - if (!surveyUnit.get().getQuestionings().isEmpty()) { + if (!surveyUnit.getQuestionings().isEmpty()) { log.warn("Some questionings exist for the survey unit {}, the survey unit can't be deleted", id); return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Some questionings exist for this survey unit, the survey unit can't be deleted"); } surveyUnitService.deleteSurveyUnit(id); return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey unit deleted"); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("survey unit not found"); + } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java index e4cf778e..ef41592c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/UploadController.java @@ -18,7 +18,6 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import java.util.Optional; import java.util.stream.Collectors; @RestController @@ -40,11 +39,7 @@ public class UploadController { public ResponseEntity deleteOneUpload(@PathVariable Long id) { log.info("Request DELETE for upload n° {}", id); - Optional upOpt = moogUploadService.findById(id); - if(!upOpt.isPresent()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Upload does not exist"); - } - Upload up = upOpt.get(); + Upload up = moogUploadService.findById(id); up.getQuestioningEvents().stream().forEach(q -> { Questioning quesitoning = q.getQuestioning(); quesitoning.setQuestioningEvents(quesitoning.getQuestioningEvents().stream() diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java index 44f41819..31f82a4b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java @@ -1,14 +1,12 @@ package fr.insee.survey.datacollectionmanagement.questioning.service; -import java.util.List; -import java.util.Optional; -import java.util.Set; - +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; +import java.util.List; +import java.util.Set; public interface QuestioningAccreditationService { @@ -30,7 +28,7 @@ public interface QuestioningAccreditationService { public Page findAll(Pageable pageable); - public Optional findById(Long id); + public QuestioningAccreditation findById(Long id); public QuestioningAccreditation saveQuestioningAccreditation(QuestioningAccreditation questioningAccreditation); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningEventService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningEventService.java index 0fd890e3..654da18d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningEventService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningEventService.java @@ -1,18 +1,17 @@ package fr.insee.survey.datacollectionmanagement.questioning.service; -import java.util.List; -import java.util.Optional; - -import org.springframework.stereotype.Service; - import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; @Service public interface QuestioningEventService { - public Optional findbyId(Long id); + public QuestioningEvent findbyId(Long id); public QuestioningEvent saveQuestioningEvent(QuestioningEvent questioningEvent); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningService.java index 743679c4..cd35e88d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningService.java @@ -1,19 +1,17 @@ package fr.insee.survey.datacollectionmanagement.questioning.service; -import java.util.Optional; -import java.util.Set; - +import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import java.util.Set; public interface QuestioningService { public Page findAll(Pageable pageable); - public Optional findbyId(Long id); + public Questioning findbyId(Long id); public Questioning saveQuestioning(Questioning questioning); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java index 6c1ae94a..61c95856 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java @@ -1,16 +1,14 @@ package fr.insee.survey.datacollectionmanagement.questioning.service; -import java.util.List; -import java.util.Optional; - +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; +import java.util.List; public interface SurveyUnitService { - public Optional findbyId(String idSu); + public SurveyUnit findbyId(String idSu); public List findbyIdentificationCode(String identificationCode); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/UploadService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/UploadService.java index 2677b925..4709defc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/UploadService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/UploadService.java @@ -8,14 +8,13 @@ import java.util.Date; import java.util.List; -import java.util.Optional; @Service public interface UploadService { public ResultUpload save(String idCampaign, UploadDto uploadDto) throws RessourceNotValidatedException; - public Optional findById(long id); + public Upload findById(long id); public List findAllByIdCampaign(String idCampaign); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java index f30f3e3d..1dbbf020 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; @@ -12,7 +13,6 @@ import java.util.HashSet; import java.util.List; -import java.util.Optional; import java.util.Set; @Service @@ -69,8 +69,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findById(Long id) { - return questioningAccreditationRepository.findById(id); + public QuestioningAccreditation findById(Long id) { + return questioningAccreditationRepository.findById(id).orElseThrow(()-> new NotFoundException(String.format("QuestioningAccreditation %s not found", id))); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java index 12cee8a3..42b5743f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningEventServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.repository.QuestioningEventRepository; @@ -21,8 +22,8 @@ public class QuestioningEventServiceImpl implements QuestioningEventService { private final QuestioningEventRepository questioningEventRepository; @Override - public Optional findbyId(Long id) { - return questioningEventRepository.findById(id); + public QuestioningEvent findbyId(Long id) { + return questioningEventRepository.findById(id).orElseThrow(() -> new NotFoundException(String.format("QuestioningEvent %s not found", id))); } @Override @@ -38,7 +39,7 @@ public void deleteQuestioningEvent(Long id) { @Override public Optional getLastQuestioningEvent(Questioning questioning, - List events) { + List events) { List listQuestioningEvent = questioning.getQuestioningEvents().stream() .filter(qe -> events.contains(qe.getType())).sorted(lastQuestioningEventComparator).toList(); @@ -46,8 +47,8 @@ public Optional getLastQuestioningEvent(Questioning questionin } @Override - public List findbyIdUpload(Long id){ - return questioningEventRepository.findAll().stream().filter(qe -> qe.getUpload()!= null && qe.getUpload().getId().equals(id)).toList(); + public List findbyIdUpload(Long id) { + return questioningEventRepository.findAll().stream().filter(qe -> qe.getUpload() != null && qe.getUpload().getId().equals(id)).toList(); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java index cf5fbf5d..bce0bfd7 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningServiceImpl.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; import fr.insee.survey.datacollectionmanagement.config.ApplicationConfig; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; @@ -14,7 +15,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Optional; import java.util.Set; @Service @@ -37,8 +37,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findbyId(Long id) { - return questioningRepository.findById(id); + public Questioning findbyId(Long id) { + return questioningRepository.findById(id).orElseThrow(() -> new NotFoundException(String.format("Questioning %s not found", id))); } @Override @@ -80,14 +80,14 @@ public Set findBySurveyUnitIdSu(String idSu) { @Override public String getAccessUrl(Questioning questioning, String surveyUnitId) { - return applicationConfig.getQuestioningUrl() + "/questionnaire/" + questioning.getModelName() - + "/unite-enquetee/" + surveyUnitId; - } + return applicationConfig.getQuestioningUrl() + "/questionnaire/" + questioning.getModelName() + + "/unite-enquetee/" + surveyUnitId; + } @Override public Questioning findByIdPartitioningAndSurveyUnitIdSu(String idPartitioning, - String surveyUnitIdSu) { + String surveyUnitIdSu) { return questioningRepository.findByIdPartitioningAndSurveyUnitIdSu(idPartitioning, surveyUnitIdSu); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java index e655d04d..7c087605 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitAddressRepository; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; @@ -11,7 +12,6 @@ import org.springframework.stereotype.Service; import java.util.List; -import java.util.Optional; @Service @Slf4j @@ -23,8 +23,8 @@ public class SurveyUnitServiceImpl implements SurveyUnitService { private final SurveyUnitAddressRepository surveyUnitAddressRepository; @Override - public Optional findbyId(String idSu) { - return surveyUnitRepository.findById(idSu); + public SurveyUnit findbyId(String idSu) { + return surveyUnitRepository.findById(idSu).orElseThrow(() -> new NotFoundException(String.format("SurveyUnit %s not found", idSu))); } @Override @@ -51,18 +51,20 @@ public SurveyUnit saveSurveyUnit(SurveyUnit surveyUnit) { public SurveyUnit saveSurveyUnitAndAddress(SurveyUnit surveyUnit) { if (surveyUnit.getSurveyUnitAddress() != null) { - - Optional existingSurveyUnit = findbyId(surveyUnit.getIdSu()); - if (existingSurveyUnit.isPresent()) { - if (existingSurveyUnit.get().getSurveyUnitAddress() != null) { - surveyUnit.getSurveyUnitAddress().setId(existingSurveyUnit.get().getSurveyUnitAddress().getId()); + try { + SurveyUnit existingSurveyUnit = findbyId(surveyUnit.getIdSu()); + if (existingSurveyUnit.getSurveyUnitAddress() != null) { + surveyUnit.getSurveyUnitAddress().setId(existingSurveyUnit.getSurveyUnitAddress().getId()); } - } else - log.info("Survey unit does not exist"); - + } + catch (NotFoundException e){ + log.debug("Survey unit does not exist"); + } surveyUnitAddressRepository.save(surveyUnit.getSurveyUnitAddress()); + } return surveyUnitRepository.save(surveyUnit); + } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java index f034f877..a2f9b937 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/UploadServiceImpl.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.questioning.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.exception.RessourceNotValidatedException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -59,18 +60,15 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc try { QuestioningEvent qe = new QuestioningEvent(); - Optional campaign = campaignService.findById(idCampaign); - if (campaign.isEmpty()) { - throw new RessourceNotValidatedException("Campaign", idCampaign); - } - Set setParts = campaign.get().getPartitionings(); + Campaign campaign = campaignService.findById(idCampaign); + Set setParts = campaign.getPartitionings(); if (setParts.isEmpty()) { throw new RessourceNotValidatedException("No partitionings found for campaign ", idCampaign); } Set questionings = questioningService.findBySurveyUnitIdSu(mmDto.getIdSu()); - List listIdParts = campaignService.findById(idCampaign).get().getPartitionings().stream().map(Partitioning::getId).toList(); + List listIdParts = campaignService.findById(idCampaign).getPartitionings().stream().map(Partitioning::getId).toList(); Optional quest = questionings.stream().filter(q -> listIdParts.contains(q.getIdPartitioning()) && q.getQuestioningAccreditations().stream().map(QuestioningAccreditation::getIdContact) .toList().contains(mmDto.getIdContact())).findFirst(); @@ -105,25 +103,23 @@ public ResultUpload save(String idCampaign, UploadDto uploadDto) throws Ressourc } @Override - public Optional findById(long id) { - return uploadRepository.findById(id); + public Upload findById(long id) { + return uploadRepository.findById(id).orElseThrow(()-> new NotFoundException(String.format("Upload %s not found", id))); } @Override public List findAllByIdCampaign(String idCampaign) { - Optional campaign = campaignService.findById(idCampaign); - if (campaign.isPresent()) { + Campaign campaign = campaignService.findById(idCampaign); - List partitioningIds = campaign.get().getPartitionings().stream().map(Partitioning::getId).toList(); + List partitioningIds = campaign.getPartitionings().stream().map(Partitioning::getId).toList(); + + // Keeps the uploads which first managementMonitoringInfo belongs to the survey + return uploadRepository.findAll().stream().filter(upload -> !upload.getQuestioningEvents().isEmpty()) + .filter(upload -> partitioningIds.contains(upload.getQuestioningEvents().stream().findFirst().get().getQuestioning().getIdPartitioning() + )) + .toList(); - // Keeps the uploads which first managementMonitoringInfo belongs to the survey - return uploadRepository.findAll().stream().filter(upload -> !upload.getQuestioningEvents().isEmpty()) - .filter(upload -> partitioningIds.contains(upload.getQuestioningEvents().stream().findFirst().get().getQuestioning().getIdPartitioning() - )) - .toList(); - } - return Collections.emptyList(); } @@ -139,21 +135,19 @@ public Upload saveAndFlush(Upload up) { @Override public boolean checkUploadDate(String idCampaign, Date date) { - Optional campaign = campaignService.findById(idCampaign); + Campaign campaign = campaignService.findById(idCampaign); long timestamp = date.getTime(); - if (campaign.isPresent()) { - Optional openingDate = campaign.get().getPartitionings().stream().map(Partitioning::getOpeningDate) - .toList().stream() - .min(Comparator.comparing(Date::getTime)); - Optional closingDate = campaign.get().getPartitionings().stream().map(Partitioning::getClosingDate) - .toList().stream() - .max(Comparator.comparing(Date::getTime)); - if(openingDate.isPresent() && closingDate.isPresent()){ - long start = openingDate.get().getTime(); - long end = closingDate.get().getTime(); - return (start < timestamp && timestamp < end); + Optional openingDate = campaign.getPartitionings().stream().map(Partitioning::getOpeningDate) + .toList().stream() + .min(Comparator.comparing(Date::getTime)); + Optional closingDate = campaign.getPartitionings().stream().map(Partitioning::getClosingDate) + .toList().stream() + .max(Comparator.comparing(Date::getTime)); + if (openingDate.isPresent() && closingDate.isPresent()) { + long start = openingDate.get().getTime(); + long end = closingDate.get().getTime(); + return (start < timestamp && timestamp < end); - } } return false; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java index d5e55768..55097b32 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/SourceAccreditationController.java @@ -30,7 +30,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.util.List; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -62,16 +61,12 @@ public class SourceAccreditationController { @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity getSourceAccreditation(@PathVariable("id") String id) { + Source source = sourceService.findById(id); try { - Optional optSource = sourceService.findById(id); - if (optSource.isPresent()) - return new ResponseEntity<>( - optSource.get().getSourceAccreditations().stream().map(c -> convertToDto(c)) - .collect(Collectors.toList()), - HttpStatus.OK); - else - return new ResponseEntity<>("Source does not exist", HttpStatus.NOT_FOUND); + return ResponseEntity.ok().body(source.getSourceAccreditations().stream().map(c -> convertToDto(c)) + .collect(Collectors.toList())); + } catch (Exception e) { return new ResponseEntity("Error", HttpStatus.INTERNAL_SERVER_ERROR); } @@ -87,25 +82,11 @@ public ResponseEntity getSourceAccreditation(@PathVariable("id") String id) { }) @Transactional public ResponseEntity postSourceAccreditation(@PathVariable("id") String id, - @Valid @RequestBody SourceAccreditationDto sourceAccreditationDto) { - - Optional optSource = null; + @Valid @RequestBody SourceAccreditationDto sourceAccreditationDto) { + Source source = sourceService.findById(id);; String idUser = sourceAccreditationDto.getIdUser(); - - // Check if questioning exists - try { - optSource = sourceService.findById(id); - if (!optSource.isPresent()) - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Source does not exist"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } - Source source = optSource.get(); - - // Check if contact exists - if (!userService.findByIdentifier(idUser).isPresent()) - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); + userService.findByIdentifier(idUser); HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 8b16b783..0144176c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -32,8 +32,6 @@ import java.text.ParseException; import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; import java.util.Set; @RestController @@ -71,21 +69,10 @@ public ResponseEntity getUsers( @Operation(summary = "Search for a user by its id") @GetMapping(value = Constants.API_USERS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = UserDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) - public ResponseEntity getUser(@PathVariable("id") String id) { - Optional user = userService.findByIdentifier(id); - try { - if (user.isPresent()) - return ResponseEntity.ok().body(convertToDto(user.get())); - else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("user does not exist"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + public ResponseEntity getUser(@PathVariable("id") String id) { + User user = userService.findByIdentifier(id); + return ResponseEntity.ok().body(convertToDto(user)); + } @@ -110,7 +97,7 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse user"); - } catch (NoSuchElementException e) { + } catch (NotFoundException e) { log.info("Creating user with the identifier {}", userDto.getIdentifier()); user = convertToEntityNewUser(userDto); @@ -119,12 +106,8 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody } log.info("Updating user with the identifier {}", userDto.getIdentifier()); - User userUpdate = null; - try { - userUpdate = userService.updateUser(user, null); - } catch (NotFoundException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Problem when saving user"); - } + User userUpdate = userService.updateUser(user, null); + return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(userUpdate)); } @@ -138,25 +121,22 @@ public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody }) @Transactional public ResponseEntity deleteUser(@PathVariable("id") String id) { + User user = userService.findByIdentifier(id); + try { - Optional user = userService.findByIdentifier(id); - if (user.isPresent()) { - userService.deleteUserAndEvents(user.get()); - - sourceAccreditationService.findByUserIdentifier(id).stream().forEach(acc -> { - Source source = sourceService.findById(acc.getSource().getId()).get(); - Set newSet = source.getSourceAccreditations(); - newSet.removeIf(a -> a.getId().equals(acc.getId())); - source.setSourceAccreditations(newSet); - sourceService.insertOrUpdateSource(source); - sourceAccreditationService.deleteAccreditation(acc); - - }); - log.info("Delete user {}", id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("User deleted"); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); - } + userService.deleteUserAndEvents(user); + + sourceAccreditationService.findByUserIdentifier(id).stream().forEach(acc -> { + Source source = sourceService.findById(acc.getSource().getId()); + Set newSet = source.getSourceAccreditations(); + newSet.removeIf(a -> a.getId().equals(acc.getId())); + source.setSourceAccreditations(newSet); + sourceService.insertOrUpdateSource(source); + sourceAccreditationService.deleteAccreditation(acc); + + }); + log.info("Delete user {}", id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("User deleted"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -170,25 +150,18 @@ public ResponseEntity deleteUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad Request") }) public ResponseEntity getUserSources(@PathVariable("id") String id) { - Optional user = userService.findByIdentifier(id); - if (user.isPresent()) { - List accreditedSources = userService.findAccreditedSources(id); - return ResponseEntity.status(HttpStatus.OK).body(accreditedSources); - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); - } + userService.findByIdentifier(id); + List accreditedSources = userService.findAccreditedSources(id); + return ResponseEntity.status(HttpStatus.OK).body(accreditedSources); } - private User convertToEntity(UserDto userDto) throws ParseException, NoSuchElementException { + private User convertToEntity(UserDto userDto) throws ParseException { - Optional oldUser = userService.findByIdentifier(userDto.getIdentifier()); - if (!oldUser.isPresent()) { - throw new NoSuchElementException(); - } + User oldUser = userService.findByIdentifier(userDto.getIdentifier()); User user = modelMapper.map(userDto, User.class); user.setRole(User.UserRoleType.valueOf(userDto.getRole().toUpperCase())); - user.setUserEvents(oldUser.get().getUserEvents()); + user.setUserEvents(oldUser.getUserEvents()); return user; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java index 03dab014..e8052ae2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserEventController.java @@ -2,7 +2,6 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.exception.EventException; import fr.insee.survey.datacollectionmanagement.user.domain.User; import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.dto.UserEventDto; @@ -27,12 +26,10 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; -@RestController(value="UserEvents") +@RestController(value = "UserEvents") @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") @@ -55,17 +52,13 @@ public class UserEventController { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Internal servor error") }) - public ResponseEntity getUserUserEvents(@PathVariable("id") String identifier) { - try { - - Optional optUser = userService.findByIdentifier(identifier); - if (optUser.isPresent()) { - return ResponseEntity.status(HttpStatus.OK) - .body(optUser.get().getUserEvents().stream().map(this::convertToDto) - .toList()); + public ResponseEntity getUserUserEvents(@PathVariable("id") String identifier) { + User user = userService.findByIdentifier(identifier); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); + try { + return ResponseEntity.status(HttpStatus.OK) + .body(user.getUserEvents().stream().map(this::convertToDto) + .toList()); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } @@ -79,30 +72,21 @@ public ResponseEntity getUserUserEvents(@PathVariable("id") String identifier @ApiResponse(responseCode = "400", description = "Bad request"), @ApiResponse(responseCode = "404", description = "Not found") }) - public ResponseEntity postUserEvent(@Valid @RequestBody UserEventDto userEventDto) { - try { + public ResponseEntity postUserEvent(@Valid @RequestBody UserEventDto userEventDto) { + + User user = userService.findByIdentifier(userEventDto.getIdentifier()); + UserEvent userEvent = convertToEntity(userEventDto); + UserEvent newUserEvent = userEventService.saveUserEvent(userEvent); + Set setUserEvents = user.getUserEvents(); + setUserEvents.add(newUserEvent); + user.setUserEvents(setUserEvents); + userService.saveUser(user); + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.set(HttpHeaders.LOCATION, + ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); + return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) + .body(convertToDto(newUserEvent)); - Optional optUser = userService.findByIdentifier(userEventDto.getIdentifier()); - if (optUser.isPresent()) { - User user = optUser.get(); - UserEvent userEvent = convertToEntity(userEventDto); - UserEvent newUserEvent = userEventService.saveUserEvent(userEvent); - Set setUserEvents = user.getUserEvents(); - setUserEvents.add(newUserEvent); - user.setUserEvents(setUserEvents); - userService.saveUser(user); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set(HttpHeaders.LOCATION, - ServletUriComponentsBuilder.fromCurrentRequest().toUriString()); - return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders) - .body(convertToDto(newUserEvent)); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User does not exist"); - } catch (EventException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Event not recognized: only [" + Stream.of(UserEvent.UserEventType.values()) - .map(UserEvent.UserEventType::name).collect(Collectors.joining(", ")) + "] are possible"); - } } @@ -113,19 +97,17 @@ public ResponseEntity postUserEvent(@Valid @RequestBody UserEventDto userEven @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity deleteUserEvent(@PathVariable("id") Long id) { + public ResponseEntity deleteUserEvent(@PathVariable("id") Long id) { + UserEvent userEvent = userEventService.findById(id); + try { - Optional optUserEvent = userEventService.findById(id); - if (optUserEvent.isPresent()) { - UserEvent userEvent = optUserEvent.get(); - User user = userEvent.getUser(); - user.setUserEvents(user.getUserEvents().stream().filter(ue -> !ue.equals(userEvent)) - .collect(Collectors.toSet())); - userService.saveUser(user); - userEventService.deleteUserEvent(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("User event deleted"); - } else - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User event does not exist"); + User user = userEvent.getUser(); + user.setUserEvents(user.getUserEvents().stream().filter(ue -> !ue.equals(userEvent)) + .collect(Collectors.toSet())); + userService.saveUser(user); + userEventService.deleteUserEvent(id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("User event deleted"); + } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); @@ -138,8 +120,7 @@ private UserEventDto convertToDto(UserEvent userEvent) { return ueDto; } - private UserEvent convertToEntity(UserEventDto userEventDto) throws EventException { - UserEvent userEvent = modelMapper.map(userEventDto, UserEvent.class); - return userEvent; + private UserEvent convertToEntity(UserEventDto userEventDto) { + return modelMapper.map(userEventDto, UserEvent.class); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/SourceAccreditationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/SourceAccreditationService.java index 47c76772..5ae9150f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/SourceAccreditationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/SourceAccreditationService.java @@ -6,7 +6,6 @@ import org.springframework.data.domain.Pageable; import java.util.List; -import java.util.Optional; public interface SourceAccreditationService { @@ -14,7 +13,7 @@ public interface SourceAccreditationService { public Page findAll(Pageable pageable); - public Optional findById(Long id); + public SourceAccreditation findById(Long id); public SourceAccreditation saveSourceAccreditation(SourceAccreditation sourceAccreditation); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserEventService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserEventService.java index 61388842..8fd8898e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserEventService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserEventService.java @@ -8,7 +8,6 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; -import java.util.Optional; import java.util.Set; @Service @@ -16,7 +15,7 @@ public interface UserEventService { public Page findAll(Pageable pageable); - public Optional findById(Long id); + public UserEvent findById(Long id); public UserEvent saveUserEvent(UserEvent userEvent); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java index ed50b0d7..8e8804c6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java @@ -9,7 +9,6 @@ import org.springframework.stereotype.Service; import java.util.List; -import java.util.Optional; @Service public interface UserService { @@ -28,7 +27,7 @@ public interface UserService { * @param identifier * @return Optional user found */ - public Optional findByIdentifier(String identifier) ; + public User findByIdentifier(String identifier) ; /** * Update an existing user , or creates a new one diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java index 893c0aca..e41a94e4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/SourceAccreditationServiceImpl.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.user.service.impl; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; import fr.insee.survey.datacollectionmanagement.user.repository.SourceAccreditationRepository; import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; @@ -9,7 +10,6 @@ import org.springframework.stereotype.Service; import java.util.List; -import java.util.Optional; @Service @RequiredArgsConstructor @@ -27,8 +27,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findById(Long id) { - return sourceAccreditationRepository.findById(id); + public SourceAccreditation findById(Long id) { + return sourceAccreditationRepository.findById(id).orElseThrow(()-> new NotFoundException(String.format("SourceAccreditation %s not found", id))); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java index cc42675f..b5f323bd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserEventServiceImpl.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.user.domain.User; import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.repository.UserEventRepository; @@ -12,7 +13,6 @@ import org.springframework.stereotype.Service; import java.util.Date; -import java.util.Optional; import java.util.Set; @Service @@ -27,8 +27,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findById(Long id) { - return userEventRepository.findById(id); + public UserEvent findById(Long id) { + return userEventRepository.findById(id).orElseThrow(()-> new NotFoundException(String.format("QuestioningAccreditation %s not found", id))); } @Override diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index 7f95557e..88d9053b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -33,8 +33,8 @@ public Page findAll(Pageable pageable) { } @Override - public Optional findByIdentifier(String identifier) { - return userRepository.findByIdentifierIgnoreCase(identifier); + public User findByIdentifier(String identifier) { + return userRepository.findByIdentifierIgnoreCase(identifier).orElseThrow(()-> new NotFoundException(String.format("User %s not found", identifier))); } @Override @@ -58,9 +58,9 @@ public User createUser(User user, JsonNode payload) { } @Override - public User updateUser(User user, JsonNode payload) throws NotFoundException { + public User updateUser(User user, JsonNode payload) { - User existingUser = findByIdentifier(user.getIdentifier()).orElseThrow(() -> new NotFoundException("user not found")); + User existingUser = findByIdentifier(user.getIdentifier()); Set setUserEventsUser = existingUser.getUserEvents(); UserEvent userEventUpdate = userEventService.createUserEvent(user, UserEvent.UserEventType.UPDATE, diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java index 21c051bf..fd65ce3c 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java @@ -42,7 +42,7 @@ public class AddressControllerTest { @Test public void getAddressOk() throws Exception { String identifier = "CONT1"; - Contact contact = contactService.findByIdentifier(identifier).get(); + Contact contact = contactService.findByIdentifier(identifier); String json = createJsonAddress(contact); this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().isOk()).andExpect(content().json(json, false)); } @@ -58,7 +58,7 @@ public void getAddressContacttNotFound() throws Exception { public void putAddressCreateUpdate() throws Exception { String identifier = "CONT5"; - Contact contact = contactService.findByIdentifier(identifier).get(); + Contact contact = contactService.findByIdentifier(identifier); Address addressBefore = contact.getAddress(); // Before: delete existing address @@ -74,7 +74,7 @@ public void putAddressCreateUpdate() throws Exception { String jsonCreate = createJsonAddress(contact); this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonCreate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) .andExpect(status().isCreated()).andExpect(content().json(jsonCreate.toString(), false)); - Contact contactAfterCreate = contactService.findByIdentifier(identifier).get(); + Contact contactAfterCreate = contactService.findByIdentifier(identifier); assertEquals(contactAfterCreate.getAddress().getCityName(), addressCreated.getCityName()); assertEquals(contactAfterCreate.getAddress().getStreetName(), addressCreated.getStreetName()); assertEquals(contactAfterCreate.getAddress().getCountryName(), addressCreated.getCountryName()); @@ -85,7 +85,7 @@ public void putAddressCreateUpdate() throws Exception { String jsonUpdate = createJsonAddress(contact); this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonUpdate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) .andExpect(status().isOk()).andExpect(content().json(jsonUpdate.toString(), false)); - Contact contactAfterUpdate = contactService.findByIdentifier(identifier).get(); + Contact contactAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contactAfterUpdate.getAddress().getCityName(), addressUpdated.getCityName()); assertEquals(contactAfterUpdate.getAddress().getStreetName(), addressUpdated.getStreetName()); assertEquals(contactAfterUpdate.getAddress().getCountryName(), addressUpdated.getCountryName()); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index b4de3f64..2edbe23b 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.contact.repository.ContactRepository; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -48,7 +49,7 @@ public class ContactControllerTest { @Test public void getContactOk() throws Exception { String identifier = "CONT1"; - Contact contact = contactService.findByIdentifier(identifier).get(); + Contact contact = contactService.findByIdentifier(identifier); String json = createJson(contact); this.mockMvc.perform(get(Constants.API_CONTACTS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); @@ -83,7 +84,7 @@ public void putContactCreateUpdateDelete() throws Exception { put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); - Contact contactFound = contactService.findByIdentifier(identifier).get(); + Contact contactFound = contactService.findByIdentifier(identifier); assertEquals(contact.getLastName(), contactFound.getLastName()); assertEquals(contact.getFirstName(), contactFound.getFirstName()); assertEquals(contact.getEmail(), contactFound.getEmail()); @@ -98,7 +99,7 @@ public void putContactCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); - Contact contactFoundAfterUpdate = contactService.findByIdentifier(identifier).get(); + Contact contactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals("lastNameUpdate", contactFoundAfterUpdate.getLastName()); assertEquals(contact.getFirstName(), contactFoundAfterUpdate.getFirstName()); assertEquals(contact.getEmail(), contactFoundAfterUpdate.getEmail()); @@ -110,7 +111,7 @@ public void putContactCreateUpdateDelete() throws Exception { // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertFalse(contactService.findByIdentifier(identifier).isPresent()); + assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); assertTrue(contactEventService.findContactEventsByContact(contactFoundAfterUpdate).isEmpty()); // delete contact not found @@ -130,7 +131,7 @@ public void putContactAddressCreateUpdateDelete() throws Exception { put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); - Contact countactFound = contactService.findByIdentifier(identifier).get(); + Contact countactFound = contactService.findByIdentifier(identifier); assertEquals(contact.getAddress().getCityName(), countactFound.getAddress().getCityName()); // update contact - status ok @@ -140,13 +141,13 @@ public void putContactAddressCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); - Contact countactFoundAfterUpdate = contactService.findByIdentifier(identifier).get(); + Contact countactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contact.getAddress().getCityName(), countactFoundAfterUpdate.getAddress().getCityName()); // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertFalse(contactService.findByIdentifier(identifier).isPresent()); + assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index 6a283fd5..b419cebc 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -22,10 +22,9 @@ import java.util.Date; import java.util.HashSet; -import java.util.Optional; import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -222,9 +221,10 @@ private String createJson(Campaign campaign, String idSurvey) { @Rollback void getCampaignOk() throws Exception { String identifier = "SOURCE12023T01"; - Optional campaign = campaignService.findById(identifier); - assertTrue(campaign.isPresent()); - String json = createJson(campaign.get(), "SOURCE12023"); + + assertDoesNotThrow(()->campaignService.findById(identifier)); + Campaign campaign = campaignService.findById(identifier); + String json = createJson(campaign, "SOURCE12023"); this.mockMvc.perform(get(Constants.API_CAMPAIGNS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java index 5aa24872..a01cd7e7 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; @@ -16,8 +17,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -41,9 +40,9 @@ public class SourceControllerTest { @Test public void getSourceOk() throws Exception { String identifier = "SOURCE1"; - Optional source = sourceService.findById(identifier); - assertTrue(source.isPresent()); - String json = createJson(source.get()); + assertDoesNotThrow(() -> sourceService.findById(identifier)); + Source source = sourceService.findById(identifier); + String json = createJson(source); this.mockMvc.perform(get(Constants.API_SOURCES_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } @@ -74,31 +73,32 @@ public void putSourceCreateUpdateDelete() throws Exception { Source source = initSource(identifier); String jsonSource = createJson(source); mockMvc.perform( - put(Constants.API_SOURCES_ID, identifier).content(jsonSource) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SOURCES_ID, identifier).content(jsonSource) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSource.toString(), false)); - Optional sourceFound = sourceService.findById(identifier); - assertTrue(sourceFound.isPresent()); - assertEquals(source.getLongWording(), sourceFound.get().getLongWording()); - assertEquals(source.getShortWording(), sourceFound.get().getShortWording()); - assertEquals(source.getPeriodicity(), sourceFound.get().getPeriodicity()); + assertDoesNotThrow(() -> sourceService.findById(identifier)); + + Source sourceFound = sourceService.findById(identifier); + assertEquals(source.getLongWording(), sourceFound.getLongWording()); + assertEquals(source.getShortWording(), sourceFound.getShortWording()); + assertEquals(source.getPeriodicity(), sourceFound.getPeriodicity()); // update source - status ok source.setLongWording("Long wording update"); String jsonSourceUpdate = createJson(source); mockMvc.perform(put(Constants.API_SOURCES_ID, identifier).content(jsonSourceUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSourceUpdate.toString(), false)); - Optional sourceFoundAfterUpdate = sourceService.findById(identifier); - assertTrue(sourceFoundAfterUpdate.isPresent()); - assertEquals("Long wording update", sourceFoundAfterUpdate.get().getLongWording()); - assertEquals(source.getId(), sourceFoundAfterUpdate.get().getId()); + assertDoesNotThrow(() -> sourceService.findById(identifier)); + Source sourceFoundAfterUpdate = sourceService.findById(identifier); + assertEquals("Long wording update", sourceFoundAfterUpdate.getLongWording()); + assertEquals(source.getId(), sourceFoundAfterUpdate.getId()); // delete source mockMvc.perform(delete(Constants.API_SOURCES_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertFalse(sourceService.findById(identifier).isPresent()); + assertThrows(NotFoundException.class, ()->sourceService.findById(identifier)); // delete source not found mockMvc.perform(delete(Constants.API_SOURCES + "/" + identifier).contentType(MediaType.APPLICATION_JSON)) @@ -113,7 +113,7 @@ public void putSourcesErrorId() throws Exception { Source source = initSource(identifier); String jsonSource = createJson(source); mockMvc.perform(put(Constants.API_SOURCES + "/" + otherIdentifier).content(jsonSource) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()).andExpect(content().string("id and source id don't match")); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index 525d9684..b51896fc 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; @@ -15,8 +16,6 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import java.util.Optional; - import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -60,11 +59,12 @@ public void putSurveyCreateUpdateDelete() throws Exception { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurvey.toString(), false)); - Optional surveyFound = surveyService.findById(identifier); - assertTrue(surveyFound.isPresent()); - assertEquals(survey.getLongWording(), surveyFound.get().getLongWording()); - assertEquals(survey.getShortWording(), surveyFound.get().getShortWording()); - assertEquals(survey.getSampleSize(), surveyFound.get().getSampleSize()); + + assertDoesNotThrow(()->surveyService.findById(identifier)); + Survey surveyFound = surveyService.findById(identifier); + assertEquals(survey.getLongWording(), surveyFound.getLongWording()); + assertEquals(survey.getShortWording(), surveyFound.getShortWording()); + assertEquals(survey.getSampleSize(), surveyFound.getSampleSize()); // update survey - status ok survey.setLongWording("Long wording update"); @@ -72,15 +72,17 @@ public void putSurveyCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_SURVEYS_ID, identifier).content(jsonSurveyUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUpdate.toString(), false)); - Optional surveyFoundAfterUpdate = surveyService.findById(identifier); - assertTrue(surveyFoundAfterUpdate.isPresent()); - assertEquals("Long wording update", surveyFoundAfterUpdate.get().getLongWording()); - assertEquals(survey.getId(), surveyFoundAfterUpdate.get().getId()); + assertDoesNotThrow(()->surveyService.findById(identifier)); + Survey surveyFoundAfterUpdate = surveyService.findById(identifier); + + assertEquals("Long wording update", surveyFoundAfterUpdate.getLongWording()); + assertEquals(survey.getId(), surveyFoundAfterUpdate.getId()); // delete survey mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertFalse(surveyService.findById(identifier).isPresent()); + + assertThrows(NotFoundException.class,()->surveyService.findById(identifier)); // delete survey not found mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) @@ -124,9 +126,10 @@ private String createJson(Survey survey, String idSource) throws JSONException { @Test public void getSurveyOk() throws Exception { String identifier = "SOURCE12022"; - Optional survey = surveyService.findById(identifier); - assertTrue(survey.isPresent()); - String json = createJson(survey.get(), "SOURCE1"); + assertDoesNotThrow(()->surveyService.findById(identifier)); + Survey survey = surveyService.findById(identifier); + + String json = createJson(survey, "SOURCE1"); this.mockMvc.perform(get(Constants.API_SURVEYS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java index cefab50d..bb6d028e 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java @@ -97,7 +97,7 @@ public void postAccreditationCreateUpdate() throws Exception { .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonAccreditation.toString(), false)); - Questioning questioning = questioningService.findbyId((long) idQuestioning).get(); + Questioning questioning = questioningService.findbyId((long) idQuestioning); Set setAccreditationFound = questioning.getQuestioningAccreditations(); QuestioningAccreditation accreditationFound = setAccreditationFound.stream() .filter(acc -> acc.getIdContact().equals(idContact)) @@ -114,7 +114,7 @@ public void postAccreditationCreateUpdate() throws Exception { .andExpect(status().isOk()) .andExpect(content().json(jsonAccreditationUpdate.toString(), false)); - QuestioningAccreditation accreditationFoundAfterUpdate = questioningService.findbyId((long) idQuestioning).get() + QuestioningAccreditation accreditationFoundAfterUpdate = questioningService.findbyId((long) idQuestioning) .getQuestioningAccreditations().stream().filter(acc -> acc.getIdContact().equals(idContact)) .toList().get(0); assertEquals(true, accreditationFoundAfterUpdate.isMain()); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java index cecac765..5ce3c03c 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.questioning.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; @@ -16,8 +17,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -41,7 +41,7 @@ public class SurveyUnitControllerTest { @Test public void getSurveyUnitOk() throws Exception { String identifier = "100000000"; - SurveyUnit surveyUnit = surveyUnitService.findbyId(identifier).get(); + SurveyUnit surveyUnit = surveyUnitService.findbyId(identifier); String json = createJson(surveyUnit); this.mockMvc.perform(get(Constants.API_SURVEY_UNITS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); @@ -77,7 +77,7 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); - SurveyUnit surveyUnitFound = surveyUnitService.findbyId(identifier).get(); + SurveyUnit surveyUnitFound = surveyUnitService.findbyId(identifier); assertEquals(surveyUnit.getIdSu(), surveyUnitFound.getIdSu()); assertEquals(surveyUnit.getIdentificationCode(), surveyUnitFound.getIdentificationCode()); assertEquals(surveyUnit.getIdentificationName(), surveyUnitFound.getIdentificationName()); @@ -88,15 +88,15 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); - SurveyUnit surveyUnitFoundAfterUpdate = surveyUnitService.findbyId(identifier).get(); + SurveyUnit surveyUnitFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals("identificationNameUpdate", surveyUnitFoundAfterUpdate.getIdentificationName()); assertEquals(surveyUnit.getIdSu(), surveyUnitFoundAfterUpdate.getIdSu()); assertEquals(surveyUnit.getIdentificationName(), surveyUnitFoundAfterUpdate.getIdentificationName()); // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertFalse( - surveyUnitService.findbyId(identifier).isPresent()); + assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); + } @@ -112,7 +112,7 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); - SurveyUnit suFound = surveyUnitService.findbyId(identifier).get(); + SurveyUnit suFound = surveyUnitService.findbyId(identifier); assertEquals(surveyUnit.getSurveyUnitAddress().getCityName(), suFound.getSurveyUnitAddress().getCityName()); // update surveyUnit - status ok @@ -122,13 +122,13 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); - SurveyUnit countactFoundAfterUpdate = surveyUnitService.findbyId(identifier).get(); + SurveyUnit countactFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals(surveyUnit.getSurveyUnitAddress().getCityName(), countactFoundAfterUpdate.getSurveyUnitAddress().getCityName()); // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertFalse(surveyUnitService.findbyId(identifier).isPresent()); + assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java index d39f0a11..d2b9821a 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.user.controller.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.user.domain.User; import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent; import fr.insee.survey.datacollectionmanagement.user.domain.UserEvent.UserEventType; @@ -81,7 +82,8 @@ public void putUserCreateUpdateDelete() throws Exception { put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonUser.toString(), false)); - User userFound = userService.findByIdentifier(identifier).get(); + assertDoesNotThrow(() -> userService.findByIdentifier(identifier)); + User userFound = userService.findByIdentifier(identifier); assertEquals(user.getIdentifier(), userFound.getIdentifier()); assertEquals(user.getRole(), userFound.getRole()); @@ -91,7 +93,7 @@ public void putUserCreateUpdateDelete() throws Exception { mockMvc.perform(put(Constants.API_USERS_ID, identifier).content(jsonUserUpdate) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonUserUpdate.toString(), false)); - User userFoundAfterUpdate = userService.findByIdentifier(identifier).get(); + User userFoundAfterUpdate = userService.findByIdentifier(identifier); assertEquals(User.UserRoleType.ASSISTANCE, userFoundAfterUpdate.getRole()); List listUpdate = new ArrayList<>( userEventService.findUserEventsByUser(userFoundAfterUpdate)); @@ -101,7 +103,8 @@ public void putUserCreateUpdateDelete() throws Exception { // delete user mockMvc.perform(delete(Constants.API_USERS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertFalse(userService.findByIdentifier(identifier).isPresent()); + assertThrows(NotFoundException.class,() -> userService.findByIdentifier(identifier)); + assertTrue(userEventService.findUserEventsByUser(userFoundAfterUpdate).isEmpty()); // delete user not found From f18db93231d6e0a5846ba3c4d091c10b6f36c50e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:07:42 +0100 Subject: [PATCH 040/111] fix: exception handler to get body --- .../exception/ApiError.java | 8 +-- .../exception/ApiExceptionComponent.java | 8 +-- .../exception/ExceptionControllerAdvice.java | 59 +++++++++++-------- .../ImpossibleToDeleteException.java | 9 +++ .../exception/NotMatchException.java | 8 +++ 5 files changed, 58 insertions(+), 34 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/ImpossibleToDeleteException.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotMatchException.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java index dfff8572..475f937b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiError.java @@ -21,12 +21,12 @@ public class ApiError { private Date timestamp; /** - * @param status http status for this error - * @param path origin request path - * @param timestamp timestamp of the generated error + * @param status http status for this error + * @param path origin request path + * @param timestamp timestamp of the generated error * @param errorMessage error message */ - public ApiError (HttpStatus status, String path, Date timestamp, String errorMessage) { + public ApiError(HttpStatus status, String path, Date timestamp, String errorMessage) { if (errorMessage == null || errorMessage.isEmpty()) { errorMessage = status.getReasonPhrase(); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java index 1dab632a..0902b583 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ApiExceptionComponent.java @@ -24,16 +24,15 @@ public ApiExceptionComponent(ErrorAttributes errorAttributes) { } /** - * - * @param request origin request - * @param status status from exception + * @param request origin request + * @param status status from exception * @param errorMessage error message * @return error object used for JSON response */ public ApiError buildApiErrorObject(WebRequest request, HttpStatus status, String errorMessage) { String path = getPath(request); Date timestamp = getTimeStamp(request); - return new ApiError(status, path, timestamp, errorMessage); + return new ApiError(status, path, timestamp, errorMessage); } /** @@ -46,7 +45,6 @@ private Date getTimeStamp(WebRequest request) { } /** - * * @param request origin request * @return get path from origin request */ diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java index 07042ddc..f575dc57 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java @@ -27,9 +27,8 @@ @RequiredArgsConstructor public class ExceptionControllerAdvice { - private final ApiExceptionComponent errorComponent; - private static final String ERROR_OCCURRED_LABEL = "An error has occurred"; + private final ApiExceptionComponent errorComponent; /** * Global method to process the catched exception @@ -63,44 +62,41 @@ private ResponseEntity processException(Exception ex, HttpStatus statu @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) - @ResponseBody - public void noHandlerFoundException(NoHandlerFoundException e, WebRequest request) { + public ResponseEntity noHandlerFoundException(NoHandlerFoundException e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.NOT_FOUND, request); + return processException(e, HttpStatus.NOT_FOUND, request); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) - @ResponseBody - public void accessDeniedException(AccessDeniedException e, WebRequest request) { + public ResponseEntity accessDeniedException(AccessDeniedException e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.FORBIDDEN, request); + return processException(e, HttpStatus.FORBIDDEN, request); } @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) - @ResponseBody - public void handleMethodArgumentNotValid( + public ResponseEntity handleMethodArgumentNotValid( MethodArgumentNotValidException e, WebRequest request) { - log.error(e.getMessage(), e); - processException(e, HttpStatus.BAD_REQUEST, request, "Invalid parameters"); + + String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage(); + log.error(defaultMessage, e); + return processException(e, HttpStatus.BAD_REQUEST, request, defaultMessage); } @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ExceptionHandler(ConstraintViolationException.class) - @ResponseBody - public void handleConstraintViolation( + public ResponseEntity handleConstraintViolation( ConstraintViolationException e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.BAD_REQUEST, request, e.getMessage()); + return processException(e, HttpStatus.BAD_REQUEST, request, e.getMessage()); } @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) - @ResponseBody - public void handleHttpMessageNotReadableException( + public ResponseEntity handleHttpMessageNotReadableException( HttpMessageNotReadableException e, WebRequest request) { log.error(e.getMessage(), e); @@ -115,30 +111,43 @@ public void handleHttpMessageNotReadableException( String location = mappingException.getLocation() != null ? "[line: " + mappingException.getLocation().getLineNr() + ", column: " + mappingException.getLocation().getColumnNr() + "]" : ""; errorMessage = "Error when deserializing JSON. Check that your JSON properties are of the expected types " + location; } - processException(e, HttpStatus.BAD_REQUEST, request, errorMessage); + return processException(e, HttpStatus.BAD_REQUEST, request, errorMessage); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) - @ResponseBody - public void notFoundException(NotFoundException e, WebRequest request) { + public ResponseEntity notFoundException(NotFoundException e, WebRequest request) { + log.error(e.getMessage(), e); + return processException(e, HttpStatus.NOT_FOUND, request); + } + + @ExceptionHandler(NotMatchException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity notMatchException(NotMatchException e, WebRequest request) { + log.error(e.getMessage(), e); + return processException(e, HttpStatus.BAD_REQUEST, request); + } + + @ExceptionHandler(ImpossibleToDeleteException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity impossibleToDeleteException(ImpossibleToDeleteException e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.NOT_FOUND, request); + return processException(e, HttpStatus.BAD_REQUEST, request); } @ExceptionHandler(HttpClientErrorException.class) @ResponseBody - public void exceptions(HttpClientErrorException e, WebRequest request) { + public ResponseEntity exceptions(HttpClientErrorException e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.valueOf(e.getStatusCode().value()), request, ERROR_OCCURRED_LABEL); + return processException(e, HttpStatus.valueOf(e.getStatusCode().value()), request, ERROR_OCCURRED_LABEL); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody - public void exceptions(Exception e, WebRequest request) { + public ResponseEntity exceptions(Exception e, WebRequest request) { log.error(e.getMessage(), e); - processException(e, HttpStatus.INTERNAL_SERVER_ERROR, request, ERROR_OCCURRED_LABEL); + return processException(e, HttpStatus.INTERNAL_SERVER_ERROR, request, ERROR_OCCURRED_LABEL); } } \ No newline at end of file diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ImpossibleToDeleteException.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ImpossibleToDeleteException.java new file mode 100644 index 00000000..8d358b42 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ImpossibleToDeleteException.java @@ -0,0 +1,9 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +public class ImpossibleToDeleteException extends RuntimeException { + + public ImpossibleToDeleteException(String errorMessage) { + super(errorMessage); + } + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotMatchException.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotMatchException.java new file mode 100644 index 00000000..122900ca --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/NotMatchException.java @@ -0,0 +1,8 @@ +package fr.insee.survey.datacollectionmanagement.exception; + +public class NotMatchException extends RuntimeException { + public NotMatchException(String errorMessage) { + super(errorMessage); + } + +} From 6275ce1c1d9211d3f38d7be93d1822bbe8b8c71c Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:08:24 +0100 Subject: [PATCH 041/111] refactor: handle exceptions in controller --- .../controller/CampaignController.java | 5 ++- .../metadata/controller/OwnerController.java | 8 +++- .../controller/PartitioningController.java | 5 ++- .../metadata/controller/SourceController.java | 11 ++++-- .../controller/SupportController.java | 8 +++- .../metadata/controller/SurveyController.java | 20 +++++----- .../metadata/dto/OwnerDto.java | 2 + .../metadata/dto/PartitioningDto.java | 6 ++- .../metadata/dto/SourceCompleteDto.java | 2 + .../metadata/dto/SupportDto.java | 2 + .../metadata/dto/SurveyDto.java | 5 ++- .../query/controller/WebclientController.java | 19 +++++---- .../controller/SurveyUnitController.java | 30 +++++++------- .../questioning/dto/SurveyUnitDto.java | 4 +- .../user/controller/UserController.java | 6 +-- .../user/validation/UserRoleValid.java | 2 +- ...acollectionManagementApplicationTests.java | 6 +-- .../controller/AddressControllerTest.java | 32 +++++++-------- .../controller/ContactControllerTest.java | 39 ++++++++++--------- .../ContactEventControllerTest.java | 27 ++++++------- .../dataloader/DataloaderTest.java | 6 +-- .../controller/CampaignControllerTest.java | 9 +++-- .../controller/SourceControllerTest.java | 17 ++++---- .../controller/SurveyControllerTest.java | 33 ++++++++-------- .../CheckHabilitationControllerTest.java | 13 +------ .../query/controller/MoogControllerTest.java | 26 ++++++------- .../MyQuestioningsControllerTest.java | 6 +-- ...estionningAccreditationControllerTest.java | 28 ++++++------- .../QuestionningControllerTest.java | 13 +++---- .../QuestionningEventControllerTest.java | 16 ++++---- .../controller/SurveyUnitControllerTest.java | 38 +++++++++--------- .../controller/UserControllerTest.java | 27 ++++++------- .../controller/UserEventControllerTest.java | 16 ++++---- .../util/JsonUtil.java | 19 +++++++++ 34 files changed, 276 insertions(+), 230 deletions(-) create mode 100644 src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index d46d02d9..1b3072ac 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; @@ -122,8 +123,8 @@ public ResponseEntity getCampaign(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Valid CampaignDto campaignDto) { - if (StringUtils.isBlank(campaignDto.getId()) || !campaignDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idCampaign don't match"); + if ( !campaignDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idCampaign don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index ac8fb154..2910a649 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.dto.OwnerDto; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -19,6 +21,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -32,6 +35,7 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @RequiredArgsConstructor +@Validated public class OwnerController { private final ModelMapper modelmapper; @@ -73,9 +77,9 @@ public ResponseEntity getOwner(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = OwnerDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody OwnerDto ownerDto) { + public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @Valid OwnerDto ownerDto) { if (!ownerDto.getId().equals(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and owner id don't match"); + throw new NotMatchException("id and owner id don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index 7d1038fd..e09229a1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.dto.PartitioningDto; @@ -94,8 +95,8 @@ public ResponseEntity getPartitioning(@PathVariable("id") String id) { }) public ResponseEntity putPartitioning(@PathVariable("id") String id, @RequestBody PartitioningDto partitioningDto) { - if (StringUtils.isBlank(partitioningDto.getId()) || !partitioningDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idPartitioning don't match"); + if (!partitioningDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and owner id don't match"); } Partitioning partitioning; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index 8e2c1a40..cd2c2f49 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Owner; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; @@ -20,6 +21,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -30,6 +32,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -43,6 +46,7 @@ @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @Slf4j @RequiredArgsConstructor +@Validated public class SourceController { private final SourceService sourceService; @@ -93,9 +97,10 @@ public ResponseEntity getSource(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SourceCompleteDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody SourceCompleteDto SourceCompleteDto) { - if (StringUtils.isBlank(SourceCompleteDto.getId()) || !SourceCompleteDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and source id don't match"); + public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody @Valid SourceCompleteDto SourceCompleteDto) { + if ( !SourceCompleteDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and source id don't match"); + } Source source; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index 70286ff4..5fe9a754 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Support; import fr.insee.survey.datacollectionmanagement.metadata.dto.SupportDto; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; @@ -19,6 +21,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -32,6 +35,7 @@ + "|| @AuthorizeMethodDecider.isAdmin() ") @Tag(name = "3 - Metadata", description = "Enpoints to create, update, delete and find entities in metadata domain") @RequiredArgsConstructor +@Validated public class SupportController { private final ModelMapper modelmapper; @@ -73,9 +77,9 @@ public ResponseEntity getSupport(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SupportDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody SupportDto supportDto) { + public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody @Valid SupportDto supportDto) { if (!supportDto.getId().equals(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and support id don't match"); + throw new NotMatchException("id and support id don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 38a7c519..34820613 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; @@ -18,6 +19,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -79,14 +81,10 @@ public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity getSurvey(@PathVariable("id") String id) { + public ResponseEntity getSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(StringUtils.upperCase(id)); - try { - return ResponseEntity.ok().body(convertToDto(survey)); + return ResponseEntity.ok().body(convertToDto(survey)); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @@ -97,9 +95,11 @@ public ResponseEntity getSurvey(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody SurveyDto surveyDto) { - if (StringUtils.isBlank(surveyDto.getId()) || !surveyDto.getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idSurvey don't match"); + public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody @Valid SurveyDto surveyDto) { + if (!surveyDto.getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idSurvey don't match"); + + } Survey survey; HttpHeaders responseHeaders = new HttpHeaders(); @@ -131,7 +131,7 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody S @ApiResponse(responseCode = "400", description = "Bad Request") }) @Transactional - public ResponseEntity deleteSurvey(@PathVariable("id") String id) { + public ResponseEntity deleteSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(id); try { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java index cd4047b1..3c4ecc6f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/OwnerDto.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -7,6 +8,7 @@ @Setter public class OwnerDto { + @NotBlank private String id; private String label; private String ministry; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java index 750b7680..8a18e185 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PartitioningDto.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; -import java.util.Date; - +import jakarta.validation.constraints.NotBlank; import lombok.Data; +import java.util.Date; + @Data public class PartitioningDto { + @NotBlank private String id; private String campaignId; private String label; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java index b2419eb3..806a40e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SourceCompleteDto.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -8,6 +9,7 @@ @Setter public class SourceCompleteDto { + @NotBlank private String id; private String longWording; private String shortWording; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java index f0c110a7..8ae7c2e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SupportDto.java @@ -1,5 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @@ -7,6 +8,7 @@ @Setter public class SupportDto { + @NotBlank private String id; private String label; private String phoneNumber; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java index 6e8c7ed8..a408b27a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/SurveyDto.java @@ -1,15 +1,16 @@ package fr.insee.survey.datacollectionmanagement.metadata.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; @Getter @Setter public class SurveyDto { + @NotBlank private String id; - @NonNull + @NotBlank private String sourceId; private Integer year; private Integer sampleSize; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java index 3caa08ce..f5717290 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/WebclientController.java @@ -9,6 +9,7 @@ import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.*; import fr.insee.survey.datacollectionmanagement.metadata.dto.*; import fr.insee.survey.datacollectionmanagement.metadata.service.*; @@ -33,6 +34,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -42,6 +44,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -54,6 +57,7 @@ @Slf4j @Tag(name = "6 - Webclients", description = "Enpoints for webclients") @RequiredArgsConstructor +@Validated public class WebclientController { private final QuestioningService questioningService; @@ -118,12 +122,11 @@ public ResponseEntity putQuestioning(@RequestBody QuestioningWebclientDto que su = convertToEntity(questioningWebclientDto.getSurveyUnit()); // Create su if not exists or update - try{ + try { SurveyUnit optSuBase = surveyUnitService.findbyId(idSu); su.setQuestionings(optSuBase.getQuestionings()); - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.warn("survey unit {} does not exist - Creation of the survey unit", idSu); su.setQuestionings(new HashSet<>()); @@ -299,12 +302,12 @@ public ResponseEntity getMetadata(@PathVariable("id") String id) { }) @Transactional public ResponseEntity putMetadata(@PathVariable("id") String id, - @RequestBody MetadataDto metadataDto) { + @RequestBody @Valid MetadataDto metadataDto) { + if (!metadataDto.getPartitioningDto().getId().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idPartitioning don't match"); + } try { - if (StringUtils.isBlank(metadataDto.getPartitioningDto().getId()) - || !metadataDto.getPartitioningDto().getId().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idPartitioning don't match"); - } + MetadataDto metadataReturn = new MetadataDto(); HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index bf69bd01..ee24e5e0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.dto.SurveyUnitDto; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; @@ -11,6 +12,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -20,6 +22,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -33,6 +36,7 @@ @Tag(name = "2 - Questioning", description = "Enpoints to create, update, delete and find entities around the questionings") @Slf4j @RequiredArgsConstructor +@Validated public class SurveyUnitController { private final SurveyUnitService surveyUnitService; @@ -75,10 +79,9 @@ public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyUnitDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody SurveyUnitDto surveyUnitDto) { - if (StringUtils.isBlank(surveyUnitDto.getIdSu()) || !surveyUnitDto.getIdSu().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and idSu don't match"); - + public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody @Valid SurveyUnitDto surveyUnitDto) { + if (!surveyUnitDto.getIdSu().equalsIgnoreCase(id)) { + throw new NotMatchException("id and idSu don't match"); } SurveyUnit surveyUnit; @@ -92,12 +95,11 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo } catch (ParseException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse survey unit"); } - try{ + try { surveyUnitService.findbyId(surveyUnitDto.getIdSu()); responseStatus = HttpStatus.OK; - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.info("Creating survey with the id {}", surveyUnitDto.getIdSu()); responseStatus = HttpStatus.CREATED; } @@ -118,13 +120,13 @@ public ResponseEntity deleteSurveyUnit(@PathVariable("id") String id) { SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); try { - if (!surveyUnit.getQuestionings().isEmpty()) { - log.warn("Some questionings exist for the survey unit {}, the survey unit can't be deleted", id); - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body("Some questionings exist for this survey unit, the survey unit can't be deleted"); - } - surveyUnitService.deleteSurveyUnit(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey unit deleted"); + if (!surveyUnit.getQuestionings().isEmpty()) { + log.warn("Some questionings exist for the survey unit {}, the survey unit can't be deleted", id); + return ResponseEntity.status(HttpStatus.BAD_REQUEST) + .body("Some questionings exist for this survey unit, the survey unit can't be deleted"); + } + surveyUnitService.deleteSurveyUnit(id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey unit deleted"); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java index 7f1c0f93..805b2cc1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/dto/SurveyUnitDto.java @@ -1,12 +1,14 @@ package fr.insee.survey.datacollectionmanagement.questioning.dto; +import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Getter @Setter public class SurveyUnitDto { - + + @NotBlank private String idSu; private String identificationCode; private String identificationName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 0144176c..8eaf3e04 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -2,6 +2,7 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.user.domain.SourceAccreditation; @@ -18,7 +19,6 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; @@ -84,8 +84,8 @@ public ResponseEntity getUser(@PathVariable("id") String id) { @ApiResponse(responseCode = "400", description = "Bad request") }) public ResponseEntity putUser(@PathVariable("id") String id, @Valid @RequestBody UserDto userDto) { - if (StringUtils.isBlank(userDto.getIdentifier()) || !userDto.getIdentifier().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and user identifier don't match"); + if (!userDto.getIdentifier().equalsIgnoreCase(id)) { + throw new NotMatchException("id and user identifier don't match"); } User user; HttpHeaders responseHeaders = new HttpHeaders(); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java index b3a614e0..75f97f5f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/validation/UserRoleValid.java @@ -16,7 +16,7 @@ @Constraint(validatedBy = UserRoleValidator.class) public @interface UserRoleValid { //error message - String message() default "Role missing or not recognized. Only CREATE, UPDATE, DELETE"; + String message() default "Role missing or not recognized. Only RESPONSABLE, GESTIONNAIRE, ASSISTANCE are valid"; //represents group of constraints Class[] groups() default {}; diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java index a6e44c20..36d8de69 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/DatacollectionManagementApplicationTests.java @@ -8,8 +8,8 @@ @EnableJpaRepositories class DatacollectionManagementApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java index fd65ce3c..eaf83504 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/AddressControllerTest.java @@ -28,34 +28,34 @@ @SpringBootTest @ActiveProfiles("test") @ContextConfiguration -public class AddressControllerTest { +class AddressControllerTest { @Autowired private MockMvc mockMvc; @Autowired private ContactService contactService; - + @Autowired private AddressService addressService; @Test - public void getAddressOk() throws Exception { + void getAddressOk() throws Exception { String identifier = "CONT1"; Contact contact = contactService.findByIdentifier(identifier); String json = createJsonAddress(contact); - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().isOk()).andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().isOk()).andExpect(content().json(json, false)); } @Test - public void getAddressContacttNotFound() throws Exception { + void getAddressContacttNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); } @Test - public void putAddressCreateUpdate() throws Exception { + void putAddressCreateUpdate() throws Exception { String identifier = "CONT5"; Contact contact = contactService.findByIdentifier(identifier); @@ -65,31 +65,31 @@ public void putAddressCreateUpdate() throws Exception { contact.setAddress(null); contact = contactService.saveContact(contact); addressService.deleteAddressById(addressBefore.getId()); - - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS , identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); + + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_ADDRESS, identifier)).andDo(print()).andExpect(status().is(HttpStatus.NOT_FOUND.value())); // Create address - status created Address addressCreated = initAddressMock(identifier); contact.setAddress(addressCreated); String jsonCreate = createJsonAddress(contact); - this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonCreate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) - .andExpect(status().isCreated()).andExpect(content().json(jsonCreate.toString(), false)); + this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS, identifier).content(jsonCreate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) + .andExpect(status().isCreated()).andExpect(content().json(jsonCreate.toString(), false)); Contact contactAfterCreate = contactService.findByIdentifier(identifier); assertEquals(contactAfterCreate.getAddress().getCityName(), addressCreated.getCityName()); assertEquals(contactAfterCreate.getAddress().getStreetName(), addressCreated.getStreetName()); assertEquals(contactAfterCreate.getAddress().getCountryName(), addressCreated.getCountryName()); - + // Update address - status OK Address addressUpdated = initAddressMock("UPDATE"); contact.setAddress(addressUpdated); String jsonUpdate = createJsonAddress(contact); - this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS , identifier).content(jsonUpdate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) - .andExpect(status().isOk()).andExpect(content().json(jsonUpdate.toString(), false)); + this.mockMvc.perform(put(Constants.API_CONTACTS_ID_ADDRESS, identifier).content(jsonUpdate).contentType(MediaType.APPLICATION_JSON)).andDo(print()) + .andExpect(status().isOk()).andExpect(content().json(jsonUpdate.toString(), false)); Contact contactAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contactAfterUpdate.getAddress().getCityName(), addressUpdated.getCityName()); assertEquals(contactAfterUpdate.getAddress().getStreetName(), addressUpdated.getStreetName()); assertEquals(contactAfterUpdate.getAddress().getCountryName(), addressUpdated.getCountryName()); - + // back to before contact.setAddress(addressBefore); addressService.saveAddress(addressBefore); @@ -97,7 +97,7 @@ public void putAddressCreateUpdate() throws Exception { assertEquals(contact.getAddress().getCityName(), addressBefore.getCityName()); assertEquals(contact.getAddress().getStreetName(), addressBefore.getStreetName()); assertEquals(contact.getAddress().getCountryName(), addressBefore.getCountryName()); - + } private Address initAddressMock(String identifier) { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index 2edbe23b..14d2907d 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -9,6 +9,7 @@ import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class ContactControllerTest { +class ContactControllerTest { @Autowired private MockMvc mockMvc; @@ -47,7 +48,7 @@ public class ContactControllerTest { private ContactRepository contactRepository; @Test - public void getContactOk() throws Exception { + void getContactOk() throws Exception { String identifier = "CONT1"; Contact contact = contactService.findByIdentifier(identifier); String json = createJson(contact); @@ -56,7 +57,7 @@ public void getContactOk() throws Exception { } @Test - public void getContactNotFound() throws Exception { + void getContactNotFound() throws Exception { String identifier = "CONT500"; this.mockMvc.perform(get(Constants.API_CONTACTS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -64,7 +65,7 @@ public void getContactNotFound() throws Exception { } @Test - public void getContactsOk() throws Exception { + void getContactsOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", contactRepository.count()); jo.put("numberOfElements", contactRepository.count()); @@ -74,14 +75,14 @@ public void getContactsOk() throws Exception { } @Test - public void putContactCreateUpdateDelete() throws Exception { + void putContactCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create contact - status created Contact contact = initContact(identifier); String jsonContact = createJson(contact); mockMvc.perform( - put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); Contact contactFound = contactService.findByIdentifier(identifier); @@ -90,14 +91,14 @@ public void putContactCreateUpdateDelete() throws Exception { assertEquals(contact.getEmail(), contactFound.getEmail()); List list = new ArrayList<>(contactEventService.findContactEventsByContact(contactFound)); // List list = new ArrayList<>(contactFound.getContactEvents()); - assertEquals(list.size(), 1); - assertEquals(list.get(0).getType(), ContactEventType.create); + assertEquals(1, list.size()); + assertEquals(ContactEventType.create, list.get(0).getType()); // update contact - status ok contact.setLastName("lastNameUpdate"); String jsonContactUpdate = createJson(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); Contact contactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals("lastNameUpdate", contactFoundAfterUpdate.getLastName()); @@ -105,13 +106,13 @@ public void putContactCreateUpdateDelete() throws Exception { assertEquals(contact.getEmail(), contactFoundAfterUpdate.getEmail()); List listUpdate = new ArrayList<>( contactEventService.findContactEventsByContact(contactFoundAfterUpdate)); - assertEquals(listUpdate.size(), 2); - assertEquals(listUpdate.get(1).getType(), ContactEventType.update); + assertEquals(2, listUpdate.size()); + assertEquals(ContactEventType.update, listUpdate.get(1).getType()); // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> contactService.findByIdentifier(identifier)); assertTrue(contactEventService.findContactEventsByContact(contactFoundAfterUpdate).isEmpty()); // delete contact not found @@ -121,14 +122,14 @@ public void putContactCreateUpdateDelete() throws Exception { } @Test - public void putContactAddressCreateUpdateDelete() throws Exception { + void putContactAddressCreateUpdateDelete() throws Exception { String identifier = "TESTADDRESS"; // create contact - status created Contact contact = initContactAddress(identifier); String jsonContact = createJsonContactAddress(contact); mockMvc.perform( - put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_CONTACTS_ID, identifier).content(jsonContact).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonContact.toString(), false)); Contact countactFound = contactService.findByIdentifier(identifier); @@ -139,7 +140,7 @@ public void putContactAddressCreateUpdateDelete() throws Exception { contact.getAddress().setCityName(newCityName); String jsonContactUpdate = createJsonContactAddress(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, identifier).content(jsonContactUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonContactUpdate.toString(), false)); Contact countactFoundAfterUpdate = contactService.findByIdentifier(identifier); assertEquals(contact.getAddress().getCityName(), countactFoundAfterUpdate.getAddress().getCityName()); @@ -147,20 +148,20 @@ public void putContactAddressCreateUpdateDelete() throws Exception { // delete contact mockMvc.perform(delete(Constants.API_CONTACTS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->contactService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> contactService.findByIdentifier(identifier)); } @Test - public void putContactsErrorId() throws Exception { + void putContactsErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Contact contact = initContact(identifier); String jsonContact = createJson(contact); mockMvc.perform(put(Constants.API_CONTACTS_ID, otherIdentifier).content(jsonContact) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and contact identifier don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and contact identifier don't match"), false)); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java index 91abaef8..db885e53 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactEventControllerTest.java @@ -1,10 +1,6 @@ package fr.insee.survey.datacollectionmanagement.contacts.controller; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - +import fr.insee.survey.datacollectionmanagement.constants.Constants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -16,34 +12,39 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class ContactEventControllerTest { +class ContactEventControllerTest { @Autowired private MockMvc mockMvc; @Test - public void getContactEventOk() throws Exception { + void getContactEventOk() throws Exception { String identifier = "CONT1"; String json = createJsonContactEvent(identifier); - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS,identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); } @Test - public void getContactEventNotFound() throws Exception { + void getContactEventNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS,identifier)).andDo(print()) - .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_CONTACTS_ID_CONTACTEVENTS, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } private String createJsonContactEvent(String identifier) throws JSONException { + //region Description JSONObject jo = new JSONObject(); + //endregion JSONObject joPayload = new JSONObject(); joPayload.put("contact_identifier", identifier); jo.put("payload", joPayload); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java index 65cd570f..f1ac2b45 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java @@ -107,7 +107,7 @@ private void initUser() { User user = new User(); user.setIdentifier("USER1"); user.setRole(User.UserRoleType.ASSISTANCE); - userService.createUser(user,null); + userService.createUser(user, null); } private void initOrder() { @@ -292,8 +292,8 @@ private void initMetadata() throws ParseException { sourceRepository.save(source); log.info("Source created : " + source.toString()); ownerInsee.setSources(setSourcesInsee); - ownerRepository.saveAll(Arrays.asList(new Owner[] { - ownerInsee })); + ownerRepository.saveAll(Arrays.asList(new Owner[]{ + ownerInsee})); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java index b419cebc..7365f051 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import net.minidev.json.JSONObject; import org.assertj.core.util.DateUtil; import org.junit.jupiter.api.Test; @@ -60,9 +61,10 @@ void putCampaignsErrorId() throws Exception { String otherIdentifier = "WRONG"; Campaign campaign = initOpenedCampaign(identifier); String jsonCampaign = createJson(campaign, "SOURCE12023"); + String jsonError = JsonUtil.createJsonErrorBadRequest("id and idCampaign don't match"); mockMvc.perform(put(Constants.API_CAMPAIGNS_ID, otherIdentifier).content(jsonCampaign) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and idCampaign don't match")); + .andExpect(status().isBadRequest()).andExpect(content().json(jsonError, false)); } @@ -206,7 +208,7 @@ private String createJsonPart(Partitioning part) { return jo.toString(); } - private String createJson(Campaign campaign, String idSurvey) { + private String createJson(Campaign campaign, String idSurvey) { JSONObject jo = new JSONObject(); jo.put("id", campaign.getId()); jo.put("year", campaign.getYear()); @@ -222,11 +224,12 @@ private String createJson(Campaign campaign, String idSurvey) { void getCampaignOk() throws Exception { String identifier = "SOURCE12023T01"; - assertDoesNotThrow(()->campaignService.findById(identifier)); + assertDoesNotThrow(() -> campaignService.findById(identifier)); Campaign campaign = campaignService.findById(identifier); String json = createJson(campaign, "SOURCE12023"); this.mockMvc.perform(get(Constants.API_CAMPAIGNS_ID, identifier)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } + } \ No newline at end of file diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java index a01cd7e7..a779bb33 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.repository.SourceRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -26,7 +27,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SourceControllerTest { +class SourceControllerTest { @Autowired MockMvc mockMvc; @@ -38,7 +39,7 @@ public class SourceControllerTest { SourceRepository sourceRepository; @Test - public void getSourceOk() throws Exception { + void getSourceOk() throws Exception { String identifier = "SOURCE1"; assertDoesNotThrow(() -> sourceService.findById(identifier)); Source source = sourceService.findById(identifier); @@ -48,7 +49,7 @@ public void getSourceOk() throws Exception { } @Test - public void getSourceNotFound() throws Exception { + void getSourceNotFound() throws Exception { String identifier = "SOURCENOTFOUND"; this.mockMvc.perform(get(Constants.API_SOURCES_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -56,7 +57,7 @@ public void getSourceNotFound() throws Exception { } @Test - public void getSourcesOk() throws Exception { + void getSourcesOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", sourceRepository.count()); jo.put("numberOfElements", sourceRepository.count()); @@ -66,7 +67,7 @@ public void getSourcesOk() throws Exception { } @Test - public void putSourceCreateUpdateDelete() throws Exception { + void putSourceCreateUpdateDelete() throws Exception { String identifier = "SOURCEPUT"; // create source - status created @@ -98,7 +99,7 @@ public void putSourceCreateUpdateDelete() throws Exception { // delete source mockMvc.perform(delete(Constants.API_SOURCES_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class, ()->sourceService.findById(identifier)); + assertThrows(NotFoundException.class, () -> sourceService.findById(identifier)); // delete source not found mockMvc.perform(delete(Constants.API_SOURCES + "/" + identifier).contentType(MediaType.APPLICATION_JSON)) @@ -107,14 +108,14 @@ public void putSourceCreateUpdateDelete() throws Exception { } @Test - public void putSourcesErrorId() throws Exception { + void putSourcesErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Source source = initSource(identifier); String jsonSource = createJson(source); mockMvc.perform(put(Constants.API_SOURCES + "/" + otherIdentifier).content(jsonSource) .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and source id don't match")); + .andExpect(status().isBadRequest()).andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and source id don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index b51896fc..2f941ebe 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -5,6 +5,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.repository.SurveyRepository; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -25,7 +26,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SurveyControllerTest { +class SurveyControllerTest { @Autowired private MockMvc mockMvc; @@ -37,9 +38,8 @@ public class SurveyControllerTest { private SurveyRepository surveyRepository; - @Test - public void getSurveyNotFound() throws Exception { + void getSurveyNotFound() throws Exception { String identifier = "SURVEYNOTFOUND"; this.mockMvc.perform(get(Constants.API_SURVEYS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -48,19 +48,19 @@ public void getSurveyNotFound() throws Exception { @Test - public void putSurveyCreateUpdateDelete() throws Exception { + void putSurveyCreateUpdateDelete() throws Exception { String identifier = "SURVEYPUT"; // create survey - status created Survey survey = initSurvey(identifier); String jsonSurvey = createJson(survey, "SOURCE1"); mockMvc.perform( - put(Constants.API_SURVEYS_ID, identifier).content(jsonSurvey) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEYS_ID, identifier).content(jsonSurvey) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurvey.toString(), false)); - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey surveyFound = surveyService.findById(identifier); assertEquals(survey.getLongWording(), surveyFound.getLongWording()); assertEquals(survey.getShortWording(), surveyFound.getShortWording()); @@ -68,11 +68,11 @@ public void putSurveyCreateUpdateDelete() throws Exception { // update survey - status ok survey.setLongWording("Long wording update"); - String jsonSurveyUpdate = createJson(survey,"SOURCE1"); + String jsonSurveyUpdate = createJson(survey, "SOURCE1"); mockMvc.perform(put(Constants.API_SURVEYS_ID, identifier).content(jsonSurveyUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUpdate.toString(), false)); - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey surveyFoundAfterUpdate = surveyService.findById(identifier); assertEquals("Long wording update", surveyFoundAfterUpdate.getLongWording()); @@ -82,7 +82,7 @@ public void putSurveyCreateUpdateDelete() throws Exception { mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class,()->surveyService.findById(identifier)); + assertThrows(NotFoundException.class, () -> surveyService.findById(identifier)); // delete survey not found mockMvc.perform(delete(Constants.API_SURVEYS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) @@ -91,14 +91,15 @@ public void putSurveyCreateUpdateDelete() throws Exception { } @Test - public void putSurveysErrorId() throws Exception { + void putSurveysErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; Survey survey = initSurvey(identifier); String jsonSurvey = createJson(survey, "SOURCE1"); mockMvc.perform(put(Constants.API_SURVEYS_ID, otherIdentifier).content(jsonSurvey) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()).andExpect(content().string("id and idSurvey don't match")); + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and idSurvey don't match"))); + } @@ -124,9 +125,9 @@ private String createJson(Survey survey, String idSource) throws JSONException { } @Test - public void getSurveyOk() throws Exception { + void getSurveyOk() throws Exception { String identifier = "SOURCE12022"; - assertDoesNotThrow(()->surveyService.findById(identifier)); + assertDoesNotThrow(() -> surveyService.findById(identifier)); Survey survey = surveyService.findById(identifier); String json = createJson(survey, "SOURCE1"); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java index 9a41cf22..4c70a115 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/CheckHabilitationControllerTest.java @@ -1,24 +1,13 @@ package fr.insee.survey.datacollectionmanagement.query.controller; -import static org.hamcrest.Matchers.containsString; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.jupiter.api.Test; +import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import fr.insee.survey.datacollectionmanagement.constants.Constants; -import fr.insee.survey.datacollectionmanagement.query.service.CheckHabilitationService; - @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java index 4975f7c9..f0183d35 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java @@ -17,7 +17,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class MoogControllerTest { +class MoogControllerTest { @Autowired private MockMvc mockMvc; @@ -26,25 +26,25 @@ public class MoogControllerTest { private MoogService moogService; @Test - public void getMoogReadOnlyUrl() throws Exception { - String idCampaign= "SOURCE12023T01"; - String surveyUnitId= "100000000"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isOk()) + void getMoogReadOnlyUrl() throws Exception { + String idCampaign = "SOURCE12023T01"; + String surveyUnitId = "100000000"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isOk()) .andExpect(content().string("http://localhost:8081/readonly/questionnaire/m0/unite-enquetee/100000000")); } @Test - public void getMoogReadOnlyUrlCampaignNotFound() throws Exception { - String idCampaign= "CAMPAIGN"; - String surveyUnitId= "100000000"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); + void getMoogReadOnlyUrlCampaignNotFound() throws Exception { + String idCampaign = "CAMPAIGN"; + String surveyUnitId = "100000000"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } @Test - public void getMoogReadOnlyUrlQuestioningNotFound() throws Exception { - String idCampaign= "SOURCE12023T01"; - String surveyUnitId= "SU"; - this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign,surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); + void getMoogReadOnlyUrlQuestioningNotFound() throws Exception { + String idCampaign = "SOURCE12023T01"; + String surveyUnitId = "SU"; + this.mockMvc.perform(get(Constants.MOOG_API_READONLY_URL, idCampaign, surveyUnitId)).andDo(print()).andExpect(status().isNotFound()); } } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java index b90d8ac4..2945d8fd 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MyQuestioningsControllerTest.java @@ -23,7 +23,7 @@ @SpringBootTest @ActiveProfiles("test") @ContextConfiguration -public class MyQuestioningsControllerTest { +class MyQuestioningsControllerTest { @Autowired private MockMvc mockMvc; @@ -32,7 +32,7 @@ public class MyQuestioningsControllerTest { private CheckHabilitationService checkAccreditationService; // @Test -// public void myQuestionings() throws Exception { +// void myQuestionings() throws Exception { // String identifier = "CONT2"; // // MvcResult result = this.mockMvc.perform(get(Constants.API_MY_QUESTIONINGS_ID, identifier)).andDo(print()) @@ -52,7 +52,7 @@ public class MyQuestioningsControllerTest { // } @Test - public void myQuestioningsContactNotExist() throws Exception { + void myQuestioningsContactNotExist() throws Exception { String identifier = "CONT500"; MvcResult result = this.mockMvc.perform(get(Constants.API_MY_QUESTIONINGS_ID, identifier)).andDo(print()) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java index bb6d028e..59da0593 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningAccreditationControllerTest.java @@ -29,7 +29,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningAccreditationControllerTest { +class QuestionningAccreditationControllerTest { @Autowired private MockMvc mockMvc; @@ -38,7 +38,7 @@ public class QuestionningAccreditationControllerTest { private QuestioningService questioningService; @Test - public void getQuestioningAccreditationOk() throws Exception { + void getQuestioningAccreditationOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long identifier = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJsonQuestioningAcreditation(identifier); @@ -47,7 +47,7 @@ public void getQuestioningAccreditationOk() throws Exception { } @Test - public void getQuestioningAccreditationNotFound() throws Exception { + void getQuestioningAccreditationNotFound() throws Exception { String identifier = "300"; this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -55,7 +55,7 @@ public void getQuestioningAccreditationNotFound() throws Exception { } @Test - public void postAccreditationQuestioningNotFound() throws Exception { + void postAccreditationQuestioningNotFound() throws Exception { int idQuestioning = 10000; String idContact = "CONT1"; @@ -63,13 +63,13 @@ public void postAccreditationQuestioningNotFound() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test - public void postAccreditationContactNotFound() throws Exception { + void postAccreditationContactNotFound() throws Exception { Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); Long idQuestioning = q.getId(); String idContact = "CONT7500"; @@ -78,13 +78,13 @@ public void postAccreditationContactNotFound() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test - public void postAccreditationCreateUpdate() throws Exception { + void postAccreditationCreateUpdate() throws Exception { Questioning q = questioningService.findByIdPartitioning("SOURCE12023T1000").stream().findFirst().get(); Long idQuestioning = q.getId(); String idContact = "CONT5"; @@ -93,8 +93,8 @@ public void postAccreditationCreateUpdate() throws Exception { QuestioningAccreditation accreditation = initAccreditation(idContact); String jsonAccreditation = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditation).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonAccreditation.toString(), false)); Questioning questioning = questioningService.findbyId((long) idQuestioning); @@ -109,8 +109,8 @@ public void postAccreditationCreateUpdate() throws Exception { accreditation.setMain(true); String jsonAccreditationUpdate = createJson(accreditation); mockMvc.perform( - post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) - .content(jsonAccreditationUpdate).contentType(MediaType.APPLICATION_JSON)) + post(Constants.API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS, idQuestioning) + .content(jsonAccreditationUpdate).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json(jsonAccreditationUpdate.toString(), false)); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java index 56a4816c..380ab2f5 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningControllerTest.java @@ -22,16 +22,15 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningControllerTest { - - @Autowired - private MockMvc mockMvc; +class QuestionningControllerTest { @Autowired QuestioningService questioningService; + @Autowired + private MockMvc mockMvc; @Test - public void getQuestioningOk() throws Exception { + void getQuestioningOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJson(id).toString(); @@ -40,7 +39,7 @@ public void getQuestioningOk() throws Exception { } @Test - public void getQuestioningNotFound() throws Exception { + void getQuestioningNotFound() throws Exception { String id = "300"; this.mockMvc.perform(get(Constants.API_QUESTIONINGS_ID, id)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -48,7 +47,7 @@ public void getQuestioningNotFound() throws Exception { } @Test - public void getQuestioningsBySurveyUnit() throws Exception { + void getQuestioningsBySurveyUnit() throws Exception { String idSu = "100000000"; String json = createJsonQuestionings(idSu); this.mockMvc.perform(get(Constants.API_SURVEY_UNITS_ID_QUESTIONINGS, idSu)).andDo(print()) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java index 23efccdb..5433d7e8 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/QuestionningEventControllerTest.java @@ -22,28 +22,26 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class QuestionningEventControllerTest { - - @Autowired - private MockMvc mockMvc; +class QuestionningEventControllerTest { @Autowired QuestioningService questioningService; - + @Autowired + private MockMvc mockMvc; @Test - public void getQuestioningEventOk() throws Exception { + void getQuestioningEventOk() throws Exception { Questioning questioning = questioningService.findBySurveyUnitIdSu("100000001").stream().findFirst().get(); Long id = questioning.getQuestioningAccreditations().stream().findFirst().get().getId(); String json = createJsonQuestioningEvent(id); - this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,id)).andDo(print()).andExpect(status().isOk()) + this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS, id)).andDo(print()).andExpect(status().isOk()) .andExpect(content().json(json, false)); } @Test - public void getQuestioningEventNotFound() throws Exception { + void getQuestioningEventNotFound() throws Exception { String identifier = "300"; - this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS,identifier)).andDo(print()) + this.mockMvc.perform(get(Constants.API_QUESTIONING_ID_QUESTIONING_EVENTS, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java index 5ce3c03c..b89e1dd1 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitControllerTest.java @@ -6,6 +6,7 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnitAddress; import fr.insee.survey.datacollectionmanagement.questioning.repository.SurveyUnitRepository; import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -17,7 +18,8 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @@ -27,7 +29,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class SurveyUnitControllerTest { +class SurveyUnitControllerTest { @Autowired private MockMvc mockMvc; @@ -39,7 +41,7 @@ public class SurveyUnitControllerTest { private SurveyUnitRepository surveyUnitRepository; @Test - public void getSurveyUnitOk() throws Exception { + void getSurveyUnitOk() throws Exception { String identifier = "100000000"; SurveyUnit surveyUnit = surveyUnitService.findbyId(identifier); String json = createJson(surveyUnit); @@ -48,7 +50,7 @@ public void getSurveyUnitOk() throws Exception { } @Test - public void getSurveyUnitNotFound() throws Exception { + void getSurveyUnitNotFound() throws Exception { String identifier = "900000000"; this.mockMvc.perform(get(Constants.API_SURVEY_UNITS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -56,7 +58,7 @@ public void getSurveyUnitNotFound() throws Exception { } @Test - public void getSurveyUnitsOk() throws Exception { + void getSurveyUnitsOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", surveyUnitRepository.count()); jo.put("numberOfElements", surveyUnitRepository.count()); @@ -66,15 +68,15 @@ public void getSurveyUnitsOk() throws Exception { } @Test - public void putSurveyUnitCreateUpdateDelete() throws Exception { + void putSurveyUnitCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create surveyUnit - status created SurveyUnit surveyUnit = initSurveyUnit(identifier); String jsonSurveyUnit = createJson(surveyUnit); mockMvc.perform( - put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); SurveyUnit surveyUnitFound = surveyUnitService.findbyId(identifier); @@ -86,7 +88,7 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { surveyUnit.setIdentificationName("identificationNameUpdate"); String jsonSurveyUnitUpdate = createJson(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); SurveyUnit surveyUnitFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals("identificationNameUpdate", surveyUnitFoundAfterUpdate.getIdentificationName()); @@ -95,21 +97,21 @@ public void putSurveyUnitCreateUpdateDelete() throws Exception { // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); + assertThrows(NotFoundException.class, () -> surveyUnitService.findbyId(identifier)); } @Test - public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { + void putSurveyUnitAddressCreateUpdateDelete() throws Exception { String identifier = "TESTADDRESS"; // create surveyUnit - status created SurveyUnit surveyUnit = initSurveyUnitAddress(identifier); String jsonSurveyUnit = createJsonSurveyUnitAddress(surveyUnit); mockMvc.perform( - put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnit) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonSurveyUnit.toString(), false)); SurveyUnit suFound = surveyUnitService.findbyId(identifier); @@ -120,7 +122,7 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { surveyUnit.getSurveyUnitAddress().setCityName(newCityName); String jsonSurveyUnitUpdate = createJsonSurveyUnitAddress(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, identifier).content(jsonSurveyUnitUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonSurveyUnitUpdate.toString(), false)); SurveyUnit countactFoundAfterUpdate = surveyUnitService.findbyId(identifier); assertEquals(surveyUnit.getSurveyUnitAddress().getCityName(), @@ -128,20 +130,20 @@ public void putSurveyUnitAddressCreateUpdateDelete() throws Exception { // delete surveyUnit surveyUnitService.deleteSurveyUnit(identifier); - assertThrows(NotFoundException.class,()->surveyUnitService.findbyId(identifier)); + assertThrows(NotFoundException.class, () -> surveyUnitService.findbyId(identifier)); } @Test - public void putSurveyUnitsErrorId() throws Exception { + void putSurveyUnitsErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; SurveyUnit surveyUnit = initSurveyUnit(identifier); String jsonSurveyUnit = createJson(surveyUnit); mockMvc.perform(put(Constants.API_SURVEY_UNITS_ID, otherIdentifier).content(jsonSurveyUnit) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and idSu don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and idSu don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java index d2b9821a..be744971 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.user.repository.UserRepository; import fr.insee.survey.datacollectionmanagement.user.service.UserEventService; import fr.insee.survey.datacollectionmanagement.user.service.UserService; +import fr.insee.survey.datacollectionmanagement.util.JsonUtil; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; @@ -31,7 +32,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class UserControllerTest { +class UserControllerTest { @Autowired private MockMvc mockMvc; @@ -46,7 +47,7 @@ public class UserControllerTest { private UserRepository userRepository; @Test - public void getUserNotFound() throws Exception { + void getUserNotFound() throws Exception { String identifier = "CONT500"; this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.NOT_FOUND.value())); @@ -54,7 +55,7 @@ public void getUserNotFound() throws Exception { } @Test - public void getUserOk() throws Exception { + void getUserOk() throws Exception { String identifier = "USER1"; this.mockMvc.perform(get(Constants.API_USERS_ID, identifier)).andDo(print()) .andExpect(status().is(HttpStatus.OK.value())); @@ -62,7 +63,7 @@ public void getUserOk() throws Exception { } @Test - public void getUsersOk() throws Exception { + void getUsersOk() throws Exception { JSONObject jo = new JSONObject(); jo.put("totalElements", userRepository.count()); jo.put("numberOfElements", userRepository.count()); @@ -72,14 +73,14 @@ public void getUsersOk() throws Exception { } @Test - public void putUserCreateUpdateDelete() throws Exception { + void putUserCreateUpdateDelete() throws Exception { String identifier = "TESTPUT"; // create user - status created User user = initGestionnaire(identifier); String jsonUser = createJson(user); mockMvc.perform( - put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) + put(Constants.API_USERS_ID, identifier).content(jsonUser).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()) .andExpect(content().json(jsonUser.toString(), false)); assertDoesNotThrow(() -> userService.findByIdentifier(identifier)); @@ -91,19 +92,19 @@ public void putUserCreateUpdateDelete() throws Exception { user.setRole(User.UserRoleType.ASSISTANCE); String jsonUserUpdate = createJson(user); mockMvc.perform(put(Constants.API_USERS_ID, identifier).content(jsonUserUpdate) - .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) + .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content().json(jsonUserUpdate.toString(), false)); User userFoundAfterUpdate = userService.findByIdentifier(identifier); assertEquals(User.UserRoleType.ASSISTANCE, userFoundAfterUpdate.getRole()); List listUpdate = new ArrayList<>( userEventService.findUserEventsByUser(userFoundAfterUpdate)); - assertEquals(listUpdate.size(), 2); - assertEquals(listUpdate.get(1).getType(), UserEventType.UPDATE); + assertEquals(2, listUpdate.size()); + assertEquals(UserEventType.UPDATE, listUpdate.get(1).getType()); // delete user mockMvc.perform(delete(Constants.API_USERS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - assertThrows(NotFoundException.class,() -> userService.findByIdentifier(identifier)); + assertThrows(NotFoundException.class, () -> userService.findByIdentifier(identifier)); assertTrue(userEventService.findUserEventsByUser(userFoundAfterUpdate).isEmpty()); @@ -114,15 +115,15 @@ public void putUserCreateUpdateDelete() throws Exception { } @Test - public void putUsersErrorId() throws Exception { + void putUsersErrorId() throws Exception { String identifier = "NEWONE"; String otherIdentifier = "WRONG"; User user = initGestionnaire(identifier); String jsonUser = createJson(user); mockMvc.perform(put(Constants.API_USERS_ID, otherIdentifier).content(jsonUser) - .contentType(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) - .andExpect(content().string("id and user identifier don't match")); + .andExpect(content().json(JsonUtil.createJsonErrorBadRequest("id and user identifier don't match"))); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java index 9c7d6705..bf163ea7 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserEventControllerTest.java @@ -21,29 +21,29 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") -public class UserEventControllerTest { +class UserEventControllerTest { @Autowired private MockMvc mockMvc; @Test - public void getUserEventOk() throws Exception { + void getUserEventOk() throws Exception { String identifier = "USER1"; String json = createJsonUserEvent(identifier, null); - this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()).andExpect(status().isOk()) - .andExpect(content().json(json, false)); + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS, identifier)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(json, false)); } @Test - public void getUserEventNotFound() throws Exception { + void getUserEventNotFound() throws Exception { String identifier = "CONT500"; - this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS,identifier)).andDo(print()) - .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + this.mockMvc.perform(get(Constants.API_USERS_ID_USEREVENTS, identifier)).andDo(print()) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); } - private String createJsonUserEvent(String identifier, JSONObject payload ) throws JSONException { + private String createJsonUserEvent(String identifier, JSONObject payload) throws JSONException { JSONObject jo = new JSONObject(); JSONObject joPayload = new JSONObject(); joPayload.put("identifier", identifier); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java b/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java new file mode 100644 index 00000000..40221c03 --- /dev/null +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/util/JsonUtil.java @@ -0,0 +1,19 @@ +package fr.insee.survey.datacollectionmanagement.util; + +import net.minidev.json.JSONObject; +import org.springframework.http.HttpStatus; + +public class JsonUtil { + + + public static String createJsonError(int code, String message) { + JSONObject jo = new JSONObject(); + jo.put("code", code); + jo.put("message", message); + return jo.toString(); + } + + public static String createJsonErrorBadRequest(String message) { + return createJsonError(HttpStatus.BAD_REQUEST.value(), message); + } +} From 8a65a0dc7272f4139bf0524cc8b2b585de59e7dc Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:08:45 +0100 Subject: [PATCH 042/111] refactor: contact domain --- .../contact/controller/AddressController.java | 41 ++----- .../contact/controller/ContactController.java | 116 ++++++------------ .../controller/ContactEventController.java | 30 ++--- .../contact/dto/ContactEventDto.java | 1 - .../service/impl/ContactServiceImpl.java | 3 + .../contact/util/PayloadUtil.java | 22 ++++ .../validation/ContactGenderValidator.java | 2 +- 7 files changed, 89 insertions(+), 126 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index 20afcb52..b4736a0c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -6,15 +6,12 @@ import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; import fr.insee.survey.datacollectionmanagement.contact.dto.AddressDto; -import fr.insee.survey.datacollectionmanagement.contact.dto.ContactDto; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.contact.util.PayloadUtil; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -24,6 +21,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; @@ -46,28 +44,17 @@ public class AddressController { @Operation(summary = "Search for a contact address by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_ADDRESS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AddressDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "500", description = "Internal servor error") - }) @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - public ResponseEntity getContactAddress(@PathVariable("id") String id) { + public ResponseEntity getContactAddress(@PathVariable("id") String id) { Contact contact = contactService.findByIdentifier(id); - try { - if (contact.getAddress() != null) - return ResponseEntity.status(HttpStatus.OK) - .body(addressService.convertToDto(contact.getAddress())); - else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Address does not exist"); - } - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error"); - } + if (contact.getAddress() != null) + return ResponseEntity.status(HttpStatus.OK) + .body(addressService.convertToDto(contact.getAddress())); + else throw new NotFoundException(String.format("No address found for contact %s", id)); + } @@ -77,12 +64,8 @@ public ResponseEntity getContactAddress(@PathVariable("id") String id) { + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = AddressDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactDto.class))), - @ApiResponse(responseCode = "404", description = "Not found") - }) - public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto) { + + public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto, Authentication auth) { Contact contact = contactService.findByIdentifier(id); HttpStatus httpStatus; Address addressUpdate; @@ -102,7 +85,7 @@ public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody contactService.saveContact(contact); httpStatus = HttpStatus.CREATED; } - + PayloadUtil.getPayloadAuthor(auth); ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, null); contactEventService.saveContactEvent(contactEventUpdate); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index d505630c..5a9ad304 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -1,5 +1,7 @@ package fr.insee.survey.datacollectionmanagement.contact.controller; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; @@ -7,17 +9,13 @@ import fr.insee.survey.datacollectionmanagement.contact.dto.ContactFirstLoginDto; import fr.insee.survey.datacollectionmanagement.contact.service.AddressService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.contact.util.PayloadUtil; +import fr.insee.survey.datacollectionmanagement.exception.ImpossibleToDeleteException; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; -import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; -import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; -import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -29,21 +27,19 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.transaction.annotation.Transactional; +import org.springframework.security.core.Authentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.text.ParseException; +import java.io.Serial; import java.util.List; -import java.util.NoSuchElementException; -import java.util.Set; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| @AuthorizeMethodDecider.isAdmin() ") -@Tag(name = "1 - Contacts", description = "Enpoints to create, update, delete and find contacts") +@Tag(name = "1 - Contacts", description = "Endpoints to create, update, delete and find contacts") @Slf4j @RequiredArgsConstructor @Validated @@ -55,18 +51,13 @@ public class ContactController { private final ViewService viewService; - private final QuestioningService questioningService; - private final QuestioningAccreditationService questioningAccreditationService; private final ModelMapper modelMapper; @Operation(summary = "Search for contacts, paginated") @GetMapping(value = Constants.API_CONTACTS_ALL, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ContactPage.class))) - }) - public ResponseEntity getContacts( + public ResponseEntity getContacts( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "identifier") String sort) { @@ -82,90 +73,63 @@ public ResponseEntity getContacts( + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - public ResponseEntity getContact(@PathVariable("id") String id) { + public ResponseEntity getContact(@PathVariable("id") String id) { Contact contact = contactService.findByIdentifier(StringUtils.upperCase(id)); - try { - return ResponseEntity.ok().body(convertToFirstLoginDto(contact)); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + return ResponseEntity.ok().body(convertToFirstLoginDto(contact)); + } + @Operation(summary = "Update or create a contact") @PutMapping(value = Constants.API_CONTACTS_ID, produces = "application/json", consumes = "application/json") @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = ContactDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody @Valid ContactDto contactDto) { - if (StringUtils.isBlank(contactDto.getIdentifier()) || !contactDto.getIdentifier().equalsIgnoreCase(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("id and contact identifier don't match"); + public ResponseEntity putContact(@PathVariable("id") String id, @RequestBody @Valid ContactDto contactDto, Authentication auth) throws JsonProcessingException { + if (!contactDto.getIdentifier().equalsIgnoreCase(id)) { + throw new NotMatchException("id and contact identifier don't match"); } Contact contact; HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest() .buildAndExpand(contactDto.getIdentifier()).toUriString()); + JsonNode payload = PayloadUtil.getPayloadAuthor(auth); try { contact = convertToEntity(contactDto); - } catch (ParseException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse contact"); + if (contactDto.getAddress() != null) + contact.setAddress(addressService.convertToEntity(contactDto.getAddress())); + Contact contactUpdate = contactService.updateContactAddressEvent(contact, payload); + return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(contactUpdate)); } catch (NotFoundException e) { log.info("Creating contact with the identifier {}", contactDto.getIdentifier()); contact = convertToEntityNewContact(contactDto); if (contactDto.getAddress() != null) contact.setAddress(addressService.convertToEntity(contactDto.getAddress())); - Contact contactCreate = contactService.createContactAddressEvent(contact, null); + Contact contactCreate = contactService.createContactAddressEvent(contact, payload); viewService.createView(id, null, null); return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).body(convertToDto(contactCreate)); - } - if (contactDto.getAddress() != null) - contact.setAddress(addressService.convertToEntity(contactDto.getAddress())); - Contact contactUpdate = null; - try { - contactUpdate = contactService.updateContactAddressEvent(contact, null); - } catch (NotFoundException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error when update contact"); - } - return ResponseEntity.ok().headers(responseHeaders).body(convertToDto(contactUpdate)); + } - @Operation(summary = "Delete a contact, its address, its contactEvents and its accreditations") + + @Operation(summary = "Delete a contact, its address, its contactEvents") @DeleteMapping(value = Constants.API_CONTACTS_ID) - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) - @Transactional - public ResponseEntity deleteContact(@PathVariable("id") String id) { - try { - Contact contact = contactService.findByIdentifier(id); - contactService.deleteContactAddressEvent(contact); - - viewService.findViewByIdentifier(id).stream().forEach(viewService::deleteView); - questioningAccreditationService.findByContactIdentifier(id).stream().forEach(acc -> { - Questioning questioning = questioningService.findbyId(acc.getQuestioning().getId()); - Set newSet = questioning.getQuestioningAccreditations(); - newSet.removeIf(a -> a.getId().equals(acc.getId())); - questioning.setQuestioningAccreditations(newSet); - questioningService.saveQuestioning(questioning); - questioningAccreditationService.deleteAccreditation(acc); - - }); - log.info("Delete contact {}", id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact deleted"); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); + @ResponseStatus(HttpStatus.NO_CONTENT) + public void deleteContact(@PathVariable("id") String id) { + + if (!questioningAccreditationService.findByContactIdentifier(id).isEmpty()) { + throw new ImpossibleToDeleteException( + String.format("Contact %s cannot be deleted as he/she is still entitled to answer one or more questionnaires", id)); } + + log.info("Delete contact {}", id); + Contact contact = contactService.findByIdentifier(id); + contactService.deleteContactAddressEvent(contact); + } private ContactDto convertToDto(Contact contact) { @@ -177,12 +141,11 @@ private ContactDto convertToDto(Contact contact) { private ContactFirstLoginDto convertToFirstLoginDto(Contact contact) { ContactFirstLoginDto contactFirstLoginDto = modelMapper.map(contact, ContactFirstLoginDto.class); contactFirstLoginDto.setCivility(contact.getGender()); - contactFirstLoginDto.setFirstConnect(contact.getContactEvents().stream() - .filter(e -> e.getType().equals(ContactEventType.firstConnect)).count() == 0); + contactFirstLoginDto.setFirstConnect(contact.getContactEvents().stream().noneMatch(e -> e.getType().equals(ContactEventType.firstConnect))); return contactFirstLoginDto; } - private Contact convertToEntity(ContactDto contactDto) throws ParseException, NoSuchElementException { + private Contact convertToEntity(ContactDto contactDto) { Contact contact = modelMapper.map(contactDto, Contact.class); contact.setGender(Contact.Gender.valueOf(contactDto.getCivility())); Contact oldContact = contactService.findByIdentifier(contactDto.getIdentifier()); @@ -199,8 +162,9 @@ private Contact convertToEntityNewContact(ContactDto contactDto) { return contact; } - class ContactPage extends PageImpl { + static class ContactPage extends PageImpl { + @Serial private static final long serialVersionUID = 656181199902518234L; public ContactPage(List content, Pageable pageable, long total) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index 6bd5cf13..44e6f609 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -54,14 +54,10 @@ public class ContactEventController { }) public ResponseEntity getContactContactEvents(@PathVariable("id") String identifier) { Contact contact = contactService.findByIdentifier(identifier); - try { - return ResponseEntity.status(HttpStatus.OK) - .body(contact.getContactEvents().stream().map(this::convertToDto) - .toList()); + return ResponseEntity.status(HttpStatus.OK) + .body(contact.getContactEvents().stream().map(this::convertToDto) + .toList()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @@ -99,18 +95,13 @@ public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto co }) public ResponseEntity deleteContactEvent(@PathVariable("id") Long id) { ContactEvent contactEvent = contactEventService.findById(id); + Contact contact = contactEvent.getContact(); + contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent)) + .collect(Collectors.toSet())); + contactService.saveContact(contact); + contactEventService.deleteContactEvent(id); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted"); - try { - Contact contact = contactEvent.getContact(); - contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent)) - .collect(Collectors.toSet())); - contactService.saveContact(contact); - contactEventService.deleteContactEvent(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - - } } private ContactEventDto convertToDto(ContactEvent contactEvent) { @@ -120,7 +111,7 @@ private ContactEventDto convertToDto(ContactEvent contactEvent) { } private ContactEvent convertToEntity(ContactEventDto contactEventDto) { - return modelMapper.map(contactEventDto, ContactEvent.class); + return modelMapper.map(contactEventDto, ContactEvent.class); } class ContactEventPage extends PageImpl { @@ -132,4 +123,5 @@ public ContactEventPage(List content, Pageable pageable, long t } } + } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java index a84cf5b7..75fac077 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactEventDto.java @@ -11,7 +11,6 @@ @Setter public class ContactEventDto { - private Long id; private String identifier; private Date eventDate; @ContactEventTypeValid diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index d52de717..830e8657 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -14,6 +14,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.util.*; @@ -106,6 +107,7 @@ public List searchListContactParameters(String identifier, String lastN } @Override + @Transactional public Contact createContactAddressEvent(Contact contact, JsonNode payload) { if (contact.getAddress() != null) { addressService.saveAddress(contact.getAddress()); @@ -117,6 +119,7 @@ public Contact createContactAddressEvent(Contact contact, JsonNode payload) { } @Override + @Transactional public Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException { Contact existingContact = findByIdentifier(contact.getIdentifier()); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java new file mode 100644 index 00000000..ccb8edf3 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java @@ -0,0 +1,22 @@ +package fr.insee.survey.datacollectionmanagement.contact.util; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.security.core.Authentication; + +import java.util.HashMap; +import java.util.Map; + +public class PayloadUtil { + + private PayloadUtil() { + throw new IllegalStateException("Utility class"); + } + + public static JsonNode getPayloadAuthor(Authentication auth) { + Map mapAuthor = new HashMap<>(); + mapAuthor.put("author", auth.getName()); + return new ObjectMapper().valueToTree(mapAuthor); + } + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java index 5116f4d6..d82bd99c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/validation/ContactGenderValidator.java @@ -18,6 +18,6 @@ public void initialize(ContactGenderValid constraintAnnotation) { public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) return false; - return Arrays.stream(Contact.Gender.values()).anyMatch(v -> value.equalsIgnoreCase(v.name())); + return Arrays.stream(Contact.Gender.values()).anyMatch(v -> value.equals(v.name())); } } \ No newline at end of file From 274703061eb25b60e5f44eba20793b96b9d2b3e4 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:25:05 +0100 Subject: [PATCH 043/111] fix: payload for noauth mode --- .../contact/controller/AddressController.java | 8 +++++++- .../contact/controller/ContactController.java | 9 ++++++++- .../contact/util/PayloadUtil.java | 8 +++++--- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index b4736a0c..c44e7534 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -1,5 +1,7 @@ package fr.insee.survey.datacollectionmanagement.contact.controller; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Address; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; @@ -42,6 +44,9 @@ public class AddressController { private final ContactEventService contactEventService; + private final UserProvider userProvider; + + @Operation(summary = "Search for a contact address by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_ADDRESS, produces = "application/json") @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -85,7 +90,8 @@ public ResponseEntity putAddress(@PathVariable("id") String id, @Req contactService.saveContact(contact); httpStatus = HttpStatus.CREATED; } - PayloadUtil.getPayloadAuthor(auth); + AuthUser authUser = userProvider.getUser(auth); + PayloadUtil.getPayloadAuthor(authUser.getId()); ContactEvent contactEventUpdate = contactEventService.createContactEvent(contact, ContactEventType.update, null); contactEventService.saveContactEvent(contactEventUpdate); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java index 5a9ad304..39f7f508 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactController.java @@ -2,6 +2,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.survey.datacollectionmanagement.config.auth.user.AuthUser; +import fr.insee.survey.datacollectionmanagement.config.auth.user.UserProvider; import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.domain.ContactEvent.ContactEventType; @@ -55,6 +57,9 @@ public class ContactController { private final ModelMapper modelMapper; + private final UserProvider userProvider; + + @Operation(summary = "Search for contacts, paginated") @GetMapping(value = Constants.API_CONTACTS_ALL, produces = "application/json") public ResponseEntity getContacts( @@ -95,7 +100,9 @@ public ResponseEntity putContact(@PathVariable("id") String id, @Req HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest() .buildAndExpand(contactDto.getIdentifier()).toUriString()); - JsonNode payload = PayloadUtil.getPayloadAuthor(auth); + AuthUser authUser = userProvider.getUser(auth); + + JsonNode payload = PayloadUtil.getPayloadAuthor(authUser.getId()); try { contact = convertToEntity(contactDto); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java index ccb8edf3..e5b26742 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/util/PayloadUtil.java @@ -2,21 +2,23 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.security.core.Authentication; import java.util.HashMap; import java.util.Map; + public class PayloadUtil { private PayloadUtil() { throw new IllegalStateException("Utility class"); } - public static JsonNode getPayloadAuthor(Authentication auth) { + + public static JsonNode getPayloadAuthor(String author) { Map mapAuthor = new HashMap<>(); - mapAuthor.put("author", auth.getName()); + mapAuthor.put("author", author); return new ObjectMapper().valueToTree(mapAuthor); } + } From 03e49f28a70af3a572947848033e1f181f784506 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:28:33 +0100 Subject: [PATCH 044/111] refactor: contct controllers --- .../contact/controller/AddressController.java | 1 - .../controller/ContactEventController.java | 20 ------------------- 2 files changed, 21 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java index c44e7534..c8801cfa 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/AddressController.java @@ -69,7 +69,6 @@ public ResponseEntity getContactAddress(@PathVariable("id") String i + "|| @AuthorizeMethodDecider.isWebClient() " + "|| (@AuthorizeMethodDecider.isRespondent() && (#id == @AuthorizeMethodDecider.getUsername()))" + "|| @AuthorizeMethodDecider.isAdmin() ") - public ResponseEntity putAddress(@PathVariable("id") String id, @RequestBody AddressDto addressDto, Authentication auth) { Contact contact = contactService.findByIdentifier(id); HttpStatus httpStatus; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index 44e6f609..51efe807 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -7,11 +7,6 @@ import fr.insee.survey.datacollectionmanagement.contact.service.ContactEventService; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -47,11 +42,6 @@ public class ContactEventController { @Operation(summary = "Search for contactEvents by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_CONTACTEVENTS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = ContactEventDto.class)))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Internal servor error") - }) public ResponseEntity getContactContactEvents(@PathVariable("id") String identifier) { Contact contact = contactService.findByIdentifier(identifier); return ResponseEntity.status(HttpStatus.OK) @@ -63,11 +53,6 @@ public ResponseEntity getContactContactEvents(@PathVariable("id") String iden @Operation(summary = "Create a contactEvent") @PostMapping(value = Constants.API_CONTACTEVENTS, produces = "application/json", consumes = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = ContactEventDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request"), - @ApiResponse(responseCode = "404", description = "Not found") - }) public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto contactEventDto) { Contact contact = contactService.findByIdentifier(contactEventDto.getIdentifier()); @@ -88,11 +73,6 @@ public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto co @Operation(summary = "Delete a contact event") @DeleteMapping(value = Constants.API_CONTACTEVENTS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) public ResponseEntity deleteContactEvent(@PathVariable("id") Long id) { ContactEvent contactEvent = contactEventService.findById(id); Contact contact = contactEvent.getContact(); From 1ff6bf171224d606de855c2285d36e316dd64197 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Dec 2023 16:30:35 +0100 Subject: [PATCH 045/111] refactor: contact controllers --- .../contact/controller/ContactEventController.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java index 51efe807..c29e88bc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/controller/ContactEventController.java @@ -42,7 +42,7 @@ public class ContactEventController { @Operation(summary = "Search for contactEvents by the contact id") @GetMapping(value = Constants.API_CONTACTS_ID_CONTACTEVENTS, produces = "application/json") - public ResponseEntity getContactContactEvents(@PathVariable("id") String identifier) { + public ResponseEntity> getContactContactEvents(@PathVariable("id") String identifier) { Contact contact = contactService.findByIdentifier(identifier); return ResponseEntity.status(HttpStatus.OK) .body(contact.getContactEvents().stream().map(this::convertToDto) @@ -53,7 +53,7 @@ public ResponseEntity getContactContactEvents(@PathVariable("id") String iden @Operation(summary = "Create a contactEvent") @PostMapping(value = Constants.API_CONTACTEVENTS, produces = "application/json", consumes = "application/json") - public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto contactEventDto) { + public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto contactEventDto) { Contact contact = contactService.findByIdentifier(contactEventDto.getIdentifier()); ContactEvent contactEvent = convertToEntity(contactEventDto); @@ -73,14 +73,14 @@ public ResponseEntity postContactEvent(@RequestBody @Valid ContactEventDto co @Operation(summary = "Delete a contact event") @DeleteMapping(value = Constants.API_CONTACTEVENTS_ID, produces = "application/json") - public ResponseEntity deleteContactEvent(@PathVariable("id") Long id) { + @ResponseStatus(HttpStatus.NO_CONTENT) + public void deleteContactEvent(@PathVariable("id") Long id) { ContactEvent contactEvent = contactEventService.findById(id); Contact contact = contactEvent.getContact(); contact.setContactEvents(contact.getContactEvents().stream().filter(ce -> !ce.equals(contactEvent)) .collect(Collectors.toSet())); contactService.saveContact(contact); contactEventService.deleteContactEvent(id); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Contact event deleted"); } From e23448bda8f23ac300669b5888450a57b2ce4b20 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 11 Dec 2023 11:48:54 +0100 Subject: [PATCH 046/111] refactor: handle exceptions in controller of matadata domain --- .../controller/CampaignController.java | 87 ++++++---------- .../metadata/controller/OwnerController.java | 28 +----- .../controller/PartitioningController.java | 61 +++--------- .../PeriodPeriodicityController.java | 21 +--- .../metadata/controller/SourceController.java | 96 ++++++------------ .../controller/SupportController.java | 26 +---- .../metadata/controller/SurveyController.java | 98 ++++++------------- .../query/controller/MoogController.java | 40 ++++---- 8 files changed, 139 insertions(+), 318 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 1b3072ac..4f09e513 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -1,6 +1,7 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.ImpossibleToDeleteException; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.exception.NotMatchException; import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; @@ -15,7 +16,6 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.UploadService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; @@ -38,7 +38,6 @@ import java.util.List; import java.util.Set; -import java.util.stream.Collectors; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -65,36 +64,24 @@ public class CampaignController { @Operation(summary = "Search for campaigns, paginated") @GetMapping(value = Constants.API_CAMPAIGNS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = CampaignPage.class))) - }) - public ResponseEntity getSources( + public ResponseEntity getSources( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "id") String sort) { Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); Page pageCampaign = campaignService.findAll(pageable); - List listCampaigns = pageCampaign.stream().map(c -> convertToDto(c)).collect(Collectors.toList()); + List listCampaigns = pageCampaign.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new CampaignPage(listCampaigns, pageable, pageCampaign.getTotalElements())); } @Operation(summary = "Search for campaigns by the survey id") @GetMapping(value = Constants.API_SURVEYS_ID_CAMPAIGNS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = CampaignDto.class)))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getCampaignsBySurvey(@PathVariable("id") String id) { + public ResponseEntity> getCampaignsBySurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(id); + return ResponseEntity.ok() + .body(survey.getCampaigns().stream().map(this::convertToDto).toList()); - try { - return ResponseEntity.ok() - .body(survey.getCampaigns().stream().map(s -> convertToDto(s)).toList()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @Operation(summary = "Search for a campaign by its id") @@ -104,14 +91,10 @@ public ResponseEntity getCampaignsBySurvey(@PathVariable("id") String id) { @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity getCampaign(@PathVariable("id") String id) { + public ResponseEntity getCampaign(@PathVariable("id") String id) { Campaign campaign = campaignService.findById(StringUtils.upperCase(id)); + return ResponseEntity.ok().body(convertToDto(campaign)); - try { - return ResponseEntity.ok().body(convertToDto(campaign)); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @@ -122,8 +105,8 @@ public ResponseEntity getCampaign(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = CampaignDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Valid CampaignDto campaignDto) { - if ( !campaignDto.getId().equalsIgnoreCase(id)) { + public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Valid CampaignDto campaignDto) { + if (!campaignDto.getId().equalsIgnoreCase(id)) { throw new NotMatchException("id and idCampaign don't match"); } HttpHeaders responseHeaders = new HttpHeaders(); @@ -149,42 +132,34 @@ public ResponseEntity putCampaign(@PathVariable("id") String id, @RequestBody @Operation(summary = "Delete a campaign, its campaigns, partitionings, questionings ...") @DeleteMapping(value = {Constants.API_CAMPAIGNS_ID, Constants.MOOG_API_CAMPAIGNS_ID}) - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) + @Transactional - public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr.insee.survey.datacollectionmanagement.exception.NotFoundException { + public void deleteCampaign(@PathVariable("id") String id) throws fr.insee.survey.datacollectionmanagement.exception.NotFoundException { if (campaignService.isCampaignOngoing(id)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Campaign is still ongoing and can't be deleted"); + throw new ImpossibleToDeleteException("Campaign is still ongoing and can't be deleted"); } Campaign campaign = campaignService.findById(id); - try { - int nbQuestioningDeleted = 0; - Survey survey = campaign.getSurvey(); - survey.getCampaigns().remove(campaign); - surveyService.insertOrUpdateSurvey(survey); - List uploadsCamp = uploadService.findAllByIdCampaign(id); - campaignService.deleteCampaignById(id); - Set listPartitionings = campaign.getPartitionings(); - - int nbViewDeleted = viewService.deleteViewsOfOneCampaign(campaign); - - for (Partitioning partitioning : listPartitionings) { - nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); - } - uploadsCamp.forEach(up -> uploadService.delete(up)); - log.info("Campaign {} deleted with all its metadata children - {} questioning deleted - {} view deleted - {} uploads deleted", - id, - nbQuestioningDeleted, nbViewDeleted, uploadsCamp.size()); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Campaign deleted"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); + int nbQuestioningDeleted = 0; + Survey survey = campaign.getSurvey(); + survey.getCampaigns().remove(campaign); + surveyService.insertOrUpdateSurvey(survey); + List uploadsCamp = uploadService.findAllByIdCampaign(id); + campaignService.deleteCampaignById(id); + Set listPartitionings = campaign.getPartitionings(); + + int nbViewDeleted = viewService.deleteViewsOfOneCampaign(campaign); + + for (Partitioning partitioning : listPartitionings) { + nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); } + uploadsCamp.forEach(uploadService::delete); + log.info("Campaign {} deleted with all its metadata children - {} questioning deleted - {} view deleted - {} uploads deleted", + id, + nbQuestioningDeleted, nbViewDeleted, uploadsCamp.size()); + } @Operation(summary = "campaign is ongoing") @@ -193,7 +168,7 @@ public ResponseEntity deleteCampaign(@PathVariable("id") String id) throws fr @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OnGoingDto.class))), @ApiResponse(responseCode = "404", description = "Not found") }) - public ResponseEntity isOnGoingCampaign(@PathVariable("id") String id) { + public ResponseEntity isOnGoingCampaign(@PathVariable("id") String id) { boolean isOnGoing = campaignService.isCampaignOngoing(id); return ResponseEntity.ok().body(new OnGoingDto(isOnGoing)); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java index 2910a649..1a1eb574 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/OwnerController.java @@ -7,10 +7,6 @@ import fr.insee.survey.datacollectionmanagement.metadata.dto.OwnerDto; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -44,10 +40,7 @@ public class OwnerController { @Operation(summary = "Search for owners, paginated") @GetMapping(value = Constants.API_OWNERS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OwnerPage.class))) - }) - public ResponseEntity getOwners( + public ResponseEntity getOwners( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "id") String sort) { @@ -59,12 +52,7 @@ public ResponseEntity getOwners( @Operation(summary = "Search for a owner by its id") @GetMapping(value = Constants.API_OWNERS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OwnerDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getOwner(@PathVariable("id") String id) { + public ResponseEntity getOwner(@PathVariable("id") String id) { Owner owner = ownerService.findById(id); return ResponseEntity.ok().body(convertToDto(owner)); @@ -72,12 +60,7 @@ public ResponseEntity getOwner(@PathVariable("id") String id) { @Operation(summary = "Update or create a owner") @PutMapping(value = Constants.API_OWNERS_ID, produces = "application/json", consumes = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = OwnerDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = OwnerDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @Valid OwnerDto ownerDto) { + public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @Valid OwnerDto ownerDto) { if (!ownerDto.getId().equals(id)) { throw new NotMatchException("id and owner id don't match"); } @@ -92,8 +75,7 @@ public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @V log.warn("Update owner with the id {}", ownerDto.getId()); httpStatus = HttpStatus.OK; - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.info("Create owner with the id {}", ownerDto.getId()); httpStatus = HttpStatus.CREATED; } @@ -102,7 +84,7 @@ public ResponseEntity putOwner(@PathVariable("id") String id, @RequestBody @V Owner owner = ownerService.insertOrUpdateOwner(convertToEntity(ownerDto)); return ResponseEntity.status(httpStatus).headers(responseHeaders).body(convertToDto(owner)); } - + private OwnerDto convertToDto(Owner owner) { return modelmapper.map(owner, OwnerDto.class); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java index e09229a1..265633db 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PartitioningController.java @@ -10,7 +10,6 @@ import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; @@ -51,38 +50,21 @@ public class PartitioningController { @Operation(summary = "Search for partitionings by the campaign id") @GetMapping(value = Constants.API_CAMPAIGNS_ID_PARTITIONINGS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = PartitioningDto.class)))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getPartitioningsByCampaign(@PathVariable("id") String id) { + public ResponseEntity> getPartitioningsByCampaign(@PathVariable("id") String id) { Campaign campaign = campaignService.findById(id); - try { - return ResponseEntity.ok() - .body(campaign.getPartitionings().stream().map(this::convertToDto) - .toList()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + return ResponseEntity.ok() + .body(campaign.getPartitionings().stream().map(this::convertToDto) + .toList()); + } @Operation(summary = "Search for a partitioning by its id") @GetMapping(value = Constants.API_PARTITIONINGS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = PartitioningDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getPartitioning(@PathVariable("id") String id) { + public ResponseEntity getPartitioning(@PathVariable("id") String id) { Partitioning partitioning = partitioningService.findById(StringUtils.upperCase(id)); - try { - return ResponseEntity.ok().body(convertToDto(partitioning)); + return ResponseEntity.ok().body(convertToDto(partitioning)); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } @@ -93,8 +75,8 @@ public ResponseEntity getPartitioning(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = PartitioningDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putPartitioning(@PathVariable("id") String id, - @RequestBody PartitioningDto partitioningDto) { + public ResponseEntity putPartitioning(@PathVariable("id") String id, + @RequestBody PartitioningDto partitioningDto) { if (!partitioningDto.getId().equalsIgnoreCase(id)) { throw new NotMatchException("id and owner id don't match"); } @@ -124,28 +106,17 @@ public ResponseEntity putPartitioning(@PathVariable("id") String id, @Operation(summary = "Delete a partitioning, its partitionings, partitionings, questionings ...") @DeleteMapping(value = Constants.API_PARTITIONINGS_ID) - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) @Transactional - public ResponseEntity deletePartitioning(@PathVariable("id") String id) { + public void deletePartitioning(@PathVariable("id") String id) { Partitioning partitioning = partitioningService.findById(id); + Campaign campaign = partitioning.getCampaign(); + campaign.getPartitionings().remove(partitioning); + campaignService.insertOrUpdateCampaign(campaign); + partitioningService.deletePartitioningById(id); - try { - - Campaign campaign = partitioning.getCampaign(); - campaign.getPartitionings().remove(partitioning); - campaignService.insertOrUpdateCampaign(campaign); - partitioningService.deletePartitioningById(id); + int nbQuestioningDeleted = questioningService.deleteQuestioningsOfOnePartitioning(partitioning); + log.info("Partitioning {} deleted - {} questionings deleted", id, nbQuestioningDeleted); - int nbQuestioningDeleted = questioningService.deleteQuestioningsOfOnePartitioning(partitioning); - log.info("Partitioning {} deleted - {} questionings deleted", id, nbQuestioningDeleted); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Partitioning deleted"); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } private PartitioningDto convertToDto(Partitioning partitioning) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java index ef90620d..d88ef5d3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java @@ -1,15 +1,13 @@ package fr.insee.survey.datacollectionmanagement.metadata.controller; import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; @@ -24,10 +22,7 @@ public class PeriodPeriodicityController { @Operation(summary = "Search for periodicities") @GetMapping(value = Constants.API_PERIODICITIES, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK") - }) - public ResponseEntity getPeriodicities() { + public ResponseEntity getPeriodicities() { JSONArray jsonArray = new JSONArray(); for (PeriodicityEnum periodicity : PeriodicityEnum.values()) { JSONObject json = new JSONObject(); @@ -40,10 +35,7 @@ public ResponseEntity getPeriodicities() { @Operation(summary = "Search for periods") @GetMapping(value = Constants.API_PERIODS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK") - }) - public ResponseEntity getPeriods() { + public ResponseEntity getPeriods() { JSONArray jsonArray = new JSONArray(); for (PeriodEnum period : PeriodEnum.values()) { @@ -58,10 +50,7 @@ public ResponseEntity getPeriods() { @Operation(summary = "Search for periods of a periodicity") @GetMapping(value = Constants.API_PERIODICITIES_ID_PERIODS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK") - }) - public ResponseEntity getPeriodsOdPeriodicity(String periodicity) { + public ResponseEntity getPeriodsOfPeriodicity(String periodicity) { try { PeriodicityEnum.valueOf(periodicity); JSONArray jsonArray = new JSONArray(); @@ -76,7 +65,7 @@ public ResponseEntity getPeriodsOdPeriodicity(String periodicity) { } return ResponseEntity.ok().body(jsonArray.toString()); } catch (IllegalArgumentException e) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body("periodicity does not exist"); + throw new NotFoundException("periodicity does not exist"); } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index cd2c2f49..240f2171 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -8,18 +8,12 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; import fr.insee.survey.datacollectionmanagement.metadata.dto.SourceCompleteDto; -import fr.insee.survey.datacollectionmanagement.metadata.dto.SurveyDto; import fr.insee.survey.datacollectionmanagement.metadata.service.OwnerService; import fr.insee.survey.datacollectionmanagement.metadata.service.SourceService; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -63,10 +57,7 @@ public class SourceController { @Operation(summary = "Search for sources, paginated") @GetMapping(value = Constants.API_SOURCES, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SourcePage.class))) - }) - public ResponseEntity getSources( + public ResponseEntity getSources( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "id") String sort) { @@ -78,12 +69,7 @@ public ResponseEntity getSources( @Operation(summary = "Search for a source by its id") @GetMapping(value = Constants.API_SOURCES_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SourceCompleteDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getSource(@PathVariable("id") String id) { + public ResponseEntity getSource(@PathVariable("id") String id) { Source source = sourceService.findById(StringUtils.upperCase(id)); source = sourceService.findById(StringUtils.upperCase(id)); return ResponseEntity.ok().body(convertToDto(source)); @@ -92,13 +78,8 @@ public ResponseEntity getSource(@PathVariable("id") String id) { @Operation(summary = "Update or create a source") @PutMapping(value = Constants.API_SOURCES_ID, produces = "application/json", consumes = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SourceCompleteDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SourceCompleteDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody @Valid SourceCompleteDto SourceCompleteDto) { - if ( !SourceCompleteDto.getId().equalsIgnoreCase(id)) { + public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody @Valid SourceCompleteDto SourceCompleteDto) { + if (!SourceCompleteDto.getId().equalsIgnoreCase(id)) { throw new NotMatchException("id and source id don't match"); } @@ -129,62 +110,43 @@ public ResponseEntity putSource(@PathVariable("id") String id, @RequestBody @ @Operation(summary = "Delete a source, its surveys, campaigns, partitionings, questionings ...") @DeleteMapping(value = Constants.API_SOURCES_ID) - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) @Transactional - public ResponseEntity deleteSource(@PathVariable("id") String id) { + public void deleteSource(@PathVariable("id") String id) { int nbQuestioningDeleted = 0, nbViewDeleted = 0; Source source = sourceService.findById(id); - try { - if (source.getOwner() != null) - ownerService.removeSourceFromOwner(source.getOwner(), source); - - if (source.getSupport() != null) - supportService.removeSourceFromSupport(source.getSupport(), source); - - sourceService.deleteSourceById(id); - List listCampaigns = new ArrayList<>(); - List listPartitionings = new ArrayList<>(); - - source.getSurveys().stream().forEach(su -> listCampaigns.addAll(su.getCampaigns())); - source.getSurveys().stream().forEach( - su -> su.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings()))); - - for (Campaign campaign : listCampaigns) { - nbViewDeleted += viewService.deleteViewsOfOneCampaign(campaign); - } - for (Partitioning partitioning : listPartitionings) { - nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); - } - log.info("Source {} deleted with all its metadata children - {} questioning deleted - {} view deleted", id, - nbQuestioningDeleted, nbViewDeleted); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Source deleted"); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); + if (source.getOwner() != null) + ownerService.removeSourceFromOwner(source.getOwner(), source); + + if (source.getSupport() != null) + supportService.removeSourceFromSupport(source.getSupport(), source); + + sourceService.deleteSourceById(id); + List listCampaigns = new ArrayList<>(); + List listPartitionings = new ArrayList<>(); + + source.getSurveys().stream().forEach(su -> listCampaigns.addAll(su.getCampaigns())); + source.getSurveys().stream().forEach( + su -> su.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings()))); + + for (Campaign campaign : listCampaigns) { + nbViewDeleted += viewService.deleteViewsOfOneCampaign(campaign); } + for (Partitioning partitioning : listPartitionings) { + nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); + } + log.info("Source {} deleted with all its metadata children - {} questioning deleted - {} view deleted", id, + nbQuestioningDeleted, nbViewDeleted); + } @Operation(summary = "Search for surveys by the owner id") @GetMapping(value = Constants.API_OWNERS_ID_SOURCES, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = SurveyDto.class)))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) public ResponseEntity getSourcesByOwner(@PathVariable("id") String id) { Owner owner = ownerService.findById(id); + return ResponseEntity.ok() + .body(owner.getSources().stream().map(this::convertToDto).toList()); - try { - return ResponseEntity.ok() - .body(owner.getSources().stream().map(this::convertToDto).toList()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java index 5fe9a754..d5d027f4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SupportController.java @@ -7,10 +7,6 @@ import fr.insee.survey.datacollectionmanagement.metadata.dto.SupportDto; import fr.insee.survey.datacollectionmanagement.metadata.service.SupportService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -44,10 +40,7 @@ public class SupportController { @Operation(summary = "Search for supports, paginated") @GetMapping(value = Constants.API_SUPPORTS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SupportPage.class))) - }) - public ResponseEntity getSupports( + public ResponseEntity getSupports( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer size, @RequestParam(defaultValue = "id") String sort) { @@ -59,12 +52,7 @@ public ResponseEntity getSupports( @Operation(summary = "Search for a support by its id") @GetMapping(value = Constants.API_SUPPORTS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SupportDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getSupport(@PathVariable("id") String id) { + public ResponseEntity getSupport(@PathVariable("id") String id) { Support support = supportService.findById(id); return ResponseEntity.ok().body(convertToDto(support)); @@ -72,12 +60,7 @@ public ResponseEntity getSupport(@PathVariable("id") String id) { @Operation(summary = "Update or create a support") @PutMapping(value = Constants.API_SUPPORTS_ID, produces = "application/json", consumes = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SupportDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SupportDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody @Valid SupportDto supportDto) { + public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody @Valid SupportDto supportDto) { if (!supportDto.getId().equals(id)) { throw new NotMatchException("id and support id don't match"); } @@ -86,9 +69,8 @@ public ResponseEntity putSupport(@PathVariable("id") String id, @RequestBody responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(supportDto.getId()).toUriString()); HttpStatus httpStatus; - Support supportBase; try { - supportBase = supportService.findById(id); + supportService.findById(id); log.info("Update support with the id {}", supportDto.getId()); httpStatus = HttpStatus.OK; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 34820613..b1ecf75a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -13,11 +13,6 @@ import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; import fr.insee.survey.datacollectionmanagement.view.service.ViewService; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @@ -58,29 +53,16 @@ public class SurveyController { @Operation(summary = "Search for surveys by the source id") @GetMapping(value = Constants.API_SOURCES_ID_SURVEYS, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = SurveyDto.class)))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) - public ResponseEntity getSurveysBySource(@PathVariable("id") String id) { + public ResponseEntity> getSurveysBySource(@PathVariable("id") String id) { Source source = sourceService.findById(id); - try { - return ResponseEntity.ok() - .body(source.getSurveys().stream().map(this::convertToDto).toList()); - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); - } + return ResponseEntity.ok() + .body(source.getSurveys().stream().map(this::convertToDto).toList()); + } @Operation(summary = "Search for a survey by its id") @GetMapping(value = Constants.API_SURVEYS_ID, produces = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SurveyDto.class))), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad request") - }) public ResponseEntity getSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(StringUtils.upperCase(id)); return ResponseEntity.ok().body(convertToDto(survey)); @@ -90,11 +72,6 @@ public ResponseEntity getSurvey(@PathVariable("id") String id) { @Operation(summary = "Update or create a survey") @PutMapping(value = Constants.API_SURVEYS_ID, produces = "application/json", consumes = "application/json") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SurveyDto.class))), - @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyDto.class))), - @ApiResponse(responseCode = "400", description = "Bad request") - }) public ResponseEntity putSurvey(@PathVariable("id") String id, @RequestBody @Valid SurveyDto surveyDto) { if (!surveyDto.getId().equalsIgnoreCase(id)) { throw new NotMatchException("id and idSurvey don't match"); @@ -125,50 +102,39 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @Reque @Operation(summary = "Delete a survey, its campaigns, partitionings, questionings ...") @DeleteMapping(value = Constants.API_SURVEYS_ID) - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "400", description = "Bad Request") - }) @Transactional - public ResponseEntity deleteSurvey(@PathVariable("id") String id) { + public void deleteSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(id); - try { + int nbQuestioningDeleted = 0; + int nbViewDeleted = 0; + + Source source = survey.getSource(); + source.getSurveys().remove(survey); + sourceService.insertOrUpdateSource(source); + surveyService.deleteSurveyById(id); + List listPartitionings = new ArrayList<>(); - int nbQuestioningDeleted = 0; - int nbViewDeleted = 0; - - Source source = survey.getSource(); - source.getSurveys().remove(survey); - sourceService.insertOrUpdateSource(source); - surveyService.deleteSurveyById(id); - List listPartitionings = new ArrayList<>(); - - survey.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings())); - - for (Campaign campaign : survey.getCampaigns()) { - viewService.findViewByCampaignId(campaign.getId()).stream() - .forEach(v -> viewService.deleteView(v)); - } - for (Partitioning partitioning : listPartitionings) { - questioningService.findByIdPartitioning(partitioning.getId()).stream() - .forEach(q -> questioningService.deleteQuestioning(q.getId())); - } - - for (Campaign campaign : survey.getCampaigns()) { - nbViewDeleted += viewService.deleteViewsOfOneCampaign(campaign); - } - for (Partitioning partitioning : listPartitionings) { - nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); - } - log.info("Source {} deleted and all its metadata children - {} questioning deleted - {} view deleted", id, - nbQuestioningDeleted, nbViewDeleted); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Survey deleted"); - - } catch (Exception e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); + survey.getCampaigns().stream().forEach(c -> listPartitionings.addAll(c.getPartitionings())); + + for (Campaign campaign : survey.getCampaigns()) { + viewService.findViewByCampaignId(campaign.getId()).stream() + .forEach(v -> viewService.deleteView(v)); + } + for (Partitioning partitioning : listPartitionings) { + questioningService.findByIdPartitioning(partitioning.getId()).stream() + .forEach(q -> questioningService.deleteQuestioning(q.getId())); + } + + for (Campaign campaign : survey.getCampaigns()) { + nbViewDeleted += viewService.deleteViewsOfOneCampaign(campaign); + } + for (Partitioning partitioning : listPartitionings) { + nbQuestioningDeleted += questioningService.deleteQuestioningsOfOnePartitioning(partitioning); } + log.info("Source {} deleted and all its metadata children - {} questioning deleted - {} view deleted", id, + nbQuestioningDeleted, nbViewDeleted); + } private SurveyDto convertToDto(Survey survey) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java index eaaa405b..d1579513 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogController.java @@ -49,36 +49,32 @@ public class MoogController { @GetMapping(path = Constants.API_MOOG_SEARCH) - public ResponseEntity moogSearch(@RequestParam(required = false) String filter1, - @RequestParam(required = false) String filter2, - @RequestParam(defaultValue = "0", required = false) int pageNo, - @RequestParam(defaultValue = "20", required = false) int pageSize) { + public ResponseEntity> moogSearch(@RequestParam(required = false) String filter1, + @RequestParam(required = false) String filter2, + @RequestParam(defaultValue = "0", required = false) int pageNo, + @RequestParam(defaultValue = "20", required = false) int pageSize) { List listView = moogService.moogSearch(filter1); Pageable pageable = PageRequest.of(pageNo, pageSize); int start = (int) pageable.getOffset(); - int end = (int) ((start + pageable.getPageSize()) > listView.size() ? listView.size() - : (start + pageable.getPageSize())); + int end = (start + pageable.getPageSize()) > listView.size() ? listView.size() + : (start + pageable.getPageSize()); if (start <= end) { - Page page = new PageImpl( + Page page = new PageImpl<>( moogService.transformListViewToListMoogSearchDto(listView.subList(start, end)), pageable, listView.size()); return new ResponseEntity<>(page, HttpStatus.OK); } else - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + throw new IllegalArgumentException("Start must be inferior to end"); } @GetMapping(path = Constants.API_MOOG_MAIL, produces = "application/json") @Operation(summary = "Get Moog questioning events by campaign and idSu") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = String.class))), - @ApiResponse(responseCode = "404", description = "Not found") - }) - public ResponseEntity getMoogMail(@PathVariable("id") String contactId) { + public ResponseEntity getMoogMail(@PathVariable("id") String contactId) { Contact contact = contactService.findByIdentifier(contactId); return ResponseEntity.ok().body(contact.getEmail()); } @@ -89,8 +85,8 @@ public ResponseEntity getMoogMail(@PathVariable("id") String contactId) { @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = MoogQuestioningEventDto.class)))), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity getMoogQuestioningEvents(@PathVariable("campaign") String campaignId, - @PathVariable("id") String idSu) { + public ResponseEntity>> getMoogQuestioningEvents(@PathVariable("campaign") String campaignId, + @PathVariable("id") String idSu) { return new ResponseEntity<>(Map.of("datas", moogService.getMoogEvents(campaignId, idSu)), HttpStatus.OK); } @@ -104,21 +100,19 @@ public JSONCollectionWrapper provideDataForExtraction(@Pat @GetMapping(value = Constants.MOOG_API_CAMPAIGN_SURVEYUNITS_FOLLOWUP, produces = "application/json") public JSONCollectionWrapper displaySurveyUnitsToFollowUp(@PathVariable String idCampaign) { log.info("Request GET for su to follow up - campaign {}", idCampaign); - return new JSONCollectionWrapper(moogService.getSurveyUnitsToFollowUp(idCampaign)); + return new JSONCollectionWrapper<>(moogService.getSurveyUnitsToFollowUp(idCampaign)); } @GetMapping(value = Constants.MOOG_API_READONLY_URL, produces = "application/json") - public ResponseEntity getReadOnlyUrl(@PathVariable String idCampaign, @PathVariable String surveyUnitId){ - log.info("Request READONLY url for su {} and campaign {}",surveyUnitId, idCampaign); + public ResponseEntity getReadOnlyUrl(@PathVariable String idCampaign, @PathVariable String surveyUnitId) { + log.info("Request READONLY url for su {} and campaign {}", surveyUnitId, idCampaign); String url; try { url = moogService.getReadOnlyUrl(idCampaign, surveyUnitId); return ResponseEntity.ok().body(url); - } - catch (NotFoundException e){ - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); - } - catch (Exception e){ + } catch (NotFoundException e) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); + } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); } } From a15d0712a4a3035cad6255bd9566faf2ced1c12d Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 19 Dec 2023 15:01:37 +0100 Subject: [PATCH 047/111] fix: cors? --- .../config/ApplicationConfig.java | 5 ++--- .../config/CorsGlobalConfig.java | 4 +--- .../exception/ExceptionControllerAdvice.java | 9 +++++++++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java index 0738f24b..bbbac362 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/ApplicationConfig.java @@ -6,7 +6,6 @@ import org.springframework.context.annotation.Configuration; import java.util.List; -import java.util.Optional; @Configuration @Getter @@ -35,8 +34,8 @@ public class ApplicationConfig { @Value("${fr.insee.datacollectionmanagement.auth.mode}") private String authType; - @Value("${fr.insee.datacollectionmanagement.cors.allowedOrigin}") - private Optional allowedOrigin; + @Value("${fr.insee.datacollectionmanagement.cors.allowedOrigins}") + private String[] allowedOrigins; @Value("${fr.insee.datacollectionmanagement.auth.realm}") private String keycloakRealm; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java index 5c387d8f..0c1cf9d2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/config/CorsGlobalConfig.java @@ -4,11 +4,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -@EnableWebMvc @RequiredArgsConstructor public class CorsGlobalConfig { @@ -19,7 +17,7 @@ public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { - String ao = applicationConfig.getAllowedOrigin().orElse("*"); + String[] ao = applicationConfig.getAllowedOrigins(); registry.addMapping("/**") .allowedOrigins(ao) .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java index f575dc57..6e11d77f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/exception/ExceptionControllerAdvice.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; +import jakarta.persistence.EntityNotFoundException; import jakarta.validation.ConstraintViolationException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -121,6 +122,14 @@ public ResponseEntity notFoundException(NotFoundException e, WebReques return processException(e, HttpStatus.NOT_FOUND, request); } + @ExceptionHandler(EntityNotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public ResponseEntity entityNotFoundException(NotFoundException e, WebRequest request) { + log.error(e.getMessage(), e); + return processException(e, HttpStatus.NOT_FOUND, request); + } + + @ExceptionHandler(NotMatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity notMatchException(NotMatchException e, WebRequest request) { From 326d4cbcc61e247d8c69297e17bcae49b239a9e0 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 14:57:16 +0100 Subject: [PATCH 048/111] fix: property in tests --- src/test/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 5d35db12..81356cee 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -13,7 +13,7 @@ springdoc.swagger-ui.tagsSorter: alpha springdoc.swagger-ui.enabled=true -fr.insee.datacollectionmanagement.cors.allowedOrigin=* +fr.insee.datacollectionmanagement.cors.allowedOrigins=* #Actuator Metrics From a01a76483550d4f609a823d2f0c555ee447b6b0f Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 16:38:21 +0100 Subject: [PATCH 049/111] fix: tests --- .../metadata/controller/SourceController.java | 1 + .../metadata/controller/SurveyController.java | 1 + .../contacts/controller/ContactControllerTest.java | 2 +- .../user/controller/controller/UserControllerTest.java | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java index 240f2171..6a6f1367 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SourceController.java @@ -110,6 +110,7 @@ public ResponseEntity putSource(@PathVariable("id") String id @Operation(summary = "Delete a source, its surveys, campaigns, partitionings, questionings ...") @DeleteMapping(value = Constants.API_SOURCES_ID) + @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void deleteSource(@PathVariable("id") String id) { int nbQuestioningDeleted = 0, nbViewDeleted = 0; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index b1ecf75a..ebbe7dca 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -102,6 +102,7 @@ public ResponseEntity putSurvey(@PathVariable("id") String id, @Reque @Operation(summary = "Delete a survey, its campaigns, partitionings, questionings ...") @DeleteMapping(value = Constants.API_SURVEYS_ID) + @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void deleteSurvey(@PathVariable("id") String id) { Survey survey = surveyService.findById(id); diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java index b5115f5e..9b173ca4 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/contacts/controller/ContactControllerTest.java @@ -118,7 +118,7 @@ void putContactCreateUpdateDelete() throws Exception { assertTrue(contactEventService.findContactEventsByContact(contactFoundAfterUpdate).isEmpty()); // delete contact not found - mockMvc.perform(delete("/contacts/" + identifier).contentType(MediaType.APPLICATION_JSON)) + mockMvc.perform(delete(Constants.API_CONTACTS + identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java index be744971..2157a7f0 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/user/controller/controller/UserControllerTest.java @@ -109,7 +109,7 @@ void putUserCreateUpdateDelete() throws Exception { assertTrue(userEventService.findUserEventsByUser(userFoundAfterUpdate).isEmpty()); // delete user not found - mockMvc.perform(delete("/users/" + identifier).contentType(MediaType.APPLICATION_JSON)) + mockMvc.perform(delete(Constants.API_USERS_ID, identifier).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } From 0692a11efd102d0fb9c2db6391472b3866771539 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 16:38:47 +0100 Subject: [PATCH 050/111] ci: ci for develop branch --- .github/workflows/ci-rc.yml | 89 +++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 .github/workflows/ci-rc.yml diff --git a/.github/workflows/ci-rc.yml b/.github/workflows/ci-rc.yml new file mode 100644 index 00000000..1e059850 --- /dev/null +++ b/.github/workflows/ci-rc.yml @@ -0,0 +1,89 @@ +name: ci +on: + push: + branches: [develop] + pull_request: + branches: [develop] +jobs: + build: + name: Build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v3 + with: + distribution: temurin + java-version: 21 + - name: Build with Maven + run: mvn -B clean package + - name: Upload jar + uses: actions/upload-artifact@v3 + with: + name: jar + path: target/*.jar + + get_version: + needs: build + if: | + github.event_name == 'push' + runs-on: ubuntu-latest + outputs: + version: ${{steps.version.outputs.version}} + steps: + - name: Checkout current branch + uses: actions/checkout@v3 + with: + ref: ${{ github.ref }} + - name: Get current version + id: version + run: echo "version=$(mvn -f pom.xml help:evaluate -Dexpression=project.version -q -DforceStdout)" >> "$GITHUB_OUTPUT" + - run: echo ${{steps.version.outputs.version}} + + release: + needs: get_version + runs-on: ubuntu-latest + steps: + - name: Checkout current branch + uses: actions/checkout@v3 + with: + ref: ${{ github.ref }} + - uses: softprops/action-gh-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{needs.get_version.outputs.version}}-rc + target_commitish: ${{ github.head_ref || github.ref }} + name: Release ${{needs.get_version.outputs.version}}-rc + draft: false + generate_release_notes: true + prerelease: false + + + docker: + needs: get_version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.ref }} + - name: Download jar + id: download + uses: actions/download-artifact@v3 + with: + name: jar + path: target + - uses: docker/setup-qemu-action@v2 + - uses: docker/setup-buildx-action@v2 + - uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - uses: docker/build-push-action@v4 + with: + platforms: linux/amd64,linux/arm64 + context: . + push: true + tags: | + inseefr/platine-management-back-office:${{ needs.get_version.outputs.version }}-rc + inseefr/platine-management-back-office:latest From 146aecdd09b8431fee5034ff9f2380170992f1a3 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 16:51:34 +0100 Subject: [PATCH 051/111] build: version 1.1.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a22fe2d9..966efc8c 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.0-rc + 1.1.0 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From 62fed6b3d2a2a2ea1ba1a1d2035fa5a19981fd52 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 16:52:52 +0100 Subject: [PATCH 052/111] Update ci-rc.yml --- .github/workflows/ci-rc.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-rc.yml b/.github/workflows/ci-rc.yml index 1e059850..522be3aa 100644 --- a/.github/workflows/ci-rc.yml +++ b/.github/workflows/ci-rc.yml @@ -1,4 +1,4 @@ -name: ci +name: ci-rc on: push: branches: [develop] From 732e713eecc3ec20c299fe9649594d06148fdba8 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 17:01:06 +0100 Subject: [PATCH 053/111] Update sonar.yml --- .github/workflows/sonar.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 5ee69ba4..96fafd5a 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -4,7 +4,7 @@ on: push: branches: - main - - upgrade + - develop pull_request: types: [opened, synchronize, reopened] jobs: From 43d942ea9fb6642e9b482a1ccd6113eac9ce8108 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 20 Dec 2023 18:32:58 +0100 Subject: [PATCH 054/111] fix: property name --- src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index db5c520c..19921732 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -37,7 +37,7 @@ springdoc.swagger-ui.tagsSorter: alpha springdoc.swagger-ui.enabled=true -fr.insee.datacollectionmanagement.cors.allowedOrigin=* +fr.insee.datacollectionmanagement.cors.allowedOriginsg=* #Actuator Metrics From 5a25baafd8b9298a4a30be0cf4ea6ac17e0e316e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 21 Dec 2023 08:53:54 +0100 Subject: [PATCH 055/111] build: version 1.1.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 966efc8c..c2aa17d9 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.0 + 1.1.1 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From e29e28457b7b72524673c3b6e21f7af71ecf1bc9 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 17 Jan 2024 08:41:20 +0100 Subject: [PATCH 056/111] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c2aa17d9..d804d6c1 100644 --- a/pom.xml +++ b/pom.xml @@ -4,12 +4,12 @@ org.springframework.boot spring-boot-starter-parent - 3.2.0 + 3.2.1 fr.insee.survey platine-management - 1.1.1 + 1.1.2 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From eb95725dffab74afd3de9cca7852fe44a9a26251 Mon Sep 17 00:00:00 2001 From: Betty Becuwe <77614323+BettyB979@users.noreply.github.com> Date: Wed, 17 Jan 2024 08:47:58 +0100 Subject: [PATCH 057/111] fix: tests (#48) --- src/main/resources/application.properties | 2 +- .../datacollectionmanagement/dataloader/DataloaderTest.java | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 19921732..0e52ee54 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -37,7 +37,7 @@ springdoc.swagger-ui.tagsSorter: alpha springdoc.swagger-ui.enabled=true -fr.insee.datacollectionmanagement.cors.allowedOriginsg=* +fr.insee.datacollectionmanagement.cors.allowedOrigins=* #Actuator Metrics diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java index f1ac2b45..db45fa7c 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderTest.java @@ -32,7 +32,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; -import java.time.Year; import java.util.*; import java.util.stream.Collectors; @@ -204,7 +203,7 @@ private Contact createContact(int i) { private void initMetadata() throws ParseException { - int year = Year.now().getValue(); + int year = 2023; Owner ownerInsee = new Owner(); ownerInsee.setId("Insee"); @@ -303,7 +302,7 @@ private void initMetadata() throws ParseException { private void initQuestionning(Faker faker) { Long nbExistingQuestionings = questioningRepository.count(); - int year = Year.now().getValue(); + int year = 2023; Date today = new Date(); Questioning qu; From 3fe50aa740861ebb8ab65407d51d29102e70c6a7 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 24 Jan 2024 15:32:17 +0100 Subject: [PATCH 058/111] Update pom.xml --- pom.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pom.xml b/pom.xml index d804d6c1..ab85acab 100644 --- a/pom.xml +++ b/pom.xml @@ -99,6 +99,12 @@ com.github.javafaker javafaker ${javafaker-version} + + + org.yaml + snakeyaml + + From 6304112d5c311494be1b852606c58b43ac731375 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 25 Jan 2024 09:44:13 +0100 Subject: [PATCH 059/111] chore: spring boot 3.2.1 to 3.2.2 --- README.md | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c1892a72..db3044ff 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ REST API for communication between DB and Platine-Management UI and Platine-My-S For building and running the application you need: -- JDK 11 +- JDK 21 - Maven 3 ## Install and excute unit tests diff --git a/pom.xml b/pom.xml index ab85acab..4bd13bfd 100644 --- a/pom.xml +++ b/pom.xml @@ -4,12 +4,12 @@ org.springframework.boot spring-boot-starter-parent - 3.2.1 + 3.2.2 fr.insee.survey platine-management - 1.1.2 + 1.1.3 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From 3a5c1586add462f671a521f0e1c58d1a41d4bafa Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 7 Feb 2024 17:19:36 +0100 Subject: [PATCH 060/111] fix: use sequence strategy instead of @GeneratedValue --- pom.xml | 2 +- .../datacollectionmanagement/contact/domain/Address.java | 3 ++- .../contact/domain/ContactEvent.java | 2 +- .../metadata/domain/CampaignEvent.java | 7 ++----- .../questioning/domain/Operator.java | 3 ++- .../questioning/domain/OperatorService.java | 7 ++----- .../questioning/domain/Questioning.java | 2 +- .../questioning/domain/QuestioningAccreditation.java | 2 +- .../questioning/domain/QuestioningEvent.java | 2 +- .../questioning/domain/SurveyUnitAddress.java | 3 ++- .../user/domain/SourceAccreditation.java | 7 ++----- .../datacollectionmanagement/user/domain/UserEvent.java | 2 +- .../survey/datacollectionmanagement/view/domain/View.java | 2 +- 13 files changed, 19 insertions(+), 25 deletions(-) diff --git a/pom.xml b/pom.xml index 4bd13bfd..87b775b6 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.3 + 1.1.4 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java index 7152d0b2..ad606d07 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Address.java @@ -3,6 +3,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @@ -13,7 +14,7 @@ public class Address { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_seq") private Long id; private String streetNumber; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java index dd1d1efe..8acd1999 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/ContactEvent.java @@ -19,7 +19,7 @@ public enum ContactEventType { } @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "contact_event_seq") private Long id; private Date eventDate; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java index 4443a213..0e2686b6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/domain/CampaignEvent.java @@ -1,9 +1,6 @@ package fr.insee.survey.datacollectionmanagement.metadata.domain; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; +import jakarta.persistence.*; import lombok.*; import java.util.Date; @@ -15,7 +12,7 @@ public class CampaignEvent { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "campaign_event_seq") private Long id; @NonNull private String type; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java index 50b4c959..23ee1cb2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Operator.java @@ -3,6 +3,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @@ -13,7 +14,7 @@ public class Operator { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "operator_seq") private Long id; private String firstName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java index e0f2bd21..79f49095 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/OperatorService.java @@ -1,9 +1,6 @@ package fr.insee.survey.datacollectionmanagement.questioning.domain; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.OneToMany; +import jakarta.persistence.*; import lombok.*; import java.util.Set; @@ -14,7 +11,7 @@ public class OperatorService { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "operator_service_seq") private Long id; private String name; private String mail; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java index 9d34e72e..525f9df2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java @@ -14,7 +14,7 @@ public class Questioning { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "questioning_seq") private Long id; @NonNull diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java index 4c310bab..b7add662 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningAccreditation.java @@ -16,7 +16,7 @@ public class QuestioningAccreditation { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "questioning_accreditation_seq") private Long id; private boolean isMain; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java index 20664cb4..d7ec4f08 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java @@ -17,7 +17,7 @@ public class QuestioningEvent { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "questioning_event_seq") private Long id; private Date date; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java index c50a711b..6876dc2d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnitAddress.java @@ -2,6 +2,7 @@ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @@ -14,7 +15,7 @@ public class SurveyUnitAddress { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "survey_unit_address_seq") private Long id; private String streetNumber; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java index fbba76cd..14f90737 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/SourceAccreditation.java @@ -2,10 +2,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Source; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.OneToOne; +import jakarta.persistence.*; import lombok.*; import java.util.Date; @@ -17,7 +14,7 @@ public class SourceAccreditation { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "source_accreditation_seq") private Long id; private Date creationDate; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java index ef808a7b..178b78c4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/UserEvent.java @@ -19,7 +19,7 @@ public enum UserEventType { } @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_event_seq") private Long id; private Date eventDate; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java b/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java index 93beb648..339948d4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/view/domain/View.java @@ -19,7 +19,7 @@ public class View { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "view_seq") private Long id; @NonNull private String identifier; From ab727a9c2676f917248a1b5068a59fd6047a9c92 Mon Sep 17 00:00:00 2001 From: Eric Thuaud <58465319+EricThuaud@users.noreply.github.com> Date: Thu, 8 Feb 2024 14:25:30 +0100 Subject: [PATCH 061/111] Feat/add get surveys endpoint (#49) * chore - upgrade version * feat - impl get surveys endpoint * feat - impl get surveys endpoint * test -add test * test: add dirtiesContext... --------- Co-authored-by: Eric Thuaud Co-authored-by: y72wvh --- pom.xml | 2 +- .../constants/Constants.java | 1 + .../metadata/controller/SurveyController.java | 14 ++++++++++++-- .../metadata/controller/SurveyControllerTest.java | 10 ++++++++++ .../query/controller/MoogControllerTest.java | 2 ++ 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 4bd13bfd..87b775b6 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.3 + 1.1.4 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index f03b822b..83ca80b6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -45,6 +45,7 @@ private Constants() { public static final String API_SOURCES = "/api/sources"; public static final String API_SOURCES_ID = "/api/sources/{id}"; public static final String API_SOURCES_ID_SURVEYS = "/api/sources/{id}/surveys"; + public static final String API_SURVEYS = "/api/surveys"; public static final String API_SURVEYS_ID = "/api/surveys/{id}"; public static final String API_SURVEYS_ID_CAMPAIGNS = "/api/surveys/{id}/campaigns"; public static final String API_CAMPAIGNS = "/api/campaigns"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index ebbe7dca..765fd847 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -19,8 +19,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.*; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -51,6 +50,17 @@ public class SurveyController { private final QuestioningService questioningService; + @Operation(summary = "Search for surveys, paginated") + @GetMapping(value = Constants.API_SURVEYS, produces = "application/json") + public ResponseEntity getSurveys( + @RequestParam(defaultValue = "0") Integer page, + @RequestParam(defaultValue = "20") Integer size, + @RequestParam(defaultValue = "id") String sort) { + Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); + Page pageSurvey = surveyService.findAll(pageable); + List listSurveys = pageSurvey.stream().map(this::convertToDto).toList(); + return ResponseEntity.ok().body(new SurveyController.SurveyPage(listSurveys, pageable, pageSurvey.getTotalElements())); + } @Operation(summary = "Search for surveys by the source id") @GetMapping(value = Constants.API_SOURCES_ID_SURVEYS, produces = "application/json") public ResponseEntity> getSurveysBySource(@PathVariable("id") String id) { diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index 2f941ebe..feac4241 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -38,6 +38,16 @@ class SurveyControllerTest { private SurveyRepository surveyRepository; + @Test + void getSourcesOk() throws Exception { + JSONObject jo = new JSONObject(); + jo.put("totalElements", surveyRepository.count()); + jo.put("numberOfElements", surveyRepository.count()); + + this.mockMvc.perform(get(Constants.API_SURVEYS)).andDo(print()).andExpect(status().isOk()) + .andExpect(content().json(jo.toString(), false)); + } + @Test void getSurveyNotFound() throws Exception { String identifier = "SURVEYNOTFOUND"; diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java index f0183d35..6fa4f455 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java @@ -6,6 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; @@ -17,6 +18,7 @@ @AutoConfigureMockMvc @SpringBootTest @ActiveProfiles("test") +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) class MoogControllerTest { @Autowired From 3aca0947aa6bb259a5d8a4e0bc6e07922003110f Mon Sep 17 00:00:00 2001 From: Eric Thuaud <58465319+EricThuaud@users.noreply.github.com> Date: Mon, 12 Feb 2024 17:24:44 +0100 Subject: [PATCH 062/111] modify surveyunits get format --- pom.xml | 2 +- .../questioning/controller/SurveyUnitController.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 87b775b6..3256af46 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.4 + 1.1.5 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index ee24e5e0..799f3649 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -45,7 +45,7 @@ public class SurveyUnitController { @Operation(summary = "Search for a survey units, paginated") @GetMapping(value = Constants.API_SURVEY_UNITS, produces = "application/json") @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SurveyUnitDto.class))), + @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SurveyUnitPage.class))), @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) From 4cd4d270e9e258dd7633c2ede388567fffbac0b7 Mon Sep 17 00:00:00 2001 From: Eric Thuaud <58465319+EricThuaud@users.noreply.github.com> Date: Tue, 13 Feb 2024 16:31:48 +0100 Subject: [PATCH 063/111] Feat searchsurveys campaignspartitioningsbysurvey endpoints (#50) * feat - add get campaigns and partitionings by survey id * feat - add search surveys endpoints * fix - integrate pr review modifs --------- Co-authored-by: Eric Thuaud --- pom.xml | 2 +- .../constants/Constants.java | 4 ++++ .../controller/CampaignController.java | 15 ++++++++++++ .../metadata/controller/SurveyController.java | 15 ++++++++++++ .../dto/CampaignPartitioningsDto.java | 19 +++++++++++++++ .../metadata/repository/SurveyRepository.java | 23 +++++++++++++++---- .../metadata/service/SurveyService.java | 4 +--- .../service/impl/SurveyServiceImpl.java | 4 ++-- 8 files changed, 76 insertions(+), 10 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignPartitioningsDto.java diff --git a/pom.xml b/pom.xml index 3256af46..c657dcc9 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.5 + 1.1.6 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 83ca80b6..d5bcdc49 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -46,8 +46,12 @@ private Constants() { public static final String API_SOURCES_ID = "/api/sources/{id}"; public static final String API_SOURCES_ID_SURVEYS = "/api/sources/{id}/surveys"; public static final String API_SURVEYS = "/api/surveys"; + + public static final String API_SURVEYS_SEARCH = "/api/surveys/search"; public static final String API_SURVEYS_ID = "/api/surveys/{id}"; public static final String API_SURVEYS_ID_CAMPAIGNS = "/api/surveys/{id}/campaigns"; + + public static final String API_SURVEYS_ID_CAMPAIGNS_PARTITIONINGS = "/api/surveys/{id}/campaigns-partitionings"; public static final String API_CAMPAIGNS = "/api/campaigns"; public static final String API_CAMPAIGNS_ID = "/api/campaigns/{id}"; public static final String CAMPAIGNS_ID_ONGOING = "/campaigns/{id}/ongoing"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java index 4f09e513..2299032a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/CampaignController.java @@ -8,6 +8,7 @@ import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignDto; +import fr.insee.survey.datacollectionmanagement.metadata.dto.CampaignPartitioningsDto; import fr.insee.survey.datacollectionmanagement.metadata.dto.OnGoingDto; import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; import fr.insee.survey.datacollectionmanagement.metadata.service.SurveyService; @@ -84,6 +85,16 @@ public ResponseEntity> getCampaignsBySurvey(@PathVariable("id" } + @Operation(summary = "Search for campaigns and partitionings by the survey id") + @GetMapping(value = Constants.API_SURVEYS_ID_CAMPAIGNS_PARTITIONINGS, produces = "application/json") + public ResponseEntity> getCampaignsPartitioningsBySurvey(@PathVariable("id") String id) { + + Survey survey = surveyService.findById(id); + return ResponseEntity.ok() + .body(survey.getCampaigns().stream().map(this::convertToCampaignPartitioningsDto).toList()); + + } + @Operation(summary = "Search for a campaign by its id") @GetMapping(value = Constants.API_CAMPAIGNS_ID, produces = "application/json") @ApiResponses(value = { @@ -178,6 +189,10 @@ private CampaignDto convertToDto(Campaign campaign) { return modelmapper.map(campaign, CampaignDto.class); } + private CampaignPartitioningsDto convertToCampaignPartitioningsDto(Campaign campaign) { + return modelmapper.map(campaign, CampaignPartitioningsDto.class); + } + private Campaign convertToEntity(CampaignDto campaignDto) { return modelmapper.map(campaignDto, Campaign.class); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java index 765fd847..74dd99a5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyController.java @@ -61,6 +61,21 @@ public ResponseEntity getSurveys( List listSurveys = pageSurvey.stream().map(this::convertToDto).toList(); return ResponseEntity.ok().body(new SurveyController.SurveyPage(listSurveys, pageable, pageSurvey.getTotalElements())); } + + @Operation(summary = "Search for surveys, paginated") + @GetMapping(value = Constants.API_SURVEYS_SEARCH, produces = "application/json") + public ResponseEntity getSurveys( + @RequestParam(required = false) String idSource, + @RequestParam(required = false) Integer year, + @RequestParam(required = false) String periodicity, + @RequestParam(defaultValue = "0") Integer page, + @RequestParam(defaultValue = "20") Integer size, + @RequestParam(defaultValue = "id") String sort) { + Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); + Page pageSurvey = surveyService.findBySourceIdYearPeriodicity(pageable, idSource, year, periodicity); + List listSurveys = pageSurvey.stream().map(this::convertToDto).toList(); + return ResponseEntity.ok().body(new SurveyController.SurveyPage(listSurveys, pageable, pageSurvey.getTotalElements())); + } @Operation(summary = "Search for surveys by the source id") @GetMapping(value = Constants.API_SOURCES_ID_SURVEYS, produces = "application/json") public ResponseEntity> getSurveysBySource(@PathVariable("id") String id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignPartitioningsDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignPartitioningsDto.java new file mode 100644 index 00000000..7ba74db9 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/CampaignPartitioningsDto.java @@ -0,0 +1,19 @@ +package fr.insee.survey.datacollectionmanagement.metadata.dto; + +import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.util.List; + +@Data +public class CampaignPartitioningsDto { + + @NotBlank + private String id; + private String surveyId; + private int year; + private String campaignWording; + private PeriodEnum period; + private List partitionings; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/SurveyRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/SurveyRepository.java index 902d3274..91cd701c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/SurveyRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/repository/SurveyRepository.java @@ -1,13 +1,28 @@ package fr.insee.survey.datacollectionmanagement.metadata.repository; -import java.util.List; - +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; public interface SurveyRepository extends JpaRepository, PagingAndSortingRepository { - - List findByYear(int year); + + static final String QUERY_FIND_SURVEY = + """ + select + su.* + from + survey su + join source so + on (so.id=su.source_id) + where + (:sourceId is null or UPPER(su.source_id) = UPPER(cast( :sourceId as text))) + and (:periodicity is null or UPPER(so.periodicity) = UPPER(cast( :periodicity as text))) + and (:year is null or su.year_value = :year) + """; + @Query(nativeQuery = true, value = QUERY_FIND_SURVEY) + Page findBySourceIdYearPeriodicity(Pageable pageable, String sourceId, Integer year, String periodicity); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java index acdbb305..49ad1e7a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/SurveyService.java @@ -5,11 +5,9 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import java.util.List; - public interface SurveyService { - List findByYear(int year); + Page findBySourceIdYearPeriodicity(Pageable pageable, String sourceId, Integer year, String periodicity); Survey findById(String id); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java index 049e66e4..aa7b1ba6 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/service/impl/SurveyServiceImpl.java @@ -22,8 +22,8 @@ public class SurveyServiceImpl implements SurveyService { private final SurveyRepository surveyRepository; @Override - public List findByYear(int year) { - return surveyRepository.findByYear(year); + public Page findBySourceIdYearPeriodicity(Pageable pageable, String sourceId, Integer year, String periodicity) { + return surveyRepository.findBySourceIdYearPeriodicity(pageable,sourceId, year, periodicity); } @Override From 12449ac9a34963e8470946f8cad6a70289bedc67 Mon Sep 17 00:00:00 2001 From: Eric Thuaud Date: Thu, 15 Feb 2024 13:41:55 +0100 Subject: [PATCH 064/111] fix - add types for front to get periodicities and periods --- .../PeriodPeriodicityController.java | 45 +++++++++---------- .../metadata/dto/PeriodDto.java | 15 +++++++ .../metadata/dto/PeriodicityDto.java | 14 ++++++ 3 files changed, 50 insertions(+), 24 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodDto.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodicityDto.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java index d88ef5d3..1ccc8906 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java @@ -2,10 +2,13 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; +import fr.insee.survey.datacollectionmanagement.metadata.dto.PeriodDto; +import fr.insee.survey.datacollectionmanagement.metadata.dto.PeriodicityDto; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodicityEnum; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.extern.slf4j.Slf4j; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import org.springframework.http.ResponseEntity; @@ -13,6 +16,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Slf4j @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + "|| @AuthorizeMethodDecider.isWebClient() " @@ -22,48 +31,36 @@ public class PeriodPeriodicityController { @Operation(summary = "Search for periodicities") @GetMapping(value = Constants.API_PERIODICITIES, produces = "application/json") - public ResponseEntity getPeriodicities() { - JSONArray jsonArray = new JSONArray(); + public ResponseEntity> getPeriodicities() { + List periodicities = new ArrayList<>(); for (PeriodicityEnum periodicity : PeriodicityEnum.values()) { - JSONObject json = new JSONObject(); - json.put("key", periodicity.name()); - json.put("label", periodicity.getValue()); - jsonArray.add(json); + periodicities.add(new PeriodicityDto(periodicity.getValue(),periodicity.name())); } - return ResponseEntity.ok().body(jsonArray.toString()); + return ResponseEntity.ok().body(periodicities); } @Operation(summary = "Search for periods") @GetMapping(value = Constants.API_PERIODS, produces = "application/json") - public ResponseEntity getPeriods() { - JSONArray jsonArray = new JSONArray(); - + public ResponseEntity> getPeriods() { + List periods = new ArrayList<>(); for (PeriodEnum period : PeriodEnum.values()) { - JSONObject json = new JSONObject(); - json.put("key", period.name()); - json.put("label", period.getValue()); - json.put("period",period.getPeriod().name()); - jsonArray.add(json); + periods.add(new PeriodDto(period.getValue(),period.name(), period.getPeriod().getValue())); } - return ResponseEntity.ok().body(jsonArray.toString()); + return ResponseEntity.ok().body(periods); } @Operation(summary = "Search for periods of a periodicity") @GetMapping(value = Constants.API_PERIODICITIES_ID_PERIODS, produces = "application/json") - public ResponseEntity getPeriodsOfPeriodicity(String periodicity) { + public ResponseEntity> getPeriodsOfPeriodicity(String periodicity) { try { PeriodicityEnum.valueOf(periodicity); - JSONArray jsonArray = new JSONArray(); + List periods = new ArrayList<>(); for (PeriodEnum period : PeriodEnum.values()) { if (period.getPeriod().equals(PeriodicityEnum.valueOf(periodicity))) { - JSONObject json = new JSONObject(); - json.put("key", period.name()); - json.put("label", period.getValue()); - json.put("period",period.getPeriod().name()); - jsonArray.add(json); + periods.add(new PeriodDto(period.getValue(),period.name(), period.getPeriod().getValue())); } } - return ResponseEntity.ok().body(jsonArray.toString()); + return ResponseEntity.ok().body(periods); } catch (IllegalArgumentException e) { throw new NotFoundException("periodicity does not exist"); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodDto.java new file mode 100644 index 00000000..f8639ce8 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodDto.java @@ -0,0 +1,15 @@ +package fr.insee.survey.datacollectionmanagement.metadata.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class PeriodDto { + private String value; + private String label; + private String period; + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodicityDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodicityDto.java new file mode 100644 index 00000000..0ab5426a --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/dto/PeriodicityDto.java @@ -0,0 +1,14 @@ +package fr.insee.survey.datacollectionmanagement.metadata.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +public class PeriodicityDto { + private String value; + private String label; + +} From 4fd208cdb5305c2abdf2ac980627f3a3246fc6c4 Mon Sep 17 00:00:00 2001 From: Eric Thuaud Date: Thu, 15 Feb 2024 13:42:20 +0100 Subject: [PATCH 065/111] chore - upgrade version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c657dcc9..bb8fd7b1 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.6 + 1.1.7 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From 087a72d9e2882feaafa9097234d772c1dab04340 Mon Sep 17 00:00:00 2001 From: Eric Thuaud Date: Fri, 16 Feb 2024 20:58:42 +0100 Subject: [PATCH 066/111] fix - correct endpoint pathvariable name --- pom.xml | 2 +- .../survey/datacollectionmanagement/constants/Constants.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index bb8fd7b1..49ac983f 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.7 + 1.1.8 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index d5bcdc49..30aa75e4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -65,7 +65,7 @@ private Constants() { public static final String API_SUPPORTS = "/api/supports"; public static final String API_SUPPORTS_ID = "/api/supports/{id}"; public static final String API_PERIODICITIES = "/api/periodicities"; - public static final String API_PERIODICITIES_ID_PERIODS = "/api/periodicities/{id}/periods"; + public static final String API_PERIODICITIES_ID_PERIODS = "/api/periodicities/{periodicity}/periods"; public static final String API_PERIODS = "/api/periods"; From ae7c591e506b08c8d60c346f93f4b06f00c307db Mon Sep 17 00:00:00 2001 From: y72wvh Date: Sat, 17 Feb 2024 11:32:03 +0100 Subject: [PATCH 067/111] wip: update dataloader to init data --- .../dataloader/Dataloader.java | 2 + .../dataloader/DataloaderPoc.java | 347 ++++++++++-------- 2 files changed, 187 insertions(+), 162 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java index 625925d0..e75d8095 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/Dataloader.java @@ -6,10 +6,12 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Slf4j +@Profile("poc") @RequiredArgsConstructor public class Dataloader { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 3b13c1a1..64423ae8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -23,15 +23,12 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; -import java.security.SecureRandom; import java.util.*; import java.util.concurrent.TimeUnit; @Component -@Profile("poc") @Slf4j @RequiredArgsConstructor public class DataloaderPoc { @@ -76,7 +73,7 @@ public class DataloaderPoc { static final String NUMBERS = "0123456789"; - static SecureRandom rnd = new SecureRandom(); + static Random rnd = new Random(); @PostConstruct public void init() { @@ -84,14 +81,17 @@ public void init() { Faker faker = new Faker(); initOrder(); - initContact(faker); - initMetadata(faker); - initQuestionning(faker); - initView(); - initSurveyUnitAddressAndOperators(faker); + //initContact(faker); + initDataForOneSource(faker, "DVM",2, 'M', + 12,2, 10000); + initDataForOneSource(faker, "DVT",3, 'T', + 4,2, 10000); + } + + private void initSurveyUnitAddressAndOperators(Faker faker) { if (surveyUnitAddressRepository.count() == 0) { for (SurveyUnit su : surveyUnitRepository.findAll()) { @@ -186,9 +186,10 @@ private void initOrder() { Long nbExistingOrders = orderRepository.count(); log.info("{} orders in database", nbExistingOrders); - if (nbExistingOrders == 0) { + if (nbExistingOrders != 8) { // Creating table order log.info("loading eventorder data"); + orderRepository.deleteAll(); orderRepository .saveAndFlush(new EventOrder(Long.parseLong("8"), TypeQuestioningEvent.REFUSAL.toString(), 8)); orderRepository @@ -208,47 +209,22 @@ private void initOrder() { private void initContact(Faker faker) { List listContact = new ArrayList<>(); - List
listAddresses = new ArrayList<>(); Long nbExistingContacts = contactRepository.count(); log.info("{} contacts exist in database", nbExistingContacts); - int nbContacts = 1000000; + int nbContacts = 10000; for (Long i = nbExistingContacts; i < nbContacts; i++) { long start = System.currentTimeMillis(); - final Contact c = new Contact(); - final Address a = new Address(); - - Name n = faker.name(); - String name = n.lastName(); - String firstName = n.firstName(); - com.github.javafaker.Address fakeAddress = faker.address(); - - a.setCountryName(fakeAddress.country()); - a.setStreetNumber(fakeAddress.buildingNumber()); - a.setStreetName(fakeAddress.streetName()); - a.setZipCode(fakeAddress.zipCode()); - a.setCityName(fakeAddress.cityName()); - // addressRepository.save(a); - listAddresses.add(a); - - c.setIdentifier(randomString(7).toUpperCase()); - c.setLastName(name); - c.setFirstName(firstName); - c.setPhone(faker.phoneNumber().phoneNumber()); - c.setGender(Gender.valueOf(faker.demographic().sex())); - c.setFunction(faker.job().title()); - c.setComment(faker.beer().name()); - c.setEmail(firstName.toLowerCase() + "." + name.toLowerCase() + "@cocorico.fr"); - c.setAddress(a); + final Contact c = initOneContact(faker); listContact.add(c); if ((i + 1) % 10000 == 0) { - addressRepository.saveAll(listAddresses); + //addressRepository.saveAll(listAddresses); contactRepository.saveAll(listContact); - listAddresses = new ArrayList<>(); + //listAddresses = new ArrayList<>(); listContact = new ArrayList<>(); long end = System.currentTimeMillis(); @@ -275,9 +251,40 @@ private void initContact(Faker faker) { } - private void initMetadata(Faker faker) { + private Contact initOneContact(Faker faker) { + final Contact c = new Contact(); + final Address a = new Address(); + + Name n = faker.name(); + String name = n.lastName(); + String firstName = n.firstName(); + com.github.javafaker.Address fakeAddress = faker.address(); + + a.setCountryName(fakeAddress.country()); + a.setStreetNumber(fakeAddress.buildingNumber()); + a.setStreetName(fakeAddress.streetName()); + a.setZipCode(fakeAddress.zipCode()); + a.setCityName(fakeAddress.cityName()); + addressRepository.save(a); + //listAddresses.add(a); + + c.setIdentifier(randomString(7).toUpperCase()); + c.setLastName(name); + c.setFirstName(firstName); + c.setPhone(faker.phoneNumber().phoneNumber()); + c.setGender(Gender.valueOf(faker.demographic().sex())); + c.setFunction(faker.job().title()); + c.setComment(faker.beer().name()); + c.setEmail(firstName.toLowerCase() + "." + name.toLowerCase() + "@cocorico.fr"); + c.setAddress(a); + contactRepository.save(c); + return c; + } + + private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysBySource, char periodType, + int nbCampaignsBySource, int nbPartByCampaign, int nbQuestioningsByPart) { - int year = 2023; + int year = 2024; Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); @@ -307,107 +314,107 @@ private void initMetadata(Faker faker) { log.info("{} campaigns exist in database", campaignRepository.count()); - while (sourceRepository.count() < 10) { + // while (sourceRepository.count() < 10) { - Source source = new Source(); + Source source = new Source(); - String nameSource = "LOAD" + sourceRepository.count() + 'A'; + String nameSource = sourceName; - if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { + if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { - source.setId(nameSource); - source.setLongWording("Have you ever heard about " + nameSource + " ?"); - source.setShortWording("Source about " + nameSource); - source.setPeriodicity(PeriodicityEnum.M); - sourceRepository.save(source); - Set setSurveys = new HashSet<>(); - Integer i = rnd.nextInt(); - if (i % 2 == 0) - setSourcesInsee.add(source); - else { - setSourcesSsp.add(source); - } - - for (int j = 0; j < 4; j++) { - - Survey survey = new Survey(); - String id = nameSource + (year - j); - survey.setId(id); - survey.setYear(year - j); - survey.setLongObjectives("The purpose of this survey is to find out everything you can about " - + nameSource - + ". Your response is essential to ensure the quality and reliability of the results of this survey."); - survey.setShortObjectives("All about " + id); - survey.setCommunication("Communication around " + id); - survey.setSpecimenUrl("http://specimenUrl/" + id); - survey.setDiffusionUrl("http://diffusion/" + id); - survey.setCnisUrl("http://cnis/" + id); - survey.setNoticeUrl("http://notice/" + id); - survey.setVisaNumber(year + randomString(6).toUpperCase()); - survey.setLongWording("Survey " + nameSource + " " + (year - j)); - survey.setShortWording(id); - survey.setSampleSize(Integer.parseInt(randomNumeric(5))); - setSurveys.add(survey); - surveyRepository.save(survey); - Set setCampaigns = new HashSet<>(); - - for (int k = 0; k < 12; k++) { - Campaign campaign = new Campaign(); - int month = k + 1; - String period = month < 10 ? "M0" + month : "M" + month; - campaign.setYear(year - j); - campaign.setPeriod(PeriodEnum.valueOf(period)); - campaign.setId(nameSource + (year - j) + period); - campaign.setCampaignWording( - "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); - setCampaigns.add(campaign); - campaignRepository.save(campaign); - Set setParts = new HashSet<>(); - - for (int l = 0; l < 3; l++) { - - Partitioning part = new Partitioning(); - part.setId(nameSource + (year - j) + "M" + month + "-00" + l); - Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); - Date closingDate = faker.date().between(openingDate, dateEndOfYear); - Date returnDate = faker.date().between(openingDate, closingDate); - - part.setOpeningDate(openingDate); - part.setClosingDate(closingDate); - part.setReturnDate(returnDate); - setParts.add(part); - part.setCampaign(campaign); - partitioningRepository.save(part); - } - campaign.setSurvey(survey); - campaign.setPartitionings(setParts); - campaignRepository.save(campaign); + source.setId(nameSource); + source.setLongWording("Have you ever heard about " + nameSource + " ?"); + source.setShortWording("Source about " + nameSource); + source.setPeriodicity(PeriodicityEnum.M); + sourceRepository.save(source); + Set setSurveys = new HashSet<>(); + Integer i = rnd.nextInt(); + if (i % 2 == 0) + setSourcesInsee.add(source); + else { + setSourcesSsp.add(source); + } + for (int j = 0; j < nbSurveysBySource; j++) { + + Survey survey = new Survey(); + String id = nameSource + (year - j); + survey.setId(id); + survey.setYear(year - j); + survey.setLongObjectives("The purpose of this survey is to find out everything you can about " + + nameSource + + ". Your response is essential to ensure the quality and reliability of the results of this survey."); + survey.setShortObjectives("All about " + id); + survey.setCommunication("Communication around " + id); + survey.setSpecimenUrl("http://specimenUrl/" + id); + survey.setDiffusionUrl("http://diffusion/" + id); + survey.setCnisUrl("http://cnis/" + id); + survey.setNoticeUrl("http://notice/" + id); + survey.setVisaNumber(year + randomString(6).toUpperCase()); + survey.setLongWording("Survey " + nameSource + " " + (year - j)); + survey.setShortWording(id); + setSurveys.add(survey); + surveyRepository.save(survey); + Set setCampaigns = new HashSet<>(); + + for (int k = 0; k < nbCampaignsBySource; k++) { + Campaign campaign = new Campaign(); + int periodValue = k + 1; + String period = periodValue < 10 ? periodType + "0" + periodValue : String.valueOf(periodType + periodValue); + campaign.setYear(year - j); + campaign.setPeriod(PeriodEnum.valueOf(period)); + campaign.setId(nameSource + (year - j) + period); + campaign.setCampaignWording( + "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); + setCampaigns.add(campaign); + campaignRepository.save(campaign); + Set setParts = new HashSet<>(); + + for (int l = 0; l < nbPartByCampaign; l++) { + + Partitioning part = new Partitioning(); + part.setId(campaign.getId() + "0" + l); + Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); + Date closingDate = faker.date().between(openingDate, dateEndOfYear); + Date returnDate = faker.date().between(openingDate, closingDate); + + part.setOpeningDate(openingDate); + part.setClosingDate(closingDate); + part.setReturnDate(returnDate); + setParts.add(part); + part.setCampaign(campaign); + partitioningRepository.save(part); + initQuestionning(faker, part, nbQuestioningsByPart); } - survey.setSource(source); - survey.setCampaigns(setCampaigns); - surveyRepository.save(survey); + campaign.setSurvey(survey); + campaign.setPartitionings(setParts); + campaignRepository.save(campaign); + } - source.setSurveys(setSurveys); - sourceRepository.save(source); - ownerInsee.setSources(setSourcesInsee); - ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); - - supportInseeHdf.setSources(setSourcesSupportInsee); - supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); + survey.setSource(source); + survey.setCampaigns(setCampaigns); + surveyRepository.save(survey); } - + source.setSurveys(setSurveys); + sourceRepository.save(source); + ownerInsee.setSources(setSourcesInsee); + ownerAgri.setSources(setSourcesSsp); + ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); + + supportInseeHdf.setSources(setSourcesSupportInsee); + supportSsne.setSources(setSourcesSupportSsne); + supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); } + //} + } - private void initQuestionning(Faker faker) { + private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings) { - Long nbExistingQuestionings = questioningRepository.count(); + //Long nbExistingQuestionings = questioningRepository.count(); - log.info("{} questionings exist in database", nbExistingQuestionings); + //log.info("{} questionings exist in database", nbExistingQuestionings); long start = System.currentTimeMillis(); Questioning qu; @@ -419,7 +426,7 @@ private void initQuestionning(Faker faker) { log.info("{} survey units exist in database", surveyUnitRepository.count()); - for (Long i = surveyUnitRepository.count(); i < 500000; i++) { + for (int i = 0; i < nbQuestionings; i++) { SurveyUnit su = new SurveyUnit(); fakeSiren = randomNumeric(9); @@ -428,17 +435,14 @@ private void initQuestionning(Faker faker) { su.setIdentificationCode(fakeSiren); surveyUnitRepository.save(su); - } - for (Long i = nbExistingQuestionings; i < 500000; i++) { qu = new Questioning(); qe = new QuestioningEvent(); List qeList = new ArrayList<>(); questioningAccreditations = new HashSet<>(); setQuestioning = new HashSet<>(); - qu.setModelName("m" + randomNumeric(2)); - qu.setIdPartitioning(partitioningRepository.findRandomPartitioning().getId()); - SurveyUnit su = surveyUnitRepository.findRandomSurveyUnit(); + qu.setModelName("m"+randomNumeric(2)); + qu.setIdPartitioning(part.getId()); qu.setSurveyUnit(su); questioningRepository.save(qu); setQuestioning.add(qu); @@ -446,8 +450,7 @@ private void initQuestionning(Faker faker) { // questioning events // everybody in INITLA - Optional part = partitioningRepository.findById(qu.getIdPartitioning()); - Date eventDate = faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()); + Date eventDate = faker.date().between(part.getOpeningDate(), part.getClosingDate()); qe.setType(TypeQuestioningEvent.INITLA); qe.setDate(eventDate); qe.setQuestioning(qu); @@ -458,47 +461,47 @@ private void initQuestionning(Faker faker) { switch (qeProfile) { case 0: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.REFUSAL, qu)); break; case 1: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PND, qu)); break; case 2: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); break; case 3, 4: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; case 5, 6, 7: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; default: qeList.add(new QuestioningEvent( - faker.date().between(part.get().getOpeningDate(), part.get().getClosingDate()), + faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); break; @@ -506,18 +509,29 @@ private void initQuestionning(Faker faker) { qeList.stream().forEach(questioningEventRepository::save); - for (int j = 0; j < 4; j++) { - accreditation = new QuestioningAccreditation(); - accreditation.setIdContact(contactRepository.findRandomIdentifierContact()); - accreditation.setQuestioning(qu); - questioningAccreditations.add(accreditation); - questioningAccreditationRepository.save(accreditation); + //for (int j = 0; j < 4; j++) { + accreditation = new QuestioningAccreditation(); + accreditation.setIdContact(initOneContact(faker).getIdentifier()); + accreditation.setQuestioning(qu); + + + if (i % 300 == 0) { + QuestioningAccreditation accreditation2 = new QuestioningAccreditation(); + accreditation2.setIdContact(contactRepository.findRandomIdentifierContact()); + accreditation2.setQuestioning(qu); + questioningAccreditations.add(accreditation2); + } + + questioningAccreditations.add(accreditation); + questioningAccreditationRepository.save(accreditation); + initOneView(accreditation); + // } qu.setQuestioningAccreditations(questioningAccreditations); questioningRepository.save(qu); - if (i % 100 == 0) { + if (i % 10000 == 0) { long end = System.currentTimeMillis(); - log.info("It took {}ms to execute save() for 100 questionings.", (end - start)); + log.info("It took {}ms to execute save() for 10000 questionings.", (end - start)); start = System.currentTimeMillis(); } @@ -530,12 +544,7 @@ private void initView() { List listAccreditations = questioningAccreditationRepository.findAll(); listAccreditations.stream().forEach(a -> { - Partitioning p = partitioningRepository.findById(a.getQuestioning().getIdPartitioning()).orElse(null); - View view = new View(); - view.setIdentifier(contactRepository.findById(a.getIdContact()).orElse(null).getIdentifier()); - view.setCampaignId(p.getCampaign().getId()); - view.setIdSu(a.getQuestioning().getSurveyUnit().getIdSu()); - viewRepository.save(view); + initOneView(a); }); Iterable listContacts = contactRepository.findAll(); @@ -550,6 +559,15 @@ private void initView() { } } + private void initOneView(QuestioningAccreditation a) { + Partitioning p = partitioningRepository.findById(a.getQuestioning().getIdPartitioning()).orElse(null); + View view = new View(); + view.setIdentifier(contactRepository.findById(a.getIdContact()).orElse(null).getIdentifier()); + view.setCampaignId(p.getCampaign().getId()); + view.setIdSu(a.getQuestioning().getSurveyUnit().getIdSu()); + viewRepository.save(view); + } + String randomString(int len) { StringBuilder sb = new StringBuilder(len); @@ -561,9 +579,14 @@ String randomString(int len) { String randomNumeric(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) - sb.append(NUMBERS.charAt(rnd.nextInt(AB.length()))); + sb.append(NUMBERS.charAt(rnd.nextInt(NUMBERS.length()))); return sb.toString(); } + public int getRandomNumber(int min, int max) { + Random random = new Random(); + return random.nextInt(max - min) + min; + } + } From e452411535c5b3fab4eb8cc1efa96c3369b8b91e Mon Sep 17 00:00:00 2001 From: Eric Thuaud <58465319+EricThuaud@users.noreply.github.com> Date: Tue, 20 Feb 2024 08:58:00 +0100 Subject: [PATCH 068/111] Feat improve user model endpoints (#51) * fix - improve user model and userDto * feat - adda accredited sources to user dto * build - upgrade version * fix - correct periodicity endpoint semantics response * fix - fix tests enum * fix - fix tests enum * fix - fix tests enum --------- Co-authored-by: Eric Thuaud --- pom.xml | 2 +- .../controller/PeriodPeriodicityController.java | 6 +++--- .../user/controller/UserController.java | 10 +++++++--- .../datacollectionmanagement/user/domain/User.java | 8 +++++++- .../datacollectionmanagement/user/dto/UserDto.java | 10 ++++++++++ 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 49ac983f..b4007d31 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.8 + 1.1.9 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java index 1ccc8906..82a84141 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java @@ -34,7 +34,7 @@ public class PeriodPeriodicityController { public ResponseEntity> getPeriodicities() { List periodicities = new ArrayList<>(); for (PeriodicityEnum periodicity : PeriodicityEnum.values()) { - periodicities.add(new PeriodicityDto(periodicity.getValue(),periodicity.name())); + periodicities.add(new PeriodicityDto(periodicity.name(),periodicity.getValue())); } return ResponseEntity.ok().body(periodicities); } @@ -44,7 +44,7 @@ public ResponseEntity> getPeriodicities() { public ResponseEntity> getPeriods() { List periods = new ArrayList<>(); for (PeriodEnum period : PeriodEnum.values()) { - periods.add(new PeriodDto(period.getValue(),period.name(), period.getPeriod().getValue())); + periods.add(new PeriodDto(period.name(), period.getValue(), period.getPeriod().getValue())); } return ResponseEntity.ok().body(periods); } @@ -57,7 +57,7 @@ public ResponseEntity> getPeriodsOfPeriodicity(String periodicit List periods = new ArrayList<>(); for (PeriodEnum period : PeriodEnum.values()) { if (period.getPeriod().equals(PeriodicityEnum.valueOf(periodicity))) { - periods.add(new PeriodDto(period.getValue(),period.name(), period.getPeriod().getValue())); + periods.add(new PeriodDto(period.name(), period.getValue(),period.getPeriod().getValue())); } } return ResponseEntity.ok().body(periods); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 8eaf3e04..3b51f6d1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -160,7 +160,7 @@ private User convertToEntity(UserDto userDto) throws ParseException { User oldUser = userService.findByIdentifier(userDto.getIdentifier()); User user = modelMapper.map(userDto, User.class); - user.setRole(User.UserRoleType.valueOf(userDto.getRole().toUpperCase())); + user.setRole(User.UserRoleType.valueOf(userDto.getRole())); user.setUserEvents(oldUser.getUserEvents()); return user; @@ -168,12 +168,16 @@ private User convertToEntity(UserDto userDto) throws ParseException { private User convertToEntityNewUser(UserDto userDto) { User user = modelMapper.map(userDto, User.class); - user.setRole(User.UserRoleType.valueOf(userDto.getRole().toUpperCase())); + user.setRole(User.UserRoleType.valueOf(userDto.getRole())); return user; } private UserDto convertToDto(User user) { - return modelMapper.map(user, UserDto.class); + + List accreditedSources = userService.findAccreditedSources(user.getIdentifier()); + UserDto userDto= modelMapper.map(user, UserDto.class); + userDto.setAccreditedSources(accreditedSources); + return userDto; } class UserPage extends PageImpl { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java index a674fe6d..102d04aa 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/domain/User.java @@ -6,6 +6,7 @@ import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; +import java.util.Date; import java.util.Set; @Entity @@ -15,12 +16,17 @@ public class User { public enum UserRoleType { - RESPONSABLE, GESTIONNAIRE, ASSISTANCE + ADMINISTRATEUR, RESPONSABLE, GESTIONNAIRE, ASSISTANCE } @Id private String identifier; + private String name; + private String firstName; + private String organization; + private Date creationDate; + private String creationAuthor; @JdbcTypeCode(SqlTypes.INTEGER) @Enumerated(EnumType.ORDINAL) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java index 7f23d455..5697fee1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/dto/UserDto.java @@ -6,6 +6,9 @@ import lombok.Getter; import lombok.Setter; +import java.util.Date; +import java.util.List; + @Getter @Setter public class UserDto{ @@ -13,6 +16,13 @@ public class UserDto{ private String identifier; @UserRoleValid private String role; + private String name; + private String firstName; + private String organization; + private List accreditedSources; + private Date creationDate; + private String creationAuthor; + } From bfcbef269ffa84195f47123e12c39c5ed284f1e4 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 08:38:26 +0100 Subject: [PATCH 069/111] fix: add indexes --- .../datacollectionmanagement/contact/domain/Contact.java | 4 +++- .../questioning/domain/Questioning.java | 4 +++- .../questioning/domain/QuestioningEvent.java | 3 +++ .../questioning/domain/SurveyUnit.java | 4 +++- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java index 1f8ae525..391cd7b0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java @@ -10,7 +10,9 @@ @Table(indexes = { @Index(name = "fn_index", columnList = "firstName"), @Index(name = "ln_index", columnList = "lastName"), @Index(name = "lnfn_index", columnList = "lastName, firstName"), - @Index(name = "email_index", columnList = "email") + @Index(name = "email_index", columnList = "email"), + @Index(name = "contactAddress_index", columnList = "address_id") + }) @Getter @Setter diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java index 525f9df2..28d37a24 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/Questioning.java @@ -9,7 +9,9 @@ @Getter @Setter@NoArgsConstructor @Table(indexes = { - @Index(name = "idPartitioning_index", columnList = "idPartitioning") + @Index(name = "idPartitioning_index", columnList = "idPartitioning"), + @Index(name = "surveyUnitId_index", columnList = "survey_unit_id_su") + }) public class Questioning { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java index d7ec4f08..aac2ce8f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/QuestioningEvent.java @@ -14,6 +14,9 @@ @Entity @Getter @Setter +@Table(indexes = { + @Index(name = "idQuestioning_index", columnList = "questioning_id") +}) public class QuestioningEvent { @Id diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java index 97f8aa66..a9059796 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/domain/SurveyUnit.java @@ -10,7 +10,9 @@ @Getter @Setter @Table(indexes = { - @Index(name = "identificationName_index", columnList = "identificationName"), @Index(name = "identificationCode_index", columnList = "identificationCode") + @Index(name = "identificationName_index", columnList = "identificationName"), + @Index(name = "identificationCode_index", columnList = "identificationCode"), + @Index(name = "surveyUnitAddress_index", columnList = "survey_unit_address_id") }) public class SurveyUnit { From a8e410258b6ec409e8924a1a20b4aee2e856c7c1 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 08:38:45 +0100 Subject: [PATCH 070/111] feat: dataloader for DV --- .../dataloader/DataloaderPoc.java | 187 ++++++++++-------- 1 file changed, 102 insertions(+), 85 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 64423ae8..9ff4ff87 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -22,7 +22,6 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.util.*; @@ -82,16 +81,14 @@ public void init() { initOrder(); //initContact(faker); - initDataForOneSource(faker, "DVM",2, 'M', - 12,2, 10000); - initDataForOneSource(faker, "DVT",3, 'T', - 4,2, 10000); - + initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 2000); + initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 10000); + initDataForOneSource(faker, "DVA", 2, PeriodicityEnum.A, 1, 2, 80000); + initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 10000); } - private void initSurveyUnitAddressAndOperators(Faker faker) { if (surveyUnitAddressRepository.count() == 0) { for (SurveyUnit su : surveyUnitRepository.findAll()) { @@ -281,10 +278,10 @@ private Contact initOneContact(Faker faker) { return c; } - private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysBySource, char periodType, + private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysBySource, PeriodicityEnum periodicity, int nbCampaignsBySource, int nbPartByCampaign, int nbQuestioningsByPart) { - int year = 2024; + int year = Calendar.getInstance().get(Calendar.YEAR); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); @@ -320,53 +317,66 @@ private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysB String nameSource = sourceName; - if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { - - source.setId(nameSource); - source.setLongWording("Have you ever heard about " + nameSource + " ?"); - source.setShortWording("Source about " + nameSource); - source.setPeriodicity(PeriodicityEnum.M); - sourceRepository.save(source); - Set setSurveys = new HashSet<>(); - Integer i = rnd.nextInt(); - if (i % 2 == 0) - setSourcesInsee.add(source); - else { - setSourcesSsp.add(source); - } + /* if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) {*/ + + source.setId(nameSource); + source.setLongWording("Have you ever heard about " + nameSource + " ?"); + source.setShortWording("Source about " + nameSource); + source.setPeriodicity(periodicity); + source.setMandatoryMySurveys(false); + + sourceRepository.save(source); + Set setSurveys = new HashSet<>(); + Integer i = rnd.nextInt(); + if (i % 2 == 0) { + setSourcesInsee.add(source); + source.setOwner(ownerInsee); + setSourcesSupportInsee.add(source); + source.setSupport(supportInseeHdf); + } + else { + setSourcesSsp.add(source); + source.setOwner(ownerAgri); + setSourcesSupportSsne.add(source); + source.setSupport(supportSsne); + } + + for (int j = 0; j < nbSurveysBySource; j++) { + + Survey survey = new Survey(); + String id = nameSource + (year - j); + survey.setId(id); + survey.setYear(year - j); + survey.setLongObjectives("The purpose of this survey is to find out everything you can about " + + nameSource + + ". Your response is essential to ensure the quality and reliability of the results of this survey."); + survey.setShortObjectives("All about " + id); + survey.setCommunication("Communication around " + id); + survey.setSpecimenUrl("http://specimenUrl/" + id); + survey.setDiffusionUrl("http://diffusion/" + id); + survey.setCnisUrl("http://cnis/" + id); + survey.setNoticeUrl("http://notice/" + id); + survey.setVisaNumber(year + randomString(6).toUpperCase()); + survey.setLongWording("Survey " + nameSource + " " + (year - j)); + survey.setShortWording(id); + setSurveys.add(survey); + surveyRepository.save(survey); + Set setCampaigns = new HashSet<>(); + + for (int k = 0; k < nbCampaignsBySource; k++) { + + Campaign campaign = new Campaign(); + int periodValue = k + 1; + String period = periodValue < 10 ? periodicity + "0" + periodValue : periodicity + String.valueOf(periodValue); + campaign.setYear(year - j); + campaign.setPeriod(PeriodEnum.valueOf(period)); + String idampaign = nameSource + (year - j) + period; + campaign.setId(idampaign); + campaign.setCampaignWording( + "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); + + if (campaignRepository.findById(idampaign).isEmpty()) { - for (int j = 0; j < nbSurveysBySource; j++) { - - Survey survey = new Survey(); - String id = nameSource + (year - j); - survey.setId(id); - survey.setYear(year - j); - survey.setLongObjectives("The purpose of this survey is to find out everything you can about " - + nameSource - + ". Your response is essential to ensure the quality and reliability of the results of this survey."); - survey.setShortObjectives("All about " + id); - survey.setCommunication("Communication around " + id); - survey.setSpecimenUrl("http://specimenUrl/" + id); - survey.setDiffusionUrl("http://diffusion/" + id); - survey.setCnisUrl("http://cnis/" + id); - survey.setNoticeUrl("http://notice/" + id); - survey.setVisaNumber(year + randomString(6).toUpperCase()); - survey.setLongWording("Survey " + nameSource + " " + (year - j)); - survey.setShortWording(id); - setSurveys.add(survey); - surveyRepository.save(survey); - Set setCampaigns = new HashSet<>(); - - for (int k = 0; k < nbCampaignsBySource; k++) { - Campaign campaign = new Campaign(); - int periodValue = k + 1; - String period = periodValue < 10 ? periodType + "0" + periodValue : String.valueOf(periodType + periodValue); - campaign.setYear(year - j); - campaign.setPeriod(PeriodEnum.valueOf(period)); - campaign.setId(nameSource + (year - j) + period); - campaign.setCampaignWording( - "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); - setCampaigns.add(campaign); campaignRepository.save(campaign); Set setParts = new HashSet<>(); @@ -388,28 +398,32 @@ private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysB } campaign.setSurvey(survey); campaign.setPartitionings(setParts); + setCampaigns.add(campaign); campaignRepository.save(campaign); - } - survey.setSource(source); - survey.setCampaigns(setCampaigns); - surveyRepository.save(survey); + } - source.setSurveys(setSurveys); - sourceRepository.save(source); - ownerInsee.setSources(setSourcesInsee); - ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); - - supportInseeHdf.setSources(setSourcesSupportInsee); - supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); + survey.setSource(source); + survey.setCampaigns(setCampaigns); + surveyRepository.save(survey); } + source.setSurveys(setSurveys); + source.setSurveys(setSurveys); - //} + sourceRepository.save(source); + ownerInsee.setSources(setSourcesInsee); + ownerAgri.setSources(setSourcesSsp); + ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); + supportInseeHdf.setSources(setSourcesSupportInsee); + supportSsne.setSources(setSourcesSupportSsne); + supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); } + //} + + //} + private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings) { //Long nbExistingQuestionings = questioningRepository.count(); @@ -437,11 +451,11 @@ private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings qu = new Questioning(); qe = new QuestioningEvent(); - List qeList = new ArrayList<>(); + Set questioningEvents = new HashSet<>(); questioningAccreditations = new HashSet<>(); setQuestioning = new HashSet<>(); - qu.setModelName("m"+randomNumeric(2)); + qu.setModelName("m" + randomNumeric(2)); qu.setIdPartitioning(part.getId()); qu.setSurveyUnit(su); questioningRepository.save(qu); @@ -454,72 +468,74 @@ private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings qe.setType(TypeQuestioningEvent.INITLA); qe.setDate(eventDate); qe.setQuestioning(qu); - qeList.add(qe); + questioningEvents.add(qe); int qeProfile = rnd.nextInt(10); switch (qeProfile) { case 0: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.REFUSAL, qu)); break; case 1: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PND, qu)); break; case 2: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); break; case 3, 4: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.FOLLOWUP, qu)); - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; case 5, 6, 7: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.VALINT, qu)); break; default: - qeList.add(new QuestioningEvent( + questioningEvents.add(new QuestioningEvent( faker.date().between(part.getOpeningDate(), part.getClosingDate()), TypeQuestioningEvent.PARTIELINT, qu)); break; } - qeList.stream().forEach(questioningEventRepository::save); + questioningEvents.stream().forEach(questioningEventRepository::save); //for (int j = 0; j < 4; j++) { accreditation = new QuestioningAccreditation(); accreditation.setIdContact(initOneContact(faker).getIdentifier()); accreditation.setQuestioning(qu); + int randomDoubleContact = rnd.nextInt(300); - if (i % 300 == 0) { + if (randomDoubleContact == 1) { QuestioningAccreditation accreditation2 = new QuestioningAccreditation(); accreditation2.setIdContact(contactRepository.findRandomIdentifierContact()); accreditation2.setQuestioning(qu); questioningAccreditations.add(accreditation2); + initOneView(accreditation); } @@ -527,6 +543,7 @@ private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings questioningAccreditationRepository.save(accreditation); initOneView(accreditation); // } + qu.setQuestioningEvents(questioningEvents); qu.setQuestioningAccreditations(questioningAccreditations); questioningRepository.save(qu); if (i % 10000 == 0) { From 7eb7f6f2a25dec9671af16885fe4eea0b0400400 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 09:14:33 +0100 Subject: [PATCH 071/111] fix:: add demo profile --- .../datacollectionmanagement/dataloader/DataloaderPoc.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 9ff4ff87..f8d95a49 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -22,6 +22,7 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.util.*; @@ -29,6 +30,7 @@ @Component @Slf4j +@Profile("demo") @RequiredArgsConstructor public class DataloaderPoc { From d4281b02300dd054459d6ca3bfb3f3c1affff1da Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 10:09:06 +0100 Subject: [PATCH 072/111] Update DataloaderPoc.java --- .../datacollectionmanagement/dataloader/DataloaderPoc.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index f8d95a49..e3c25b59 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -30,7 +30,6 @@ @Component @Slf4j -@Profile("demo") @RequiredArgsConstructor public class DataloaderPoc { @@ -292,12 +291,12 @@ private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysB Date dateEndOfYear = calendar.getTime(); Owner ownerInsee = new Owner(); - ownerInsee.setId("insee"); + ownerInsee.setId("insee"+sourceName); ownerInsee.setLabel("Insee"); Set setSourcesInsee = new HashSet<>(); Owner ownerAgri = new Owner(); - ownerAgri.setId("agri"); + ownerAgri.setId("agri"+sourceName); ownerAgri.setLabel("SSM Agriculture"); Set setSourcesSsp = new HashSet<>(); From fa86b786fef7af394e02431cfca2e4d598a69c44 Mon Sep 17 00:00:00 2001 From: Eric Thuaud <58465319+EricThuaud@users.noreply.github.com> Date: Wed, 21 Feb 2024 10:40:41 +0100 Subject: [PATCH 073/111] Feat add users endpoint without pagination (#52) * build - upgrade version * feat - add get users without pagination --------- Co-authored-by: Eric Thuaud --- pom.xml | 2 +- .../constants/Constants.java | 2 ++ .../user/controller/UserController.java | 12 ++++++++++++ .../user/service/UserService.java | 2 ++ .../user/service/impl/UserServiceImpl.java | 5 +++++ 5 files changed, 22 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b4007d31..610a703a 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.insee.survey platine-management - 1.1.9 + 1.1.10 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 30aa75e4..b43c1a74 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -20,6 +20,8 @@ private Constants() { // API USER DOMAIN public static final String API_USERS_ALL = "/api/users"; + + public static final String API_USERS_ALL_NO_PAGINATION ="/api/users/v2" ; public static final String API_USERS_ID = "/api/users/{id}"; public static final String API_USERS_ID_USEREVENTS = "/api/users/{id}/user-events"; public static final String API_USEREVENTS = "/api/users/contact-events"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java index 3b51f6d1..1e86beb0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/controller/UserController.java @@ -11,6 +11,7 @@ import fr.insee.survey.datacollectionmanagement.user.service.SourceAccreditationService; import fr.insee.survey.datacollectionmanagement.user.service.UserService; import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; @@ -67,6 +68,17 @@ public ResponseEntity getUsers( return ResponseEntity.ok().body(new UserController.UserPage(listC, pageable, pageC.getTotalElements())); } + @Operation(summary = "Search for users, without pagination") + @GetMapping(value = Constants.API_USERS_ALL_NO_PAGINATION, produces = "application/json") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = UserDto.class )))) + }) + public ResponseEntity getUsersNotPaginated() { + List users = userService.findAll(); + List listUsers = users.stream().map(this::convertToDto).toList(); + return ResponseEntity.ok().body(listUsers); + } + @Operation(summary = "Search for a user by its id") @GetMapping(value = Constants.API_USERS_ID, produces = "application/json") public ResponseEntity getUser(@PathVariable("id") String id) { diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java index 8e8804c6..54b7e33c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/UserService.java @@ -21,6 +21,8 @@ public interface UserService { */ public Page findAll(Pageable pageable); + public List findAll(); + /** * Find a user by its identifier. * diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java index 88d9053b..c18071bd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/user/service/impl/UserServiceImpl.java @@ -32,6 +32,11 @@ public Page findAll(Pageable pageable) { return userRepository.findAll(pageable); } + @Override + public List findAll() { + return userRepository.findAll(); + } + @Override public User findByIdentifier(String identifier) { return userRepository.findByIdentifierIgnoreCase(identifier).orElseThrow(()-> new NotFoundException(String.format("User %s not found", identifier))); From 993b724c7a7caba9a4da67920abdf706e14ff847 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 10:48:28 +0100 Subject: [PATCH 074/111] Update DataloaderPoc.java --- .../datacollectionmanagement/dataloader/DataloaderPoc.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index e3c25b59..f7a32bae 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -22,7 +22,6 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.util.*; From b762de1fbe273d006f336eccfbf00fe04e780f38 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 11:12:24 +0100 Subject: [PATCH 075/111] Update DataloaderPoc.java --- .../dataloader/DataloaderPoc.java | 208 +++++++++--------- 1 file changed, 103 insertions(+), 105 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index f7a32bae..1e944a33 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -22,6 +22,7 @@ import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.util.*; @@ -82,10 +83,10 @@ public void init() { initOrder(); //initContact(faker); - initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 2000); - initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 10000); - initDataForOneSource(faker, "DVA", 2, PeriodicityEnum.A, 1, 2, 80000); - initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 10000); + initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 1); + initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 1); + initDataForOneSource(faker, "DVA", 2, PeriodicityEnum.A, 1, 2, 1); + initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 1); } @@ -290,15 +291,16 @@ private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysB Date dateEndOfYear = calendar.getTime(); Owner ownerInsee = new Owner(); - ownerInsee.setId("insee"+sourceName); + ownerInsee.setId("insee"); ownerInsee.setLabel("Insee"); Set setSourcesInsee = new HashSet<>(); Owner ownerAgri = new Owner(); - ownerAgri.setId("agri"+sourceName); + ownerAgri.setId("agri"); ownerAgri.setLabel("SSM Agriculture"); Set setSourcesSsp = new HashSet<>(); + Support supportInseeHdf = new Support(); supportInseeHdf.setId("inseehdf"); supportInseeHdf.setLabel("Insee Hauts-de-France"); @@ -317,113 +319,109 @@ private void initDataForOneSource(Faker faker, String sourceName, int nbSurveysB String nameSource = sourceName; - /* if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) {*/ - - source.setId(nameSource); - source.setLongWording("Have you ever heard about " + nameSource + " ?"); - source.setShortWording("Source about " + nameSource); - source.setPeriodicity(periodicity); - source.setMandatoryMySurveys(false); - - sourceRepository.save(source); - Set setSurveys = new HashSet<>(); - Integer i = rnd.nextInt(); - if (i % 2 == 0) { - setSourcesInsee.add(source); - source.setOwner(ownerInsee); - setSourcesSupportInsee.add(source); - source.setSupport(supportInseeHdf); - } - else { - setSourcesSsp.add(source); - source.setOwner(ownerAgri); - setSourcesSupportSsne.add(source); - source.setSupport(supportSsne); - } + if (!StringUtils.contains(nameSource, " ") && sourceRepository.findById(nameSource).isEmpty()) { + + source.setId(nameSource); + source.setLongWording("Have you ever heard about " + nameSource + " ?"); + source.setShortWording("Source about " + nameSource); + source.setPeriodicity(periodicity); + source.setMandatoryMySurveys(false); + + sourceRepository.save(source); + Set setSurveys = new HashSet<>(); + Integer i = rnd.nextInt(); + if (i % 2 == 0) { + setSourcesInsee.add(source); + source.setOwner(ownerInsee); + setSourcesSupportInsee.add(source); + source.setSupport(supportInseeHdf); + } else { + setSourcesSsp.add(source); + source.setOwner(ownerAgri); + setSourcesSupportSsne.add(source); + source.setSupport(supportSsne); + } - for (int j = 0; j < nbSurveysBySource; j++) { - - Survey survey = new Survey(); - String id = nameSource + (year - j); - survey.setId(id); - survey.setYear(year - j); - survey.setLongObjectives("The purpose of this survey is to find out everything you can about " - + nameSource - + ". Your response is essential to ensure the quality and reliability of the results of this survey."); - survey.setShortObjectives("All about " + id); - survey.setCommunication("Communication around " + id); - survey.setSpecimenUrl("http://specimenUrl/" + id); - survey.setDiffusionUrl("http://diffusion/" + id); - survey.setCnisUrl("http://cnis/" + id); - survey.setNoticeUrl("http://notice/" + id); - survey.setVisaNumber(year + randomString(6).toUpperCase()); - survey.setLongWording("Survey " + nameSource + " " + (year - j)); - survey.setShortWording(id); - setSurveys.add(survey); - surveyRepository.save(survey); - Set setCampaigns = new HashSet<>(); - - for (int k = 0; k < nbCampaignsBySource; k++) { - - Campaign campaign = new Campaign(); - int periodValue = k + 1; - String period = periodValue < 10 ? periodicity + "0" + periodValue : periodicity + String.valueOf(periodValue); - campaign.setYear(year - j); - campaign.setPeriod(PeriodEnum.valueOf(period)); - String idampaign = nameSource + (year - j) + period; - campaign.setId(idampaign); - campaign.setCampaignWording( - "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); - - if (campaignRepository.findById(idampaign).isEmpty()) { - - campaignRepository.save(campaign); - Set setParts = new HashSet<>(); - - for (int l = 0; l < nbPartByCampaign; l++) { - - Partitioning part = new Partitioning(); - part.setId(campaign.getId() + "0" + l); - Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); - Date closingDate = faker.date().between(openingDate, dateEndOfYear); - Date returnDate = faker.date().between(openingDate, closingDate); - - part.setOpeningDate(openingDate); - part.setClosingDate(closingDate); - part.setReturnDate(returnDate); - setParts.add(part); - part.setCampaign(campaign); - partitioningRepository.save(part); - initQuestionning(faker, part, nbQuestioningsByPart); + for (int j = 0; j < nbSurveysBySource; j++) { + + Survey survey = new Survey(); + String id = nameSource + (year - j); + survey.setId(id); + survey.setYear(year - j); + survey.setLongObjectives("The purpose of this survey is to find out everything you can about " + + nameSource + + ". Your response is essential to ensure the quality and reliability of the results of this survey."); + survey.setShortObjectives("All about " + id); + survey.setCommunication("Communication around " + id); + survey.setSpecimenUrl("http://specimenUrl/" + id); + survey.setDiffusionUrl("http://diffusion/" + id); + survey.setCnisUrl("http://cnis/" + id); + survey.setNoticeUrl("http://notice/" + id); + survey.setVisaNumber(year + randomString(6).toUpperCase()); + survey.setLongWording("Survey " + nameSource + " " + (year - j)); + survey.setShortWording(id); + setSurveys.add(survey); + surveyRepository.save(survey); + Set setCampaigns = new HashSet<>(); + + for (int k = 0; k < nbCampaignsBySource; k++) { + + Campaign campaign = new Campaign(); + int periodValue = k + 1; + String period = periodValue < 10 ? periodicity + "0" + periodValue : periodicity + String.valueOf(periodValue); + campaign.setYear(year - j); + campaign.setPeriod(PeriodEnum.valueOf(period)); + String idampaign = nameSource + (year - j) + period; + campaign.setId(idampaign); + campaign.setCampaignWording( + "Campaign about " + nameSource + " in " + (year - j) + " and period " + period); + + if (campaignRepository.findById(idampaign).isEmpty()) { + + campaignRepository.save(campaign); + Set setParts = new HashSet<>(); + + for (int l = 0; l < nbPartByCampaign; l++) { + + Partitioning part = new Partitioning(); + part.setId(campaign.getId() + "0" + l); + Date openingDate = faker.date().past(90, 0, TimeUnit.DAYS); + Date closingDate = faker.date().between(openingDate, dateEndOfYear); + Date returnDate = faker.date().between(openingDate, closingDate); + + part.setOpeningDate(openingDate); + part.setClosingDate(closingDate); + part.setReturnDate(returnDate); + setParts.add(part); + part.setCampaign(campaign); + partitioningRepository.save(part); + initQuestionning(faker, part, nbQuestioningsByPart); + } + campaign.setSurvey(survey); + campaign.setPartitionings(setParts); + setCampaigns.add(campaign); + campaignRepository.save(campaign); } - campaign.setSurvey(survey); - campaign.setPartitionings(setParts); - setCampaigns.add(campaign); - campaignRepository.save(campaign); - } + } + survey.setSource(source); + survey.setCampaigns(setCampaigns); + surveyRepository.save(survey); } - survey.setSource(source); - survey.setCampaigns(setCampaigns); - surveyRepository.save(survey); - } - source.setSurveys(setSurveys); - source.setSurveys(setSurveys); + source.setSurveys(setSurveys); + source.setSurveys(setSurveys); - sourceRepository.save(source); - ownerInsee.setSources(setSourcesInsee); - ownerAgri.setSources(setSourcesSsp); - ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); + sourceRepository.save(source); + ownerInsee.setSources(setSourcesInsee); + ownerAgri.setSources(setSourcesSsp); + ownerRepository.saveAll(Arrays.asList(ownerInsee, ownerAgri)); - supportInseeHdf.setSources(setSourcesSupportInsee); - supportSsne.setSources(setSourcesSupportSsne); - supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); + supportInseeHdf.setSources(setSourcesSupportInsee); + supportSsne.setSources(setSourcesSupportSsne); + supportRepository.saveAll(Arrays.asList(supportInseeHdf, supportSsne)); + } } - //} - - //} - private void initQuestionning(Faker faker, Partitioning part, int nbQuestionings) { //Long nbExistingQuestionings = questioningRepository.count(); From 96a955a8f1feeadbd7b8daacf4bc09b875a997d9 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 11:29:07 +0100 Subject: [PATCH 076/111] Update DataloaderPoc.java --- .../datacollectionmanagement/dataloader/DataloaderPoc.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 1e944a33..ac964596 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -85,7 +85,7 @@ public void init() { initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 1); initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 1); - initDataForOneSource(faker, "DVA", 2, PeriodicityEnum.A, 1, 2, 1); + initDataForOneSource(faker, "DVX", 2, PeriodicityEnum.X, 1, 2, 1); initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 1); } From a866a4b2537bc2eca7fac2d3bdd4f819ff838184 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 21 Feb 2024 11:54:22 +0100 Subject: [PATCH 077/111] Update DataloaderPoc.java --- .../dataloader/DataloaderPoc.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index ac964596..a94d5d1f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -83,10 +83,10 @@ public void init() { initOrder(); //initContact(faker); - initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 1); - initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 1); - initDataForOneSource(faker, "DVX", 2, PeriodicityEnum.X, 1, 2, 1); - initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 1); + initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 2000); + initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 10000); + initDataForOneSource(faker, "DVX", 2, PeriodicityEnum.X, 1, 2, 80000); + initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 10000); } From c6a3dfb6a5196fb1cae492e21f7010b05a4a8c8a Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 23 Feb 2024 13:59:27 +0100 Subject: [PATCH 078/111] fix: add demo profile to load data on start --- .../dataloader/DataloaderPoc.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index a94d5d1f..09739019 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -23,6 +23,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import java.util.*; @@ -30,6 +31,7 @@ @Component @Slf4j +@Profile(("demo")) @RequiredArgsConstructor public class DataloaderPoc { @@ -83,10 +85,10 @@ public void init() { initOrder(); //initContact(faker); - initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 2000); - initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 10000); - initDataForOneSource(faker, "DVX", 2, PeriodicityEnum.X, 1, 2, 80000); - initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 10000); + /*initDataForOneSource(faker, "DVM", 2, PeriodicityEnum.M, 12, 3, 1); + initDataForOneSource(faker, "DVT", 3, PeriodicityEnum.T, 4, 2, 1); + initDataForOneSource(faker, "DVX", 2, PeriodicityEnum.X, 1, 2, 1); + initDataForOneSource(faker, "DVB", 2, PeriodicityEnum.B, 6, 1, 1);*/ } @@ -558,9 +560,7 @@ private void initView() { if (viewRepository.count() == 0) { List listAccreditations = questioningAccreditationRepository.findAll(); - listAccreditations.stream().forEach(a -> { - initOneView(a); - }); + listAccreditations.stream().forEach(this::initOneView); Iterable listContacts = contactRepository.findAll(); for (Contact contact : listContacts) { @@ -598,10 +598,5 @@ String randomNumeric(int len) { return sb.toString(); } - public int getRandomNumber(int min, int max) { - Random random = new Random(); - return random.nextInt(max - min) + min; - } - } From 8ec1fc48ba08f69e4096383ebdeb83318aee2aa0 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 23 Feb 2024 14:06:56 +0100 Subject: [PATCH 079/111] Update DataloaderPoc.java --- .../datacollectionmanagement/dataloader/DataloaderPoc.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java index 09739019..f6cb3160 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/dataloader/DataloaderPoc.java @@ -26,6 +26,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; +import java.security.SecureRandom; import java.util.*; import java.util.concurrent.TimeUnit; @@ -75,7 +76,7 @@ public class DataloaderPoc { static final String NUMBERS = "0123456789"; - static Random rnd = new Random(); + static SecureRandom rnd = new SecureRandom(); @PostConstruct public void init() { From ee79f5923824603780409840866d2640fdf7f671 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 23 Feb 2024 14:31:38 +0100 Subject: [PATCH 080/111] Update pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ecdd397..6dd30a36 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 1.1.10 + 1.1.11 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From ac22520f6b54567b44d4b9fc55b0abdc378a81f0 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 27 Feb 2024 10:49:38 +0100 Subject: [PATCH 081/111] fix: period and periodicitis en french --- .../metadata/util/PeriodEnum.java | 250 +++++++++--------- .../metadata/util/PeriodicityEnum.java | 4 +- 2 files changed, 127 insertions(+), 127 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodEnum.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodEnum.java index eb7b6b96..2db05522 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodEnum.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodEnum.java @@ -5,131 +5,131 @@ @Getter public enum PeriodEnum { - A00(PeriodicityEnum.A, "annual"), - X00(PeriodicityEnum.X, "pluriannual"), - X01(PeriodicityEnum.X, "pluriannual"), - X02(PeriodicityEnum.X, "pluriannual"), - X03(PeriodicityEnum.X, "pluriannual"), - X04(PeriodicityEnum.X, "pluriannual"), - X05(PeriodicityEnum.X, "pluriannual"), - X06(PeriodicityEnum.X, "pluriannual"), - X07(PeriodicityEnum.X, "pluriannual"), - X08(PeriodicityEnum.X, "pluriannual"), - X09(PeriodicityEnum.X, "pluriannual"), - X10(PeriodicityEnum.X, "pluriannual"), - X11(PeriodicityEnum.X, "pluriannual"), - X12(PeriodicityEnum.X, "pluriannual"), - X13(PeriodicityEnum.X, "pluriannual"), - X14(PeriodicityEnum.X, "pluriannual"), - X15(PeriodicityEnum.X, "pluriannual"), - X16(PeriodicityEnum.X, "pluriannual"), - X17(PeriodicityEnum.X, "pluriannual"), - X18(PeriodicityEnum.X, "pluriannual"), - X19(PeriodicityEnum.X, "pluriannual"), - X20(PeriodicityEnum.X, "pluriannual"), - X21(PeriodicityEnum.X, "pluriannual"), - X22(PeriodicityEnum.X, "pluriannual"), - X23(PeriodicityEnum.X, "pluriannual"), - X24(PeriodicityEnum.X, "pluriannual"), - X25(PeriodicityEnum.X, "pluriannual"), - X26(PeriodicityEnum.X, "pluriannual"), - X27(PeriodicityEnum.X, "pluriannual"), - X28(PeriodicityEnum.X, "pluriannual"), - X29(PeriodicityEnum.X, "pluriannual"), - X30(PeriodicityEnum.X, "pluriannual"), - X31(PeriodicityEnum.X, "pluriannual"), - X32(PeriodicityEnum.X, "pluriannual"), - X33(PeriodicityEnum.X, "pluriannual"), - X34(PeriodicityEnum.X, "pluriannual"), - X35(PeriodicityEnum.X, "pluriannual"), - X36(PeriodicityEnum.X, "pluriannual"), - X37(PeriodicityEnum.X, "pluriannual"), - X38(PeriodicityEnum.X, "pluriannual"), - X39(PeriodicityEnum.X, "pluriannual"), - X40(PeriodicityEnum.X, "pluriannual"), - X41(PeriodicityEnum.X, "pluriannual"), - X42(PeriodicityEnum.X, "pluriannual"), - X43(PeriodicityEnum.X, "pluriannual"), - X44(PeriodicityEnum.X, "pluriannual"), - X45(PeriodicityEnum.X, "pluriannual"), - X46(PeriodicityEnum.X, "pluriannual"), - X47(PeriodicityEnum.X, "pluriannual"), - X48(PeriodicityEnum.X, "pluriannual"), - X49(PeriodicityEnum.X, "pluriannual"), - X50(PeriodicityEnum.X, "pluriannual"), - X51(PeriodicityEnum.X, "pluriannual"), - X52(PeriodicityEnum.X, "pluriannual"), - X53(PeriodicityEnum.X, "pluriannual"), - X54(PeriodicityEnum.X, "pluriannual"), - X55(PeriodicityEnum.X, "pluriannual"), - X56(PeriodicityEnum.X, "pluriannual"), - X57(PeriodicityEnum.X, "pluriannual"), - X58(PeriodicityEnum.X, "pluriannual"), - X59(PeriodicityEnum.X, "pluriannual"), - X60(PeriodicityEnum.X, "pluriannual"), - X61(PeriodicityEnum.X, "pluriannual"), - X62(PeriodicityEnum.X, "pluriannual"), - X63(PeriodicityEnum.X, "pluriannual"), - X64(PeriodicityEnum.X, "pluriannual"), - X65(PeriodicityEnum.X, "pluriannual"), - X66(PeriodicityEnum.X, "pluriannual"), - X67(PeriodicityEnum.X, "pluriannual"), - X68(PeriodicityEnum.X, "pluriannual"), - X69(PeriodicityEnum.X, "pluriannual"), - X70(PeriodicityEnum.X, "pluriannual"), - X71(PeriodicityEnum.X, "pluriannual"), - X72(PeriodicityEnum.X, "pluriannual"), - X73(PeriodicityEnum.X, "pluriannual"), - X74(PeriodicityEnum.X, "pluriannual"), - X75(PeriodicityEnum.X, "pluriannual"), - X76(PeriodicityEnum.X, "pluriannual"), - X77(PeriodicityEnum.X, "pluriannual"), - X78(PeriodicityEnum.X, "pluriannual"), - X79(PeriodicityEnum.X, "pluriannual"), - X80(PeriodicityEnum.X, "pluriannual"), - X81(PeriodicityEnum.X, "pluriannual"), - X82(PeriodicityEnum.X, "pluriannual"), - X83(PeriodicityEnum.X, "pluriannual"), - X84(PeriodicityEnum.X, "pluriannual"), - X85(PeriodicityEnum.X, "pluriannual"), - X86(PeriodicityEnum.X, "pluriannual"), - X87(PeriodicityEnum.X, "pluriannual"), - X88(PeriodicityEnum.X, "pluriannual"), - X89(PeriodicityEnum.X, "pluriannual"), - X90(PeriodicityEnum.X, "pluriannual"), - X91(PeriodicityEnum.X, "pluriannual"), - X92(PeriodicityEnum.X, "pluriannual"), - X93(PeriodicityEnum.X, "pluriannual"), - X94(PeriodicityEnum.X, "pluriannual"), - X95(PeriodicityEnum.X, "pluriannual"), - X96(PeriodicityEnum.X, "pluriannual"), - X97(PeriodicityEnum.X, "pluriannual"), - X98(PeriodicityEnum.X, "pluriannual"), - X99(PeriodicityEnum.X, "pluriannual"), - S01(PeriodicityEnum.S, "1st semester"), - S02(PeriodicityEnum.S, "2nd semester"), - T01(PeriodicityEnum.T, "1st trimester"), - T02(PeriodicityEnum.T, "2nd trimester"), - T03(PeriodicityEnum.T, "3rd trimester"), - T04(PeriodicityEnum.T, "4th trimester"), - M01(PeriodicityEnum.M, "january"), - M02(PeriodicityEnum.M, "february"), - M03(PeriodicityEnum.M, "march"), - M04(PeriodicityEnum.M, "april"), - M05(PeriodicityEnum.M, "may"), - M06(PeriodicityEnum.M, "june"), - M07(PeriodicityEnum.M, "july"), - M08(PeriodicityEnum.M, "august"), - M09(PeriodicityEnum.M, "september"), - M10(PeriodicityEnum.M, "october"), - M11(PeriodicityEnum.M, "november"), - M12(PeriodicityEnum.M, "december"), - B01(PeriodicityEnum.B, "1st bimester"), - B02(PeriodicityEnum.B, "2nd bimester"), - B03(PeriodicityEnum.B, "3rd bimester"), - B04(PeriodicityEnum.B, "4th bimester"), - B05(PeriodicityEnum.B, "5th bimester"), - B06(PeriodicityEnum.B, "6th bimester"), + A00(PeriodicityEnum.A, "annuel"), + X00(PeriodicityEnum.X, "pluriannuel"), + X01(PeriodicityEnum.X, "pluriannuel"), + X02(PeriodicityEnum.X, "pluriannuel"), + X03(PeriodicityEnum.X, "pluriannuel"), + X04(PeriodicityEnum.X, "pluriannuel"), + X05(PeriodicityEnum.X, "pluriannuel"), + X06(PeriodicityEnum.X, "pluriannuel"), + X07(PeriodicityEnum.X, "pluriannuel"), + X08(PeriodicityEnum.X, "pluriannuel"), + X09(PeriodicityEnum.X, "pluriannuel"), + X10(PeriodicityEnum.X, "pluriannuel"), + X11(PeriodicityEnum.X, "pluriannuel"), + X12(PeriodicityEnum.X, "pluriannuel"), + X13(PeriodicityEnum.X, "pluriannuel"), + X14(PeriodicityEnum.X, "pluriannuel"), + X15(PeriodicityEnum.X, "pluriannuel"), + X16(PeriodicityEnum.X, "pluriannuel"), + X17(PeriodicityEnum.X, "pluriannuel"), + X18(PeriodicityEnum.X, "pluriannuel"), + X19(PeriodicityEnum.X, "pluriannuel"), + X20(PeriodicityEnum.X, "pluriannuel"), + X21(PeriodicityEnum.X, "pluriannuel"), + X22(PeriodicityEnum.X, "pluriannuel"), + X23(PeriodicityEnum.X, "pluriannuel"), + X24(PeriodicityEnum.X, "pluriannuel"), + X25(PeriodicityEnum.X, "pluriannuel"), + X26(PeriodicityEnum.X, "pluriannuel"), + X27(PeriodicityEnum.X, "pluriannuel"), + X28(PeriodicityEnum.X, "pluriannuel"), + X29(PeriodicityEnum.X, "pluriannuel"), + X30(PeriodicityEnum.X, "pluriannuel"), + X31(PeriodicityEnum.X, "pluriannuel"), + X32(PeriodicityEnum.X, "pluriannuel"), + X33(PeriodicityEnum.X, "pluriannuel"), + X34(PeriodicityEnum.X, "pluriannuel"), + X35(PeriodicityEnum.X, "pluriannuel"), + X36(PeriodicityEnum.X, "pluriannuel"), + X37(PeriodicityEnum.X, "pluriannuel"), + X38(PeriodicityEnum.X, "pluriannuel"), + X39(PeriodicityEnum.X, "pluriannuel"), + X40(PeriodicityEnum.X, "pluriannuel"), + X41(PeriodicityEnum.X, "pluriannuel"), + X42(PeriodicityEnum.X, "pluriannuel"), + X43(PeriodicityEnum.X, "pluriannuel"), + X44(PeriodicityEnum.X, "pluriannuel"), + X45(PeriodicityEnum.X, "pluriannuel"), + X46(PeriodicityEnum.X, "pluriannuel"), + X47(PeriodicityEnum.X, "pluriannuel"), + X48(PeriodicityEnum.X, "pluriannuel"), + X49(PeriodicityEnum.X, "pluriannuel"), + X50(PeriodicityEnum.X, "pluriannuel"), + X51(PeriodicityEnum.X, "pluriannuel"), + X52(PeriodicityEnum.X, "pluriannuel"), + X53(PeriodicityEnum.X, "pluriannuel"), + X54(PeriodicityEnum.X, "pluriannuel"), + X55(PeriodicityEnum.X, "pluriannuel"), + X56(PeriodicityEnum.X, "pluriannuel"), + X57(PeriodicityEnum.X, "pluriannuel"), + X58(PeriodicityEnum.X, "pluriannuel"), + X59(PeriodicityEnum.X, "pluriannuel"), + X60(PeriodicityEnum.X, "pluriannuel"), + X61(PeriodicityEnum.X, "pluriannuel"), + X62(PeriodicityEnum.X, "pluriannuel"), + X63(PeriodicityEnum.X, "pluriannuel"), + X64(PeriodicityEnum.X, "pluriannuel"), + X65(PeriodicityEnum.X, "pluriannuel"), + X66(PeriodicityEnum.X, "pluriannuel"), + X67(PeriodicityEnum.X, "pluriannuel"), + X68(PeriodicityEnum.X, "pluriannuel"), + X69(PeriodicityEnum.X, "pluriannuel"), + X70(PeriodicityEnum.X, "pluriannuel"), + X71(PeriodicityEnum.X, "pluriannuel"), + X72(PeriodicityEnum.X, "pluriannuel"), + X73(PeriodicityEnum.X, "pluriannuel"), + X74(PeriodicityEnum.X, "pluriannuel"), + X75(PeriodicityEnum.X, "pluriannuel"), + X76(PeriodicityEnum.X, "pluriannuel"), + X77(PeriodicityEnum.X, "pluriannuel"), + X78(PeriodicityEnum.X, "pluriannuel"), + X79(PeriodicityEnum.X, "pluriannuel"), + X80(PeriodicityEnum.X, "pluriannuel"), + X81(PeriodicityEnum.X, "pluriannuel"), + X82(PeriodicityEnum.X, "pluriannuel"), + X83(PeriodicityEnum.X, "pluriannuel"), + X84(PeriodicityEnum.X, "pluriannuel"), + X85(PeriodicityEnum.X, "pluriannuel"), + X86(PeriodicityEnum.X, "pluriannuel"), + X87(PeriodicityEnum.X, "pluriannuel"), + X88(PeriodicityEnum.X, "pluriannuel"), + X89(PeriodicityEnum.X, "pluriannuel"), + X90(PeriodicityEnum.X, "pluriannuel"), + X91(PeriodicityEnum.X, "pluriannuel"), + X92(PeriodicityEnum.X, "pluriannuel"), + X93(PeriodicityEnum.X, "pluriannuel"), + X94(PeriodicityEnum.X, "pluriannuel"), + X95(PeriodicityEnum.X, "pluriannuel"), + X96(PeriodicityEnum.X, "pluriannuel"), + X97(PeriodicityEnum.X, "pluriannuel"), + X98(PeriodicityEnum.X, "pluriannuel"), + X99(PeriodicityEnum.X, "pluriannuel"), + S01(PeriodicityEnum.S, "1er semestre"), + S02(PeriodicityEnum.S, "2nd semestre"), + T01(PeriodicityEnum.T, "1er trimestre"), + T02(PeriodicityEnum.T, "2e trimestre"), + T03(PeriodicityEnum.T, "3e trimestre"), + T04(PeriodicityEnum.T, "4e trimestre"), + M01(PeriodicityEnum.M, "janvier"), + M02(PeriodicityEnum.M, "février"), + M03(PeriodicityEnum.M, "mars"), + M04(PeriodicityEnum.M, "avril"), + M05(PeriodicityEnum.M, "mai"), + M06(PeriodicityEnum.M, "juin"), + M07(PeriodicityEnum.M, "juillet"), + M08(PeriodicityEnum.M, "août"), + M09(PeriodicityEnum.M, "septembre"), + M10(PeriodicityEnum.M, "octobre"), + M11(PeriodicityEnum.M, "novembre"), + M12(PeriodicityEnum.M, "décembre"), + B01(PeriodicityEnum.B, "1er bimestre"), + B02(PeriodicityEnum.B, "2e bimestre"), + B03(PeriodicityEnum.B, "3e bimestre"), + B04(PeriodicityEnum.B, "4e bimestre"), + B05(PeriodicityEnum.B, "5e bimestre"), + B06(PeriodicityEnum.B, "6e bimestre"), ; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodicityEnum.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodicityEnum.java index df375381..134c733e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodicityEnum.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/util/PeriodicityEnum.java @@ -5,8 +5,8 @@ @Getter public enum PeriodicityEnum { - X("pluriannual"), A("annual"), S("semi-annual"), T("trimestrial"), B("bimonthly"), - M("monthly"); + X("pluriannuel"), A("annuel"), S("semi-annuel"), T("trimestriel"), B("bimensuel"), + M("mensuel"); PeriodicityEnum(String value) { this.value = value; From d053dc1c1d8eec59a21182e1da1f3edc23385f64 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 27 Feb 2024 10:53:15 +0100 Subject: [PATCH 082/111] fix: sonar issue --- .../metadata/controller/PeriodPeriodicityController.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java index 82a84141..ea386ddc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/metadata/controller/PeriodPeriodicityController.java @@ -9,17 +9,14 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; -import net.minidev.json.JSONArray; -import net.minidev.json.JSONObject; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; @Slf4j @RestController @@ -51,7 +48,7 @@ public ResponseEntity> getPeriods() { @Operation(summary = "Search for periods of a periodicity") @GetMapping(value = Constants.API_PERIODICITIES_ID_PERIODS, produces = "application/json") - public ResponseEntity> getPeriodsOfPeriodicity(String periodicity) { + public ResponseEntity> getPeriodsOfPeriodicity(@PathVariable("periodicity") String periodicity) { try { PeriodicityEnum.valueOf(periodicity); List periods = new ArrayList<>(); From 1530d501fd83114e6b4f07c9634712e772820a18 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 27 Feb 2024 10:53:49 +0100 Subject: [PATCH 083/111] build: version 1.1.12 with spring boot 3.2.3 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 6dd30a36..e761bdd9 100644 --- a/pom.xml +++ b/pom.xml @@ -6,12 +6,12 @@ org.springframework.boot spring-boot-starter-parent - 3.2.2 + 3.2.3 fr.insee.survey platine-management - 1.1.11 + 1.1.12 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From 1f5a23e1a74c79f3e0dc004a740aa5577b059d32 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 11:51:03 +0100 Subject: [PATCH 084/111] feat: improve search contact endpoint --- pom.xml | 2 +- .../contact/repository/ContactRepository.java | 31 +-- .../contact/service/ContactService.java | 11 +- .../service/impl/ContactServiceImpl.java | 65 ++---- .../controller/SearchContactController.java | 41 +--- .../query/dto/SearchContactDto.java | 5 + .../query/service/SearchContactService.java | 31 +-- .../impl/SearchContactServiceImpl.java | 213 ++++-------------- 8 files changed, 93 insertions(+), 306 deletions(-) diff --git a/pom.xml b/pom.xml index e761bdd9..5c82f5ce 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 1.1.12 + 1.1.13 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java index 7b3251af..204dcc98 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java @@ -1,30 +1,35 @@ package fr.insee.survey.datacollectionmanagement.contact.repository; -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; -import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +public interface ContactRepository extends PagingAndSortingRepository, JpaRepository { -public interface ContactRepository extends PagingAndSortingRepository,JpaRepository { - Page findAll(Pageable pageable); @Query(nativeQuery = true, value = "SELECT * FROM contact ORDER BY random() LIMIT 1") - public Contact findRandomContact(); + Contact findRandomContact(); @Query(nativeQuery = true, value = "SELECT identifier FROM contact TABLESAMPLE system_rows(1)") - public String findRandomIdentifierContact(); - - public List findByLastNameIgnoreCase(String lastName); - - public List findByFirstNameIgnoreCase(String firstName); - - public List findByEmailIgnoreCase(String email); + String findRandomIdentifierContact(); + + @Query( + value = """ + select + * + from + contact c + where + upper(c.first_name) || ' ' || upper(c.last_name) like %:name% + """, + nativeQuery = true) + Page findByNameIgnoreCase(String name, Pageable pageable); + + Page findByEmailIgnoreCase(String email, Pageable pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index 7bc4f422..bb53b614 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -20,6 +20,8 @@ public interface ContactService { */ public Page findAll(Pageable pageable); + public List findAll(); + /** * Find a contact by its identifier. * @@ -42,14 +44,9 @@ public interface ContactService { */ public void deleteContact(String identifier); - public List findByLastName(String lastName); - - public List findByFirstName(String firstName); - - public List findByEmail(String email); + public Page findByName(String name, Pageable pageable); - public List searchListContactParameters(String identifier, String lastName, String firstName, - String email); + public Page findByEmail(String email, Pageable pageable); public Contact createContactAddressEvent(Contact contact, JsonNode payload); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 830e8657..7f1fe973 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -10,13 +10,15 @@ import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; import fr.insee.survey.datacollectionmanagement.exception.NotFoundException; import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.*; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Service @RequiredArgsConstructor @@ -33,6 +35,11 @@ public Page findAll(Pageable pageable) { return contactRepository.findAll(pageable); } + @Override + public List findAll() { + return contactRepository.findAll(); + } + @Override public Contact findByIdentifier(String identifier) { return contactRepository.findById(identifier).orElseThrow(() -> new NotFoundException(String.format("Contact %s not found", identifier))); @@ -49,62 +56,16 @@ public void deleteContact(String identifier) { } @Override - public List findByLastName(String lastName) { - return contactRepository.findByLastNameIgnoreCase(lastName); + public Page findByName(String name, Pageable pageable) { + return contactRepository.findByNameIgnoreCase(name.toUpperCase(), pageable); } - @Override - public List findByFirstName(String firstName) { - return contactRepository.findByFirstNameIgnoreCase(firstName); - } @Override - public List findByEmail(String email) { - return contactRepository.findByEmailIgnoreCase(email); + public Page findByEmail(String email, Pageable pageable) { + return contactRepository.findByEmailIgnoreCase(email,pageable); } - @Override - public List searchListContactParameters(String identifier, String lastName, String firstName, - String email) { - - List listContactContact = new ArrayList<>(); - boolean alwaysEmpty = true; - - if (!StringUtils.isEmpty(identifier)) { - listContactContact = Arrays.asList(findByIdentifier(identifier)); - alwaysEmpty = false; - } - - if (!StringUtils.isEmpty(lastName)) { - if (listContactContact.isEmpty() && alwaysEmpty) { - listContactContact.addAll(findByLastName(lastName)); - alwaysEmpty = false; - } else - listContactContact = listContactContact.stream().filter(c -> c.getLastName().equalsIgnoreCase(lastName)) - .toList(); - - } - - if (!StringUtils.isEmpty(firstName)) { - if (listContactContact.isEmpty() && alwaysEmpty) { - listContactContact.addAll(findByFirstName(firstName)); - alwaysEmpty = false; - } else - listContactContact = listContactContact.stream() - .filter(c -> c.getFirstName().equalsIgnoreCase(firstName)).toList(); - } - - if (!StringUtils.isEmpty(email)) { - if (listContactContact.isEmpty() && alwaysEmpty) { - listContactContact.addAll(findByEmail(email)); - alwaysEmpty = false; - } else - listContactContact = listContactContact.stream().filter(c -> c.getEmail().equalsIgnoreCase(email)) - .toList(); - } - - return listContactContact; - } @Override @Transactional diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index dfb7c019..764100f2 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -9,7 +9,6 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; -import fr.insee.survey.datacollectionmanagement.view.domain.View; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; @@ -20,7 +19,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -32,7 +30,6 @@ import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; -import java.util.Collections; import java.util.List; @RestController @@ -56,47 +53,23 @@ public class SearchContactController { @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = SearchContactDto.class)))), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity searchContacts( + public ResponseEntity> searchContacts( @RequestParam(required = false) String identifier, - @RequestParam(required = false) String lastName, - @RequestParam(required = false) String firstName, + @RequestParam(required = false) String name, @RequestParam(required = false) String email, - @RequestParam(required = false) String idSu, - @RequestParam(required = false) String identificationCode, - @RequestParam(required = false) String identificationName, - @RequestParam(required = false) String source, - @RequestParam(required = false) String year, - @RequestParam(required = false) String period, @RequestParam(defaultValue = "0") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize) { log.info( - "Search contact: identifier = {}, lastName= {}, firstName= {}, email= {}, idSu= {}, identificationCode= {}, identificationName= {}, source= {}, year= {}, period= {}, pageNo= {}, pageSize= {} ", - identifier, lastName, firstName, email, idSu, identificationCode, identificationName, source, year, - period, pageNo, pageSize); + "Search contact: identifier = {}, name= {}, email= {}, pageNo= {}, pageSize= {} ", + identifier, name, email, pageNo, pageSize); Pageable pageable = PageRequest.of(pageNo, pageSize); - List listView = searchContactService.searchContactCrossDomain(identifier, lastName, firstName, email, - idSu, identificationCode, identificationName, source, year, period, + Page page = searchContactService.searchContactCrossDomain(identifier, name, email, pageable); - int start = (int) pageable.getOffset(); - int end = (int) ((start + pageable.getPageSize()) > listView.size() ? listView.size() - : (start + pageable.getPageSize())); + return new ResponseEntity<>(page, HttpStatus.OK); - if (listView.isEmpty()) { - return new ResponseEntity<>(Collections.EMPTY_LIST, HttpStatus.NOT_FOUND); - } - if (start <= end) { - Page page = new PageImpl( - searchContactService.transformListViewDaoToDto(listView.subList(start, end)), pageable, - listView.size()); - return new ResponseEntity<>(page, HttpStatus.OK); - - } - - else - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } @@ -106,7 +79,7 @@ public ResponseEntity searchContacts( @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AccreditationDetailDto.class)))), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity getContactAccreditations(@PathVariable("id") String id) { + public ResponseEntity> getContactAccreditations(@PathVariable("id") String id) { List listAccreditations = new ArrayList<>(); List accreditations = questioningAccreditationService.findByContactIdentifier(id); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java index 98514500..b13d888f 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java @@ -3,6 +3,8 @@ import lombok.Getter; import lombok.Setter; +import java.util.List; + @Getter @Setter public class SearchContactDto { @@ -11,4 +13,7 @@ public class SearchContactDto { private String firstName; private String lastName; private String email; + private String function; + private List listSurveyUnitNames; + private List listSourcesId; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java index bc88a287..0e769511 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java @@ -1,41 +1,22 @@ package fr.insee.survey.datacollectionmanagement.query.service; -import java.util.List; - -import org.springframework.data.domain.Pageable; - import fr.insee.survey.datacollectionmanagement.query.dto.SearchContactDto; -import fr.insee.survey.datacollectionmanagement.view.domain.View; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; public interface SearchContactService { /** * Search contact according to diffeent parameters * @param identifier - * @param lastName - * @param firstName + * @param name (first name or and lastName) * @param email - * @param idSu - * @param identificationCode - * @param identificationName - * @param source - * @param year - * @param period + * @return */ - List searchContactCrossDomain( + Page searchContactCrossDomain( String identifier, - String lastName, - String firstName, + String name, String email, - String idSu, - String identificationCode, - String identificationName, - String source, - String year, - String period, Pageable pageable); - - List transformListViewDaoToDto(List subList); - } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 2559fa23..689d438d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -2,210 +2,75 @@ import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; -import fr.insee.survey.datacollectionmanagement.metadata.domain.Campaign; -import fr.insee.survey.datacollectionmanagement.metadata.service.CampaignService; +import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.dto.SearchContactDto; import fr.insee.survey.datacollectionmanagement.query.service.SearchContactService; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; -import fr.insee.survey.datacollectionmanagement.questioning.service.SurveyUnitService; -import fr.insee.survey.datacollectionmanagement.view.domain.View; -import fr.insee.survey.datacollectionmanagement.view.service.ViewService; -import lombok.EqualsAndHashCode; +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; @Service -@EqualsAndHashCode @RequiredArgsConstructor public class SearchContactServiceImpl implements SearchContactService { private final ContactService contactService; - private final SurveyUnitService surveyUnitService; + private final PartitioningService partioningService; - private final CampaignService campaignService; + private final QuestioningAccreditationService questioningAccreditationService; - @EqualsAndHashCode.Exclude - private final ViewService viewService;; @Override - public List searchContactCrossDomain( + public Page searchContactCrossDomain( String identifier, - String lastName, - String firstName, + String name, String email, - String idSu, - String identificationCode, - String identificationName, - String source, - String year, - String period, Pageable pageable) { - List listView = new ArrayList<>(); - boolean alwaysEmpty = true; + List listSearchContact = new ArrayList<>(); - if (!StringUtils.isEmpty(identifier)) { - View contactView = viewService.findFirstViewByIdentifier(identifier); - if (contactView != null) - listView.add(contactView); - alwaysEmpty = false; - } - - if (!StringUtils.isEmpty(idSu)) { - if (listView.isEmpty() && alwaysEmpty) { - listView = viewService.findViewByIdSu(idSu); - alwaysEmpty = false; - } else if (!alwaysEmpty) { - listView = listView.stream().filter(v -> viewService.findViewByIdSu(idSu).contains(v)) - .toList(); - } - } - - if (!StringUtils.isEmpty(source) && !StringUtils.isEmpty(year) && !StringUtils.isEmpty(period)) { - if (listView.isEmpty() && alwaysEmpty) { - List listCampains = campaignService.findbySourceYearPeriod(source, Integer.parseInt(year), - period); - for (Campaign campain : listCampains) { - listView.addAll(viewService.findViewByCampaignId(campain.getId())); - } - - alwaysEmpty = false; - } else if (!alwaysEmpty) { - List listCampains = campaignService.findbySourceYearPeriod(source, Integer.parseInt(year), - period); - List listViewC = new ArrayList<>(); - for (Campaign c : listCampains) { - listViewC - .addAll(listView.stream() - .filter(v -> viewService.findViewByCampaignId(c.getId()).contains(v)) - .toList()); - } - listView = listViewC; - } - } - if ((!StringUtils.isEmpty(source) || !StringUtils.isEmpty(period)) && StringUtils.isEmpty(year)) { - if (listView.isEmpty() && alwaysEmpty) { - List listCampains = campaignService.findbySourcePeriod(source, period); - for (Campaign campain : listCampains) { - listView.addAll(viewService.findViewByCampaignId(campain.getId())); - } - - alwaysEmpty = false; - } else if (!alwaysEmpty) { - List listCampains = campaignService.findbySourcePeriod(source, period); - List listViewC = new ArrayList<>(); - for (Campaign c : listCampains) { - listViewC - .addAll(listView.stream() - .filter(v -> viewService.findViewByCampaignId(c.getId()).contains(v)) - .toList()); - } - listView = listViewC; - } - } - - if (!StringUtils.isEmpty(lastName)) { - if (listView.isEmpty() && alwaysEmpty) { - List listC = contactService.findByLastName(lastName); - for (Contact c : listC) { - listView.add(viewService.findFirstViewByIdentifier(c.getIdentifier())); - } - alwaysEmpty = false; - } else if (!alwaysEmpty) - - listView = listView.stream() - .filter(v -> lastName - .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getLastName())) - .toList(); - } - - if (!StringUtils.isEmpty(firstName)) { - if (listView.isEmpty() && alwaysEmpty) { - List listC = contactService.findByFirstName(firstName); - for (Contact c : listC) { - listView.add(viewService.findFirstViewByIdentifier(c.getIdentifier())); - } - alwaysEmpty = false; - } else if (!alwaysEmpty) + Page pageContact = null; - listView = listView.stream() - .filter(v -> firstName - .equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getFirstName())) - .toList(); - } - - if (!StringUtils.isEmpty(email)) { - if (listView.isEmpty() && alwaysEmpty) { - List listC = contactService.findByEmail(email); - for (Contact c : listC) { - listView.add(viewService.findFirstViewByIdentifier(c.getIdentifier())); - } - alwaysEmpty = false; - } else if (!alwaysEmpty) - - listView = listView.stream().filter( - v -> email.equalsIgnoreCase(contactService.findByIdentifier(v.getIdentifier()).getEmail())) - .toList(); + if (!StringUtils.isEmpty(identifier)) { + Contact c = contactService.findByIdentifier(identifier); + pageContact = new PageImpl<>(Arrays.asList(c),pageable,1); + } else if (!StringUtils.isEmpty(email)) { + pageContact = contactService.findByEmail(email, pageable); + + } else if (!StringUtils.isEmpty(name)) { + pageContact = contactService.findByName(name, pageable); + } else { + pageContact = contactService.findAll(pageable); } - - if (!StringUtils.isEmpty(identificationCode)) { - if (listView.isEmpty() && alwaysEmpty) { - List listSurveyUnits = surveyUnitService.findbyIdentificationCode(identificationCode); - for (SurveyUnit s : listSurveyUnits) { - listView.addAll(viewService.findViewByIdSu(s.getIdSu())); - } - alwaysEmpty = false; - } else if (!alwaysEmpty) { - List listSurveyUnits = surveyUnitService.findbyIdentificationCode(identificationCode); - for (SurveyUnit s : listSurveyUnits) { - listView = listView.stream() - .filter(v -> identificationCode.equalsIgnoreCase(s.getIdentificationCode())) - .toList(); - } - - } + assert pageContact != null; + for (Contact c : pageContact) { + listSearchContact.add(transformContactTSearchContactDto(c)); } - if (!StringUtils.isEmpty(identificationName)) { - if (listView.isEmpty() && alwaysEmpty) { - List listSurveyUnits = surveyUnitService.findbyIdentificationName(identificationName); - for (SurveyUnit s : listSurveyUnits) { - listView.addAll(viewService.findViewByIdSu(s.getIdSu())); - } - alwaysEmpty = false; - } else if (!alwaysEmpty) { - List listSurveyUnits = surveyUnitService.findbyIdentificationCode(identificationCode); - for (SurveyUnit s : listSurveyUnits) { - listView = listView.stream() - .filter(v -> identificationName.equalsIgnoreCase(s.getIdentificationName())) - .toList(); - } - - } - } - return listView; + return new PageImpl<>(listSearchContact, pageable, pageContact.getTotalElements()); } - @Override - public List transformListViewDaoToDto(List listView) { - List listResult = new ArrayList<>(); - for (View v : listView) { - - SearchContactDto searchContact = new SearchContactDto(); - Contact c = contactService.findByIdentifier(v.getIdentifier()); - searchContact.setIdentifier(c.getIdentifier()); - searchContact.setFirstName(c.getFirstName()); - searchContact.setLastName(c.getLastName()); - searchContact.setEmail(c.getEmail()); - - listResult.add(searchContact); - } - return listResult; + private SearchContactDto transformContactTSearchContactDto(Contact c) { + SearchContactDto searchContact = new SearchContactDto(); + searchContact.setIdentifier(c.getIdentifier()); + searchContact.setFirstName(c.getFirstName()); + searchContact.setLastName(c.getLastName()); + searchContact.setEmail(c.getEmail()); + searchContact.setFunction(c.getFunction()); + List listAccreditations = questioningAccreditationService.findByContactIdentifier(c.getIdentifier()); + searchContact.setListSurveyUnitNames(listAccreditations.stream().map(a -> a.getQuestioning().getSurveyUnit().getIdSu()).toList()); + searchContact.setListSourcesId(listAccreditations.stream(). + map(a -> + partioningService.findById(a.getQuestioning().getIdPartitioning()).getCampaign().getSurvey().getSource().getId()).toList()); + return searchContact; } } From 074aa1b22e00b410f2861a4a0fcbb5d435dbdc83 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 11:55:00 +0100 Subject: [PATCH 085/111] feat: improve search contact endpoint --- .../contact/repository/ContactRepository.java | 13 +++++---- .../contact/service/ContactService.java | 28 +++++++++---------- .../service/impl/ContactServiceImpl.java | 7 ++--- .../query/service/SearchContactService.java | 4 +-- .../impl/SearchContactServiceImpl.java | 6 ++-- 5 files changed, 28 insertions(+), 30 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java index 204dcc98..2ddaf912 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java @@ -9,6 +9,7 @@ public interface ContactRepository extends PagingAndSortingRepository, JpaRepository { + @Override Page findAll(Pageable pageable); @Query(nativeQuery = true, value = "SELECT * FROM contact ORDER BY random() LIMIT 1") @@ -19,12 +20,12 @@ public interface ContactRepository extends PagingAndSortingRepository findByNameIgnoreCase(String name, Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index bb53b614..72a766f9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -14,13 +14,13 @@ public interface ContactService { /** * Find all contacts - * - * @param pageable + * + * @param pageable pageable * @return contact Page */ - public Page findAll(Pageable pageable); + Page findAll(Pageable pageable); - public List findAll(); + List findAll(); /** * Find a contact by its identifier. @@ -28,30 +28,30 @@ public interface ContactService { * @param identifier * @return contact found */ - public Contact findByIdentifier(String identifier) ; + Contact findByIdentifier(String identifier) ; /** * Update an existing contact and its address, or creates a new one - * + * * @param contact * @return contact updated */ - public Contact saveContact(Contact contact); + Contact saveContact(Contact contact); /** * Delete a contact. Delete also the contact address. - * @param identifier + * @param identifier contact identifier */ - public void deleteContact(String identifier); + void deleteContact(String identifier); - public Page findByName(String name, Pageable pageable); + Page findByName(String name, Pageable pageable); - public Page findByEmail(String email, Pageable pageable); + Page findByEmail(String email, Pageable pageable); - public Contact createContactAddressEvent(Contact contact, JsonNode payload); + Contact createContactAddressEvent(Contact contact, JsonNode payload); - public Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException; + Contact updateContactAddressEvent(Contact contact, JsonNode payload) throws NotFoundException; - public void deleteContactAddressEvent(Contact contact); + void deleteContactAddressEvent(Contact contact); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 7f1fe973..061f0271 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -15,10 +15,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; @Service @RequiredArgsConstructor @@ -75,7 +72,7 @@ public Contact createContactAddressEvent(Contact contact, JsonNode payload) { } ContactEvent newContactEvent = contactEventService.createContactEvent(contact, ContactEventType.create, payload); - contact.setContactEvents(new HashSet<>(Arrays.asList(newContactEvent))); + contact.setContactEvents(new HashSet<>(Collections.singletonList(newContactEvent))); return saveContact(contact); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java index 0e769511..a40a8dcd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java @@ -8,9 +8,9 @@ public interface SearchContactService { /** * Search contact according to diffeent parameters - * @param identifier + * @param identifier contact identifier * @param name (first name or and lastName) - * @param email + * @param email contact email * @return */ diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 689d438d..8dd6af7b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -15,7 +15,7 @@ import org.springframework.stereotype.Service; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; @Service @@ -38,11 +38,11 @@ public Page searchContactCrossDomain( List listSearchContact = new ArrayList<>(); - Page pageContact = null; + Page pageContact; if (!StringUtils.isEmpty(identifier)) { Contact c = contactService.findByIdentifier(identifier); - pageContact = new PageImpl<>(Arrays.asList(c),pageable,1); + pageContact = new PageImpl<>(Collections.singletonList(c),pageable,1); } else if (!StringUtils.isEmpty(email)) { pageContact = contactService.findByEmail(email, pageable); From 9226bc90e47887a31c8b458eb47a5da614ce53b6 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 12:57:57 +0100 Subject: [PATCH 086/111] fix: distinct surveys uits and sources in list --- .../query/service/impl/SearchContactServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 8dd6af7b..df296e63 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -67,10 +67,10 @@ private SearchContactDto transformContactTSearchContactDto(Contact c) { searchContact.setEmail(c.getEmail()); searchContact.setFunction(c.getFunction()); List listAccreditations = questioningAccreditationService.findByContactIdentifier(c.getIdentifier()); - searchContact.setListSurveyUnitNames(listAccreditations.stream().map(a -> a.getQuestioning().getSurveyUnit().getIdSu()).toList()); + searchContact.setListSurveyUnitNames(listAccreditations.stream().map(a -> a.getQuestioning().getSurveyUnit().getIdSu()).distinct().toList()); searchContact.setListSourcesId(listAccreditations.stream(). map(a -> - partioningService.findById(a.getQuestioning().getIdPartitioning()).getCampaign().getSurvey().getSource().getId()).toList()); + partioningService.findById(a.getQuestioning().getIdPartitioning()).getCampaign().getSurvey().getSource().getId()).distinct().toList()); return searchContact; } } From 604b00ba321bfaee4a95a6b5446b02f65b36eef0 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 14:55:42 +0100 Subject: [PATCH 087/111] feat: improve search contact endpoint --- .../query/service/impl/SearchContactServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index df296e63..70c549c9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -41,7 +41,7 @@ public Page searchContactCrossDomain( Page pageContact; if (!StringUtils.isEmpty(identifier)) { - Contact c = contactService.findByIdentifier(identifier); + Contact c = contactService.findByIdentifier(identifier.toUpperCase()); pageContact = new PageImpl<>(Collections.singletonList(c),pageable,1); } else if (!StringUtils.isEmpty(email)) { pageContact = contactService.findByEmail(email, pageable); From b4c3f27bd090e53448eab7de3da6293ff97c2d0a Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 15:26:22 +0100 Subject: [PATCH 088/111] feat: improve get contact accreditations --- .../controller/SearchContactController.java | 21 +++++++++++--- .../query/dto/AccreditationDetailDto.java | 28 ++++++------------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 764100f2..731cfe7c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -8,7 +8,10 @@ import fr.insee.survey.datacollectionmanagement.query.service.SearchContactService; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; +import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; @@ -31,6 +34,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -47,6 +51,8 @@ public class SearchContactController { private final PartitioningService partitioningService; + private final QuestioningEventService questioningEventService; + @GetMapping(path = Constants.API_CONTACTS_SEARCH, produces = "application/json") @Operation(summary = "Multi-criteria search contacts") @ApiResponses(value = { @@ -86,13 +92,20 @@ public ResponseEntity> getContactAccreditations(@Pa for (QuestioningAccreditation questioningAccreditation : accreditations) { Questioning questioning = questioningAccreditation.getQuestioning(); Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); + Optional questioningEvent = questioningEventService.getLastQuestioningEvent(questioning, TypeQuestioningEvent.STATE_EVENTS); - listAccreditations.add(new AccreditationDetailDto(part.getCampaign().getSurvey().getSource().getId(), + listAccreditations.add(new AccreditationDetailDto( + part.getCampaign().getSurvey().getSource().getId(), part.getCampaign().getSurvey().getSource().getShortWording(), - part.getCampaign().getSurvey().getYear(), part.getCampaign().getPeriod(), - part.getId(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), + part.getCampaign().getSurvey().getYear(), + part.getCampaign().getPeriod(), + part.getId(), + part.getClosingDate(), + questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), - questioningAccreditation.isMain())); + questioningAccreditation.isMain(), + questioningEvent.map(QuestioningEvent::getType).orElse(null) + )); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java index b5ea085f..4a69884d 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java @@ -1,11 +1,16 @@ package fr.insee.survey.datacollectionmanagement.query.dto; import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; +import java.util.Date; + @Getter @Setter +@AllArgsConstructor public class AccreditationDetailDto { private String sourceId; @@ -13,28 +18,11 @@ public class AccreditationDetailDto { private int year; private PeriodEnum period; private String partition; - private String identificationCode; + private Date partioningClosingDate; + private String surveyUnitId; private String identificationName; private boolean isMain; + private TypeQuestioningEvent lastEvent; - public AccreditationDetailDto( - String sourceId, - String sourceWording, - int year, - PeriodEnum period, - String partition, - String identificationCode, - String identificationName, - boolean isMain) { - super(); - this.sourceId = sourceId; - this.sourceWording = sourceWording; - this.year = year; - this.period = period; - this.partition = partition; - this.identificationCode = identificationCode; - this.identificationName = identificationName; - this.isMain = isMain; - } } From c355842c66f881b6922dcf39d949c55666007af2 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 15:38:18 +0100 Subject: [PATCH 089/111] feat: add filter opened partitionings --- .../controller/SearchContactController.java | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 731cfe7c..9d3c3a37 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -33,6 +33,7 @@ import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Optional; @@ -85,7 +86,7 @@ public ResponseEntity> searchContacts( @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AccreditationDetailDto.class)))), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity> getContactAccreditations(@PathVariable("id") String id) { + public ResponseEntity> getContactAccreditations(@PathVariable("id") String id, @RequestParam(defaultValue = "false") boolean isFilterOpened) { List listAccreditations = new ArrayList<>(); List accreditations = questioningAccreditationService.findByContactIdentifier(id); @@ -94,18 +95,20 @@ public ResponseEntity> getContactAccreditations(@Pa Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); Optional questioningEvent = questioningEventService.getLastQuestioningEvent(questioning, TypeQuestioningEvent.STATE_EVENTS); - listAccreditations.add(new AccreditationDetailDto( - part.getCampaign().getSurvey().getSource().getId(), - part.getCampaign().getSurvey().getSource().getShortWording(), - part.getCampaign().getSurvey().getYear(), - part.getCampaign().getPeriod(), - part.getId(), - part.getClosingDate(), - questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), - questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), - questioningAccreditation.isMain(), - questioningEvent.map(QuestioningEvent::getType).orElse(null) - )); + if (isFilterOpened && partitioningService.isOnGoing(part, new Date()) || !isFilterOpened) { + listAccreditations.add(new AccreditationDetailDto( + part.getCampaign().getSurvey().getSource().getId(), + part.getCampaign().getSurvey().getSource().getShortWording(), + part.getCampaign().getSurvey().getYear(), + part.getCampaign().getPeriod(), + part.getId(), + part.getClosingDate(), + questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), + questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), + questioningAccreditation.isMain(), + questioningEvent.map(QuestioningEvent::getType).orElse(null) + )); + } } From 649e64b96e95976ec711cbb70fe911a20aad676f Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 15:59:35 +0100 Subject: [PATCH 090/111] feat: add questioningId in get contact accreditations --- .../query/controller/SearchContactController.java | 9 ++++++--- .../query/dto/AccreditationDetailDto.java | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 9d3c3a37..4d369101 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -86,7 +86,9 @@ public ResponseEntity> searchContacts( @ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = AccreditationDetailDto.class)))), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity> getContactAccreditations(@PathVariable("id") String id, @RequestParam(defaultValue = "false") boolean isFilterOpened) { + public ResponseEntity> getContactAccreditations( + @PathVariable("id") String id, + @RequestParam(defaultValue = "false") boolean isFilterOpened) { List listAccreditations = new ArrayList<>(); List accreditations = questioningAccreditationService.findByContactIdentifier(id); @@ -95,7 +97,7 @@ public ResponseEntity> getContactAccreditations(@Pa Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); Optional questioningEvent = questioningEventService.getLastQuestioningEvent(questioning, TypeQuestioningEvent.STATE_EVENTS); - if (isFilterOpened && partitioningService.isOnGoing(part, new Date()) || !isFilterOpened) { + if (!isFilterOpened || partitioningService.isOnGoing(part, new Date())) { listAccreditations.add(new AccreditationDetailDto( part.getCampaign().getSurvey().getSource().getId(), part.getCampaign().getSurvey().getSource().getShortWording(), @@ -106,7 +108,8 @@ public ResponseEntity> getContactAccreditations(@Pa questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), questioningAccreditation.isMain(), - questioningEvent.map(QuestioningEvent::getType).orElse(null) + questioningEvent.map(QuestioningEvent::getType).orElse(null), + questioning.getId().toString() )); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java index 4a69884d..6439e675 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java @@ -23,6 +23,7 @@ public class AccreditationDetailDto { private String identificationName; private boolean isMain; private TypeQuestioningEvent lastEvent; + private String questioningId; } From a07b72efc05c0ac88bd7c7241689d344206f14e1 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 17:25:07 +0100 Subject: [PATCH 091/111] feat: add endpoint get contacts of a survey unit --- .../constants/Constants.java | 5 +- .../SearchSurveyUnitController.java | 83 +++++++++++++++++++ .../query/dto/SearchSurveyUnitContactDto.java | 19 +++++ .../QuestioningAccreditationService.java | 15 ---- .../QuestioningAccreditationServiceImpl.java | 30 ------- 5 files changed, 106 insertions(+), 46 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchSurveyUnitContactDto.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index b43c1a74..7deb523e 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -91,7 +91,10 @@ private Constants() { public static final String API_CONTACTS_SEARCH = "/api/contacts/search"; public static final String API_CONTACTS_ACCREDITATIONS = "/api/contacts/{id}/accreditations"; public static final String API_MY_QUESTIONINGS_ID = "/api/contacts/questionings"; - + + public static final String API_SURVEYUNITS_CONTACTS = "/api/survey_units/{id}/contacts"; + + // API WEBCLIENT public static final String API_WEBCLIENT_FOLLOWUP = "/api/partitionings/{idPartitioning}/survey-units/{idSu}/follow-up"; public static final String API_WEBCLIENT_EXTRACT = "/api/partitionings/{idPartitioning}/survey-units/{idSu}/extract"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java new file mode 100644 index 00000000..e2bfa25e --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java @@ -0,0 +1,83 @@ +package fr.insee.survey.datacollectionmanagement.query.controller; + +import fr.insee.survey.datacollectionmanagement.constants.Constants; +import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; +import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; +import fr.insee.survey.datacollectionmanagement.query.dto.SearchSurveyUnitContactDto; +import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +@RestController +@PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " + + "|| @AuthorizeMethodDecider.isWebClient() " + + "|| @AuthorizeMethodDecider.isAdmin() ") +@Tag(name = "4 - Cross domain") +@Slf4j +@RequiredArgsConstructor +public class SearchSurveyUnitController { + + + private final ContactService contactService; + + private final QuestioningService questioningService; + + private final QuestioningAccreditationService questioningAccreditationService; + + private final PartitioningService partitioningService; + + + @GetMapping(path = Constants.API_SURVEYUNITS_CONTACTS, produces = "application/json") + @Operation(summary = "Get contacts having accreditations to repond for a survey unit ") + public ResponseEntity> getSurveyUnitContacts( + @PathVariable("id") String id) { + + List listContactIdentifiers = new ArrayList<>(); + Set setQuestionings = questioningService.findBySurveyUnitIdSu(id); + for (Questioning questioning : setQuestionings) { + for (QuestioningAccreditation qa : questioning.getQuestioningAccreditations()) { + if (!listContactIdentifiers.contains(qa.getIdContact())) + listContactIdentifiers.add(qa.getIdContact()); + + } + } + + List listResult = new ArrayList<>(); + for (String identifier : listContactIdentifiers) { + SearchSurveyUnitContactDto searchSurveyUnitContactDto = new SearchSurveyUnitContactDto(); + Contact contact = contactService.findByIdentifier(identifier); + searchSurveyUnitContactDto.setIdentifier(identifier); + searchSurveyUnitContactDto.setCity(contact.getEmail()); + searchSurveyUnitContactDto.setEmail(contact.getEmail()); + searchSurveyUnitContactDto.setFirstName(contact.getFirstName()); + searchSurveyUnitContactDto.setLastName(contact.getLastName()); + searchSurveyUnitContactDto.setPhoneNumber(contact.getPhone()); + searchSurveyUnitContactDto.setCity(contact.getAddress() != null ? contact.getAddress().getCityName() : null); + searchSurveyUnitContactDto.setListSourcesId(questioningAccreditationService.findByContactIdentifier(identifier).stream(). + filter(qa -> qa.getQuestioning().getSurveyUnit().getIdSu().equalsIgnoreCase(id)). + map(qa -> partitioningService.findById(qa.getQuestioning().getIdPartitioning()).getCampaign().getSurvey().getSource().getId()). + distinct().toList()); + listResult.add(searchSurveyUnitContactDto); + } + + return new ResponseEntity<>(listResult, HttpStatus.OK); + + } + +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchSurveyUnitContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchSurveyUnitContactDto.java new file mode 100644 index 00000000..01219e7a --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchSurveyUnitContactDto.java @@ -0,0 +1,19 @@ +package fr.insee.survey.datacollectionmanagement.query.dto; + +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +@Getter +@Setter +public class SearchSurveyUnitContactDto { + + private String identifier; + private String firstName; + private String lastName; + private String email; + private String city; + private String phoneNumber; + private List listSourcesId; +} diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java index 31f82a4b..38b0ea59 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java @@ -1,30 +1,15 @@ package fr.insee.survey.datacollectionmanagement.questioning.service; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; -import java.util.Set; public interface QuestioningAccreditationService { public List findByContactIdentifier(String id); - public Set findBySurveyUnit(SurveyUnit su); - - public List findIdContactsByPartitionigAccredications(String idPartitioning); - - public List findIdPartitioningsByContactAccreditations(String idContact); - - public List findIdContactsByIdSource(String idSource); - - public List findIdContactsByYear(Integer year); - - public List findIdContactsByPeriod(String period); - - public List findIdContactsBySourceYearPeriod(String idSource, Integer year, String period); public Page findAll(Pageable pageable); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java index 1dbbf020..dbc2cf30 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/QuestioningAccreditationServiceImpl.java @@ -33,36 +33,6 @@ public Set findBySurveyUnit(SurveyUnit su) { return setReturn; } - @Override - public List findIdContactsByPartitionigAccredications(String idPartitioning) { - return questioningAccreditationRepository.findIdContactsByPartitionigAccredications(idPartitioning); - } - - @Override - public List findIdPartitioningsByContactAccreditations(String idContact) { - return questioningAccreditationRepository.findIdPartitioningsByContactAccreditations(idContact); - } - - @Override - public List findIdContactsByIdSource(String idSource) { - return questioningAccreditationRepository.findIdContactsByIdSource(idSource); - } - - @Override - public List findIdContactsByYear(Integer year) { - return questioningAccreditationRepository.findIdContactsByYear(year); - } - - @Override - public List findIdContactsByPeriod(String period) { - return questioningAccreditationRepository.findIdContactsByPeriod(period); - } - - @Override - public List findIdContactsBySourceYearPeriod(String source, Integer year, String period) { - return questioningAccreditationRepository.findIdContactsBySourceYearPeriod(source, year, period); - } - @Override public Page findAll(Pageable pageable) { return questioningAccreditationRepository.findAll(pageable); From 28eda909b95f88a5da88bacee899d66e64f7ec93 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 28 Feb 2024 17:27:03 +0100 Subject: [PATCH 092/111] feat: add endpoint get contacts of a survey unit --- .../datacollectionmanagement/constants/Constants.java | 6 ------ .../service/QuestioningAccreditationService.java | 10 +++++----- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 7deb523e..0c63d2ae 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -10,8 +10,6 @@ private Constants() { public static final String API_CONTACTS = "/api/contacts/"; public static final String API_CONTACTS_ALL = "/api/contacts"; public static final String API_CONTACTS_ID = "/api/contacts/{id}"; - public static final String ADDRESS = "/api/address"; - public static final String CONTACT_EVENTS = "/api/contact-events"; public static final String API_CONTACTS_ID_ADDRESS = "/api/contacts/{id}/address"; public static final String API_CONTACTS_ID_CONTACTEVENTS = "/api/contacts/{id}/contact-events"; public static final String API_CONTACTEVENTS = "/api/contacts/contact-events"; @@ -35,7 +33,6 @@ private Constants() { public static final String API_SURVEY_UNITS ="/api/survey-units"; public static final String API_SURVEY_UNITS_ID = "/api/survey-units/{id}"; public static final String API_SURVEY_UNITS_ID_QUESTIONINGS = "/api/survey-units/{id}/questionings"; - public static final String API_QUESTIONING_ACCREDITATIONS = "/api/questioning-accreditations"; public static final String API_QUESTIONINGS_ID_QUESTIONING_ACCREDITATIONS = "/api/questionings/{id}/questioning-accreditations"; public static final String API_QUESTIONING_QUESTIONING_EVENTS = "/api/questionings/questioning-events"; public static final String API_QUESTIONING_ID_QUESTIONING_EVENTS = "/api/questionings/{id}/questioning-events"; @@ -58,9 +55,7 @@ private Constants() { public static final String API_CAMPAIGNS_ID = "/api/campaigns/{id}"; public static final String CAMPAIGNS_ID_ONGOING = "/campaigns/{id}/ongoing"; public static final String API_CAMPAIGNS_ID_PARTITIONINGS = "/api/campaigns/{id}/partitionings"; - public static final String API_PARTITIONINGS = "/api/partitionings"; public static final String API_PARTITIONINGS_ID = "/api/partitionings/{id}"; - public static final String API_METADATA_ID = "/api/metadata/{id}"; public static final String API_OWNERS = "/api/owners"; public static final String API_OWNERS_ID = "/api/owners/{id}"; public static final String API_OWNERS_ID_SOURCES = "/api/owners/{id}/sources"; @@ -99,7 +94,6 @@ private Constants() { public static final String API_WEBCLIENT_FOLLOWUP = "/api/partitionings/{idPartitioning}/survey-units/{idSu}/follow-up"; public static final String API_WEBCLIENT_EXTRACT = "/api/partitionings/{idPartitioning}/survey-units/{idSu}/extract"; public static final String API_WEBCLIENT_STATE = "/api/partitionings/{idPartitioning}/survey-units/{idSu}/state"; - public static final String API_WEBCLIENT_METADATA = "/api/metadata"; public static final String API_WEBCLIENT_METADATA_ID = "/api/metadata/{id}"; public static final String API_WEBCLIENT_QUESTIONINGS = "/api/questionings"; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java index 38b0ea59..ed780ea8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/QuestioningAccreditationService.java @@ -8,15 +8,15 @@ public interface QuestioningAccreditationService { - public List findByContactIdentifier(String id); + List findByContactIdentifier(String id); - public Page findAll(Pageable pageable); + Page findAll(Pageable pageable); - public QuestioningAccreditation findById(Long id); + QuestioningAccreditation findById(Long id); - public QuestioningAccreditation saveQuestioningAccreditation(QuestioningAccreditation questioningAccreditation); + QuestioningAccreditation saveQuestioningAccreditation(QuestioningAccreditation questioningAccreditation); - public void deleteAccreditation(QuestioningAccreditation c); + void deleteAccreditation(QuestioningAccreditation c); } From 2f5c3ef8c1cb919586341685443350a0decb3883 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 4 Mar 2024 14:27:50 +0100 Subject: [PATCH 093/111] fix: contact accreditations --- .../controller/SearchContactController.java | 21 +++++++++++++------ .../query/dto/AccreditationDetailDto.java | 3 +++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 4d369101..6349a159 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -2,13 +2,16 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.dto.AccreditationDetailDto; import fr.insee.survey.datacollectionmanagement.query.dto.SearchContactDto; +import fr.insee.survey.datacollectionmanagement.query.service.MoogService; import fr.insee.survey.datacollectionmanagement.query.service.SearchContactService; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; @@ -54,6 +57,8 @@ public class SearchContactController { private final QuestioningEventService questioningEventService; + private final MoogService moogService; + @GetMapping(path = Constants.API_CONTACTS_SEARCH, produces = "application/json") @Operation(summary = "Multi-criteria search contacts") @ApiResponses(value = { @@ -98,18 +103,22 @@ public ResponseEntity> getContactAccreditations( Optional questioningEvent = questioningEventService.getLastQuestioningEvent(questioning, TypeQuestioningEvent.STATE_EVENTS); if (!isFilterOpened || partitioningService.isOnGoing(part, new Date())) { + SurveyUnit su = questioningAccreditation.getQuestioning().getSurveyUnit(); + Survey survey = part.getCampaign().getSurvey(); listAccreditations.add(new AccreditationDetailDto( - part.getCampaign().getSurvey().getSource().getId(), - part.getCampaign().getSurvey().getSource().getShortWording(), - part.getCampaign().getSurvey().getYear(), + survey.getSource().getId(), + survey.getId(), + survey.getSource().getShortWording(), + survey.getYear(), part.getCampaign().getPeriod(), part.getId(), part.getClosingDate(), - questioningAccreditation.getQuestioning().getSurveyUnit().getIdSu(), - questioningAccreditation.getQuestioning().getSurveyUnit().getIdentificationName(), + su.getIdSu(), + su.getIdentificationName(), questioningAccreditation.isMain(), questioningEvent.map(QuestioningEvent::getType).orElse(null), - questioning.getId().toString() + questioning.getId().toString(), + moogService.getReadOnlyUrl(part.getCampaign().getId(), su.getIdSu()) )); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java index 6439e675..43561200 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/AccreditationDetailDto.java @@ -14,6 +14,8 @@ public class AccreditationDetailDto { private String sourceId; + + private String surveyId; private String sourceWording; private int year; private PeriodEnum period; @@ -24,6 +26,7 @@ public class AccreditationDetailDto { private boolean isMain; private TypeQuestioningEvent lastEvent; private String questioningId; + private String questioningUrl; } From 26fdb53c245ee90caa8b3488619eddd03664c590 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 5 Mar 2024 15:45:43 +0100 Subject: [PATCH 094/111] Update SearchSurveyUnitController.java --- .../query/controller/SearchSurveyUnitController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java index e2bfa25e..936b41ce 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java @@ -44,7 +44,7 @@ public class SearchSurveyUnitController { @GetMapping(path = Constants.API_SURVEYUNITS_CONTACTS, produces = "application/json") - @Operation(summary = "Get contacts having accreditations to repond for a survey unit ") + @Operation(summary = "Get contacts authorised to respond to a survey for a survey unit") public ResponseEntity> getSurveyUnitContacts( @PathVariable("id") String id) { From 2c8667597d31c376e068be555d074a0ea8d276e8 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 5 Mar 2024 17:33:53 +0100 Subject: [PATCH 095/111] feat: add endpoint search partitionings by survey units --- .../constants/Constants.java | 3 +- .../SearchSurveyUnitController.java | 46 +++++++++++++++++-- .../query/dto/SurveyUnitPartitioningDto.java | 23 ++++++++++ 3 files changed, 67 insertions(+), 5 deletions(-) create mode 100644 src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index 0c63d2ae..c9d52a85 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -86,8 +86,9 @@ private Constants() { public static final String API_CONTACTS_SEARCH = "/api/contacts/search"; public static final String API_CONTACTS_ACCREDITATIONS = "/api/contacts/{id}/accreditations"; public static final String API_MY_QUESTIONINGS_ID = "/api/contacts/questionings"; + public static final String API_SURVEY_UNITS_CONTACTS = "/api/survey_units/{id}/contacts"; + public static final String API_SURVEY_UNITS_PARTITIONINGS = "/api/survey_units/{id}/partitionings"; - public static final String API_SURVEYUNITS_CONTACTS = "/api/survey_units/{id}/contacts"; // API WEBCLIENT diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java index 936b41ce..189654fe 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchSurveyUnitController.java @@ -3,12 +3,18 @@ import fr.insee.survey.datacollectionmanagement.constants.Constants; import fr.insee.survey.datacollectionmanagement.contact.domain.Contact; import fr.insee.survey.datacollectionmanagement.contact.service.ContactService; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Partitioning; +import fr.insee.survey.datacollectionmanagement.metadata.domain.Survey; import fr.insee.survey.datacollectionmanagement.metadata.service.PartitioningService; import fr.insee.survey.datacollectionmanagement.query.dto.SearchSurveyUnitContactDto; +import fr.insee.survey.datacollectionmanagement.query.dto.SurveyUnitPartitioningDto; import fr.insee.survey.datacollectionmanagement.questioning.domain.Questioning; import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; +import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningEvent; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; +import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningEventService; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningService; +import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; @@ -18,11 +24,10 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; @RestController @PreAuthorize("@AuthorizeMethodDecider.isInternalUser() " @@ -42,8 +47,10 @@ public class SearchSurveyUnitController { private final PartitioningService partitioningService; + private final QuestioningEventService questioningEventService; - @GetMapping(path = Constants.API_SURVEYUNITS_CONTACTS, produces = "application/json") + + @GetMapping(path = Constants.API_SURVEY_UNITS_CONTACTS, produces = "application/json") @Operation(summary = "Get contacts authorised to respond to a survey for a survey unit") public ResponseEntity> getSurveyUnitContacts( @PathVariable("id") String id) { @@ -80,4 +87,35 @@ public ResponseEntity> getSurveyUnitContacts( } + + @GetMapping(path = Constants.API_SURVEY_UNITS_PARTITIONINGS, produces = "application/json") + @Operation(summary = "Get contacts authorised to respond to a survey for a survey unit") + public ResponseEntity> getSurveyUnitPartitionings( + @PathVariable("id") String id, + @RequestParam(defaultValue = "false") boolean isFilterOpened) { + + List listParts = new ArrayList<>(); + Set setQuestionings = questioningService.findBySurveyUnitIdSu(id); + for (Questioning questioning : setQuestionings) { + Partitioning part = partitioningService.findById(questioning.getIdPartitioning()); + Optional questioningEvent = questioningEventService.getLastQuestioningEvent(questioning, TypeQuestioningEvent.STATE_EVENTS); + + if (!isFilterOpened || partitioningService.isOnGoing(part, new Date())) { + Survey survey = part.getCampaign().getSurvey(); + listParts.add(new SurveyUnitPartitioningDto( + survey.getSource().getShortWording(), + survey.getYear(), + part.getCampaign().getPeriod(), + part.getCampaign().getCampaignWording(), + part.getClosingDate(), + questioningEvent.map(QuestioningEvent::getType).orElse(null) + )); + } + + } + + return new ResponseEntity<>(listParts, HttpStatus.OK); + + } + } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java new file mode 100644 index 00000000..e5d396a9 --- /dev/null +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java @@ -0,0 +1,23 @@ +package fr.insee.survey.datacollectionmanagement.query.dto; + +import fr.insee.survey.datacollectionmanagement.metadata.util.PeriodEnum; +import fr.insee.survey.datacollectionmanagement.questioning.util.TypeQuestioningEvent; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +@Getter +@Setter +@AllArgsConstructor +public class SurveyUnitPartitioningDto { + + private String sourceWording; + private int year; + private PeriodEnum period; + private String campaingWording; + private Date partioningClosingDate; + private TypeQuestioningEvent lastEvent; + +} From ee7eb571e859c514b5c32d04ff144d9595e87b01 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Mar 2024 16:26:10 +0100 Subject: [PATCH 096/111] feat: add search survey unit --- .../constants/Constants.java | 3 ++ .../controller/SurveyUnitController.java | 36 +++++++++++++------ .../repository/SurveyUnitRepository.java | 24 +++++++++---- .../service/SurveyUnitService.java | 2 ++ .../service/impl/SurveyUnitServiceImpl.java | 8 +++-- 5 files changed, 55 insertions(+), 18 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index c9d52a85..f12fedb9 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -89,6 +89,9 @@ private Constants() { public static final String API_SURVEY_UNITS_CONTACTS = "/api/survey_units/{id}/contacts"; public static final String API_SURVEY_UNITS_PARTITIONINGS = "/api/survey_units/{id}/partitionings"; + public static final String API_SURVEY_UNITS_SEARCH = "/api/survey_units/search"; + + // API WEBCLIENT diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java index 799f3649..01504ff5 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/controller/SurveyUnitController.java @@ -26,7 +26,6 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.text.ParseException; import java.util.List; @RestController @@ -59,6 +58,26 @@ public Page getSurveyUnits( return new SurveyUnitPage(listSuDto, pageable, pageC.getTotalElements()); } + @Operation(summary = "Multi-criteria search survey-unit") + @GetMapping(value = Constants.API_SURVEY_UNITS_SEARCH, produces = "application/json") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = SurveyUnitPage.class))), + @ApiResponse(responseCode = "404", description = "Not found"), + @ApiResponse(responseCode = "400", description = "Bad Request") + }) + public Page searchSurveyUnits( + @RequestParam(required = false) String idSu, + @RequestParam(required = false) String identificationCode, + @RequestParam(required = false) String identificationName, + @RequestParam(defaultValue = "0") Integer page, + @RequestParam(defaultValue = "20") Integer size, + @RequestParam(defaultValue = "id_su") String sort) { + Pageable pageable = PageRequest.of(page, size, Sort.by(sort)); + Page pageC = surveyUnitService.findByParameters(idSu, identificationCode, identificationName, pageable); + List listSuDto = pageC.stream().map(this::convertToDto).toList(); + return new SurveyUnitPage(listSuDto, pageable, pageC.getTotalElements()); + } + @Operation(summary = "Search for a survey unit by its id") @GetMapping(value = Constants.API_SURVEY_UNITS_ID, produces = "application/json") @ApiResponses(value = { @@ -66,7 +85,7 @@ public Page getSurveyUnits( @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad Request") }) - public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { + public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); return ResponseEntity.status(HttpStatus.OK).body(convertToDto(surveyUnit)); @@ -79,7 +98,7 @@ public ResponseEntity findSurveyUnit(@PathVariable("id") String id) { @ApiResponse(responseCode = "201", description = "Created", content = @Content(schema = @Schema(implementation = SurveyUnitDto.class))), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody @Valid SurveyUnitDto surveyUnitDto) { + public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBody @Valid SurveyUnitDto surveyUnitDto) { if (!surveyUnitDto.getIdSu().equalsIgnoreCase(id)) { throw new NotMatchException("id and idSu don't match"); } @@ -90,11 +109,8 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo responseHeaders.set(HttpHeaders.LOCATION, ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(surveyUnitDto.getIdSu()).toUriString()); - try { - surveyUnit = convertToEntity(surveyUnitDto); - } catch (ParseException e) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Impossible to parse survey unit"); - } + surveyUnit = convertToEntity(surveyUnitDto); + try { surveyUnitService.findbyId(surveyUnitDto.getIdSu()); responseStatus = HttpStatus.OK; @@ -116,7 +132,7 @@ public ResponseEntity putSurveyUnit(@PathVariable("id") String id, @RequestBo @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "400", description = "Bad request") }) - public ResponseEntity deleteSurveyUnit(@PathVariable("id") String id) { + public ResponseEntity deleteSurveyUnit(@PathVariable("id") String id) { SurveyUnit surveyUnit = surveyUnitService.findbyId(StringUtils.upperCase(id)); try { @@ -137,7 +153,7 @@ private SurveyUnitDto convertToDto(SurveyUnit surveyUnit) { return modelMapper.map(surveyUnit, SurveyUnitDto.class); } - private SurveyUnit convertToEntity(SurveyUnitDto surveyUnitDto) throws ParseException { + private SurveyUnit convertToEntity(SurveyUnitDto surveyUnitDto) { return modelMapper.map(surveyUnitDto, SurveyUnit.class); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/repository/SurveyUnitRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/repository/SurveyUnitRepository.java index 7491487e..427c15a3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/repository/SurveyUnitRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/repository/SurveyUnitRepository.java @@ -1,18 +1,30 @@ package fr.insee.survey.datacollectionmanagement.questioning.repository; -import java.util.List; - +import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; -import fr.insee.survey.datacollectionmanagement.questioning.domain.SurveyUnit; +import java.util.List; public interface SurveyUnitRepository extends JpaRepository { - public List findAllByIdentificationCode(String identificationCode); + List findAllByIdentificationCode(String identificationCode); + + List findByIdentificationNameIgnoreCase(String identificationName); + + @Query(nativeQuery = true, value = """ + SELECT * + FROM survey_unit su + WHERE (:id_su is null or upper(su.id_su) like upper(concat('%', :id_su, '%'))) + AND (:identification_name is null or upper(su.identification_name) like upper(concat('%', :identification_name, '%'))) + AND (:identification_code is null or upper(su.identification_code) like upper(concat('%', :identification_code, '%'))) + """) + Page findByParameters(@Param("id_su") String idSu, @Param("identification_code") String identificationCode, @Param("identification_name") String identificationName, Pageable pageable); - public List findByIdentificationNameIgnoreCase(String identificationName); @Query(nativeQuery = true, value = "SELECT * FROM survey_unit ORDER BY random() LIMIT 1") - public SurveyUnit findRandomSurveyUnit(); + SurveyUnit findRandomSurveyUnit(); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java index 61c95856..8af5edca 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/SurveyUnitService.java @@ -16,6 +16,8 @@ public interface SurveyUnitService { public Page findAll(Pageable pageable); + public Page findByParameters(String idSu, String identificationCode, String identificationName, Pageable pageable); + public SurveyUnit saveSurveyUnit(SurveyUnit surveyUnit); public SurveyUnit saveSurveyUnitAndAddress(SurveyUnit surveyUnit); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java index 7c087605..37dbd70a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/service/impl/SurveyUnitServiceImpl.java @@ -42,6 +42,11 @@ public Page findAll(Pageable pageable) { return surveyUnitRepository.findAll(pageable); } + @Override + public Page findByParameters(String idSu, String identificationCode, String identificationName, Pageable pageable) { + return surveyUnitRepository.findByParameters(idSu, identificationCode, identificationName, pageable); + } + @Override public SurveyUnit saveSurveyUnit(SurveyUnit surveyUnit) { return surveyUnitRepository.save(surveyUnit); @@ -56,8 +61,7 @@ public SurveyUnit saveSurveyUnitAndAddress(SurveyUnit surveyUnit) { if (existingSurveyUnit.getSurveyUnitAddress() != null) { surveyUnit.getSurveyUnitAddress().setId(existingSurveyUnit.getSurveyUnitAddress().getId()); } - } - catch (NotFoundException e){ + } catch (NotFoundException e) { log.debug("Survey unit does not exist"); } surveyUnitAddressRepository.save(surveyUnit.getSurveyUnitAddress()); From 95e981d96a8f0f2f6f2c031710db181bfd38682d Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 6 Mar 2024 17:03:05 +0100 Subject: [PATCH 097/111] fix: path names --- .../datacollectionmanagement/constants/Constants.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java index f12fedb9..7053e06b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/constants/Constants.java @@ -86,10 +86,10 @@ private Constants() { public static final String API_CONTACTS_SEARCH = "/api/contacts/search"; public static final String API_CONTACTS_ACCREDITATIONS = "/api/contacts/{id}/accreditations"; public static final String API_MY_QUESTIONINGS_ID = "/api/contacts/questionings"; - public static final String API_SURVEY_UNITS_CONTACTS = "/api/survey_units/{id}/contacts"; - public static final String API_SURVEY_UNITS_PARTITIONINGS = "/api/survey_units/{id}/partitionings"; + public static final String API_SURVEY_UNITS_CONTACTS = "/api/survey-units/{id}/contacts"; + public static final String API_SURVEY_UNITS_PARTITIONINGS = "/api/survey-units/{id}/partitionings"; - public static final String API_SURVEY_UNITS_SEARCH = "/api/survey_units/search"; + public static final String API_SURVEY_UNITS_SEARCH = "/api/survey-units/search"; From 66e0f406c3c87a7357a55d5cbeabd24aed6d6a0e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 11 Mar 2024 11:14:02 +0100 Subject: [PATCH 098/111] fix: events for getLastQuestioningEvents --- .../questioning/util/TypeQuestioningEvent.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/TypeQuestioningEvent.java b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/TypeQuestioningEvent.java index 67b40825..b27b32c3 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/TypeQuestioningEvent.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/questioning/util/TypeQuestioningEvent.java @@ -22,8 +22,7 @@ public enum TypeQuestioningEvent { HC, INITLA, PARTIELINT, - PND, - FOLLOWUP); + PND); public static final List FOLLOWUP_EVENTS = Arrays.asList( VALINT, From a1dc36ac881742d0877bd67274ee094038f3222e Mon Sep 17 00:00:00 2001 From: y72wvh Date: Mon, 11 Mar 2024 11:25:24 +0100 Subject: [PATCH 099/111] Update SurveyUnitPartitioningDto.java --- .../query/dto/SurveyUnitPartitioningDto.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java index e5d396a9..b14fec4a 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SurveyUnitPartitioningDto.java @@ -16,7 +16,7 @@ public class SurveyUnitPartitioningDto { private String sourceWording; private int year; private PeriodEnum period; - private String campaingWording; + private String campaignWording; private Date partioningClosingDate; private TypeQuestioningEvent lastEvent; From 8e9f22aa793b1633ed7e3b8a7f66a4083a6e83b9 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 13 Mar 2024 08:55:43 +0100 Subject: [PATCH 100/111] fix: search contact (pageNo to page and add city and phone) --- .../query/controller/SearchContactController.java | 12 ++++++------ .../query/dto/SearchContactDto.java | 2 ++ .../query/service/impl/SearchContactServiceImpl.java | 4 +++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 6349a159..77a21146 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -69,18 +69,18 @@ public ResponseEntity> searchContacts( @RequestParam(required = false) String identifier, @RequestParam(required = false) String name, @RequestParam(required = false) String email, - @RequestParam(defaultValue = "0") Integer pageNo, + @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) { log.info( - "Search contact: identifier = {}, name= {}, email= {}, pageNo= {}, pageSize= {} ", - identifier, name, email, pageNo, pageSize); + "Search contact: identifier = {}, name= {}, email= {}, page= {}, pageSize= {} ", + identifier, name, email, page, pageSize); - Pageable pageable = PageRequest.of(pageNo, pageSize); + Pageable pageable = PageRequest.of(page, pageSize); - Page page = searchContactService.searchContactCrossDomain(identifier, name, email, + Page pageSearchContact = searchContactService.searchContactCrossDomain(identifier, name, email, pageable); - return new ResponseEntity<>(page, HttpStatus.OK); + return new ResponseEntity<>(pageSearchContact, HttpStatus.OK); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java index b13d888f..85afbfcc 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/dto/SearchContactDto.java @@ -13,6 +13,8 @@ public class SearchContactDto { private String firstName; private String lastName; private String email; + private String phone; + private String city; private String function; private List listSurveyUnitNames; private List listSourcesId; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 70c549c9..23c7d5f4 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -42,7 +42,7 @@ public Page searchContactCrossDomain( if (!StringUtils.isEmpty(identifier)) { Contact c = contactService.findByIdentifier(identifier.toUpperCase()); - pageContact = new PageImpl<>(Collections.singletonList(c),pageable,1); + pageContact = new PageImpl<>(Collections.singletonList(c), pageable, 1); } else if (!StringUtils.isEmpty(email)) { pageContact = contactService.findByEmail(email, pageable); @@ -65,6 +65,8 @@ private SearchContactDto transformContactTSearchContactDto(Contact c) { searchContact.setFirstName(c.getFirstName()); searchContact.setLastName(c.getLastName()); searchContact.setEmail(c.getEmail()); + searchContact.setPhone(c.getPhone()); + searchContact.setCity(c.getAddress() != null ? c.getAddress().getCityName() : ""); searchContact.setFunction(c.getFunction()); List listAccreditations = questioningAccreditationService.findByContactIdentifier(c.getIdentifier()); searchContact.setListSurveyUnitNames(listAccreditations.stream().map(a -> a.getQuestioning().getSurveyUnit().getIdSu()).distinct().toList()); From 5df0db8f7affe1e88198aacf75505cc29e0eb233 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 13 Mar 2024 10:35:21 +0100 Subject: [PATCH 101/111] build: version 2.0.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e761bdd9..ed4d4d0e 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 1.1.12 + 2.0.0 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI From 2193b060de40e9770032d2a69a8be60d5cffa125 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 14 Mar 2024 09:28:27 +0100 Subject: [PATCH 102/111] refactor: search contacts --- .../contact/repository/ContactRepository.java | 25 +++++++++++-------- .../contact/service/ContactService.java | 4 +-- .../service/impl/ContactServiceImpl.java | 10 ++------ .../impl/SearchContactServiceImpl.java | 16 +----------- 4 files changed, 18 insertions(+), 37 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java index 2ddaf912..cde5fe69 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java @@ -20,17 +20,20 @@ public interface ContactRepository extends PagingAndSortingRepository findByNameIgnoreCase(String name, Pageable pageable); - - Page findByEmailIgnoreCase(String email, Pageable pageable); + SELECT + * + FROM + contact c + WHERE + (:identifier IS NULL OR UPPER(c.identifier) = UPPER(:identifier)) + AND + (:name IS NULL OR UPPER(CONCAT(c.first_name, ' ', c.last_name)) LIKE UPPER(CONCAT('%', :name, '%'))) + AND + (:email IS NULL OR UPPER(c.email) = UPPER(:email)) + """, + nativeQuery = true + ) + Page findByParameters(String identifier, String name, String email, Pageable pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index 72a766f9..463f666b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -44,9 +44,7 @@ public interface ContactService { */ void deleteContact(String identifier); - Page findByName(String name, Pageable pageable); - - Page findByEmail(String email, Pageable pageable); + Page findByParameters(String identifier, String name, String email, Pageable pageable); Contact createContactAddressEvent(Contact contact, JsonNode payload); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 061f0271..43f3df80 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -53,14 +53,8 @@ public void deleteContact(String identifier) { } @Override - public Page findByName(String name, Pageable pageable) { - return contactRepository.findByNameIgnoreCase(name.toUpperCase(), pageable); - } - - - @Override - public Page findByEmail(String email, Pageable pageable) { - return contactRepository.findByEmailIgnoreCase(email,pageable); + public Page findByParameters(String identifier, String name, String email, Pageable pageable) { + return contactRepository.findByParameters(identifier,name,email,pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 23c7d5f4..83ca4cd8 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -8,14 +8,12 @@ import fr.insee.survey.datacollectionmanagement.questioning.domain.QuestioningAccreditation; import fr.insee.survey.datacollectionmanagement.questioning.service.QuestioningAccreditationService; import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.StringUtils; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.ArrayList; -import java.util.Collections; import java.util.List; @Service @@ -38,20 +36,8 @@ public Page searchContactCrossDomain( List listSearchContact = new ArrayList<>(); - Page pageContact; + Page pageContact = contactService.findByParameters(identifier, name, email, pageable); - if (!StringUtils.isEmpty(identifier)) { - Contact c = contactService.findByIdentifier(identifier.toUpperCase()); - pageContact = new PageImpl<>(Collections.singletonList(c), pageable, 1); - } else if (!StringUtils.isEmpty(email)) { - pageContact = contactService.findByEmail(email, pageable); - - } else if (!StringUtils.isEmpty(name)) { - pageContact = contactService.findByName(name, pageable); - } else { - pageContact = contactService.findAll(pageable); - } - assert pageContact != null; for (Contact c : pageContact) { listSearchContact.add(transformContactTSearchContactDto(c)); } From 80767f2005dd8e7c878d1abec0ce6032bf29a657 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Thu, 14 Mar 2024 09:31:10 +0100 Subject: [PATCH 103/111] refactor: search contacts --- .../contact/service/ContactService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index 463f666b..e4b194e1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -25,7 +25,7 @@ public interface ContactService { /** * Find a contact by its identifier. * - * @param identifier + * @param identifier contact identifier * @return contact found */ Contact findByIdentifier(String identifier) ; @@ -33,7 +33,7 @@ public interface ContactService { /** * Update an existing contact and its address, or creates a new one * - * @param contact + * @param contact Contact to save * @return contact updated */ Contact saveContact(Contact contact); From 5cd4c607a11afcdde0029c175294169078b79ff4 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 15 Mar 2024 14:31:21 +0100 Subject: [PATCH 104/111] fix: add sort param in search contact --- .../query/controller/SearchContactController.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 77a21146..22c710cb 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -27,6 +27,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -70,13 +71,14 @@ public ResponseEntity> searchContacts( @RequestParam(required = false) String name, @RequestParam(required = false) String email, @RequestParam(defaultValue = "0") Integer page, - @RequestParam(defaultValue = "10") Integer pageSize) { + @RequestParam(defaultValue = "10") Integer pageSize, + @RequestParam(defaultValue = "identifier") String sort) { log.info( "Search contact: identifier = {}, name= {}, email= {}, page= {}, pageSize= {} ", identifier, name, email, page, pageSize); - Pageable pageable = PageRequest.of(page, pageSize); + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sort)); Page pageSearchContact = searchContactService.searchContactCrossDomain(identifier, name, email, pageable); From 45e17864559ca454153b51c44eea2d88e39966ff Mon Sep 17 00:00:00 2001 From: y72wvh Date: Fri, 15 Mar 2024 15:53:25 +0100 Subject: [PATCH 105/111] feat: add usual company Name --- .../survey/datacollectionmanagement/contact/domain/Contact.java | 1 + .../survey/datacollectionmanagement/contact/dto/AddressDto.java | 1 + .../survey/datacollectionmanagement/contact/dto/ContactDto.java | 1 + .../contact/dto/ContactFirstLoginDto.java | 1 + 4 files changed, 4 insertions(+) diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java index 391cd7b0..544110cd 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/domain/Contact.java @@ -30,6 +30,7 @@ public enum Gender { private String firstName; private String email; private String function; + private String usualCompanyName; private String phone; private String comment; @Column(columnDefinition = "boolean default false") diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java index 00305d1c..300afba0 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java @@ -21,6 +21,7 @@ public class AddressDto { private String cedexCode; private String cedexName; private String specialDistribution; + private String usualCompanyName; private String countryCode; private String countryName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java index 172a55f5..a89f7702 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactDto.java @@ -19,6 +19,7 @@ public class ContactDto{ private String function; private String email; private String phone; + private String usualCompanyName; private AddressDto address; } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java index aacbf99d..2a6d262b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/ContactFirstLoginDto.java @@ -18,6 +18,7 @@ public class ContactFirstLoginDto{ private String function; private String email; private String phone; + private String usualCompanyName; private boolean firstConnect; private AddressDto address; From c5bbaa259bef52631d02058225d375fe5771dcd7 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 19 Mar 2024 11:11:45 +0100 Subject: [PATCH 106/111] feat: improve search contacts (add city and function) --- pom.xml | 2 +- .../contact/dto/AddressDto.java | 1 - .../contact/repository/ContactRepository.java | 10 +++++++++- .../contact/service/ContactService.java | 2 +- .../contact/service/impl/ContactServiceImpl.java | 9 ++++++--- .../query/controller/SearchContactController.java | 4 +++- .../query/service/SearchContactService.java | 4 ++++ .../query/service/impl/SearchContactServiceImpl.java | 4 +++- 8 files changed, 27 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index 63f090ed..ff2b11d4 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 2.1.0 + 2.1.1 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java index 300afba0..00305d1c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/dto/AddressDto.java @@ -21,7 +21,6 @@ public class AddressDto { private String cedexCode; private String cedexName; private String specialDistribution; - private String usualCompanyName; private String countryCode; private String countryName; diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java index cde5fe69..41b9ed5b 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java @@ -24,16 +24,24 @@ public interface ContactRepository extends PagingAndSortingRepository findByParameters(String identifier, String name, String email, Pageable pageable); + Page findByParameters(String identifier, String name, String email, String city, String function, Pageable pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java index e4b194e1..96d871bf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/ContactService.java @@ -44,7 +44,7 @@ public interface ContactService { */ void deleteContact(String identifier); - Page findByParameters(String identifier, String name, String email, Pageable pageable); + Page findByParameters(String identifier, String name, String email, String city, String function, Pageable pageable); Contact createContactAddressEvent(Contact contact, JsonNode payload); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java index 43f3df80..c3e64f39 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/service/impl/ContactServiceImpl.java @@ -15,7 +15,10 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.*; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Service @RequiredArgsConstructor @@ -53,8 +56,8 @@ public void deleteContact(String identifier) { } @Override - public Page findByParameters(String identifier, String name, String email, Pageable pageable) { - return contactRepository.findByParameters(identifier,name,email,pageable); + public Page findByParameters(String identifier, String name, String email, String city, String function, Pageable pageable) { + return contactRepository.findByParameters(identifier, name, email, city, function, pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java index 22c710cb..97475ba1 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/controller/SearchContactController.java @@ -70,6 +70,8 @@ public ResponseEntity> searchContacts( @RequestParam(required = false) String identifier, @RequestParam(required = false) String name, @RequestParam(required = false) String email, + @RequestParam(required = false) String city, + @RequestParam(required = false) String function, @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "identifier") String sort) { @@ -80,7 +82,7 @@ public ResponseEntity> searchContacts( Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sort)); - Page pageSearchContact = searchContactService.searchContactCrossDomain(identifier, name, email, + Page pageSearchContact = searchContactService.searchContactCrossDomain(identifier, name, email, city, function, pageable); return new ResponseEntity<>(pageSearchContact, HttpStatus.OK); diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java index a40a8dcd..c7a450cf 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/SearchContactService.java @@ -11,6 +11,8 @@ public interface SearchContactService { * @param identifier contact identifier * @param name (first name or and lastName) * @param email contact email + * @param city contact city + * @param function contact function * @return */ @@ -18,5 +20,7 @@ Page searchContactCrossDomain( String identifier, String name, String email, + String city, + String function, Pageable pageable); } diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java index 83ca4cd8..02378afa 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/query/service/impl/SearchContactServiceImpl.java @@ -32,11 +32,13 @@ public Page searchContactCrossDomain( String identifier, String name, String email, + String city, + String function, Pageable pageable) { List listSearchContact = new ArrayList<>(); - Page pageContact = contactService.findByParameters(identifier, name, email, pageable); + Page pageContact = contactService.findByParameters(identifier, name, email,city, function, pageable); for (Contact c : pageContact) { listSearchContact.add(transformContactTSearchContactDto(c)); From 89156c1e5d672b4d4e60dc7f81d6a1743b40a6f2 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Tue, 19 Mar 2024 13:47:13 +0100 Subject: [PATCH 107/111] fix: search contact by function containing --- pom.xml | 2 +- .../contact/repository/ContactRepository.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ff2b11d4..de8d4ea0 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 2.1.1 + 2.1.2 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI diff --git a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java index 41b9ed5b..976e067c 100644 --- a/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java +++ b/src/main/java/fr/insee/survey/datacollectionmanagement/contact/repository/ContactRepository.java @@ -35,7 +35,7 @@ public interface ContactRepository extends PagingAndSortingRepository Date: Wed, 27 Mar 2024 15:55:31 +0100 Subject: [PATCH 108/111] Update renovate.json (#57) add package rules --- renovate.json | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index 39a2b6e9..17869171 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,45 @@ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "config:base" - ] + ], + "packageRules": [ + { + "matchPackagePatterns": ["*"], + "labels": ["dependencies"], + "bumpVersion": "patch", + "dependencyDashboardApproval": true + }, + { + "groupName": "spring", + "groupSlug": "spring", + "matchPackagePatterns": ["org.springframework.*"], + "bumpVersion": "minor", + "dependencyDashboardApproval": true + }, + { + "groupName": "all minor dependencies", + "groupSlug": "all-minor-patch", + "matchPackagePatterns": ["*"], + "matchUpdateTypes": ["minor", "patch"], + "bumpVersion": "patch", + "dependencyDashboardApproval": true + }, + { + "groupName": "spring minor dependencies", + "groupSlug": "spring-minor-patch", + "matchPackagePatterns": ["org.springframework.*"], + "matchUpdateTypes": ["minor", "patch"], + "bumpVersion": "patch", + "dependencyDashboardApproval": true + } + ], + "vulnerabilityAlerts": { + "enabled": true, + "addLabels": ["security"], + "bumpVersion": "patch", + "schedule": ["before 5:00am"] + }, + "schedule": ["every weekend"], + "timezone": "Europe/Paris" +} } From f2df1d300d6186c89b27bf4c2102067c7a7c1f65 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 27 Mar 2024 16:25:13 +0100 Subject: [PATCH 109/111] fix: merge main into develop --- .../metadata/controller/SurveyControllerTest.java | 11 +++++++---- .../query/controller/MoogControllerTest.java | 1 - 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java index 731ce415..c9ec591d 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/metadata/controller/SurveyControllerTest.java @@ -19,11 +19,14 @@ import org.springframework.test.web.servlet.MockMvc; import static org.junit.jupiter.api.Assertions.*; -import java.util.Optional; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + @AutoConfigureMockMvc @SpringBootTest diff --git a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java index 0754b3b2..b34a4de8 100644 --- a/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java +++ b/src/test/java/fr/insee/survey/datacollectionmanagement/query/controller/MoogControllerTest.java @@ -17,7 +17,6 @@ @AutoConfigureMockMvc @SpringBootTest -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @ActiveProfiles("test") @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) class MoogControllerTest { From 5b86d812f3f069b3893613cdb4c310fe4938629e Mon Sep 17 00:00:00 2001 From: Betty Becuwe <77614323+BettyB979@users.noreply.github.com> Date: Thu, 4 Apr 2024 10:14:39 +0200 Subject: [PATCH 110/111] Update Dockerfile (#58) --- Dockerfile | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index fb89e2e3..1e044d0a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,14 @@ -FROM eclipse-temurin:17.0.7_7-jre -WORKDIR /application -RUN rm -rf /application -ADD target/*.jar /application/app.jar -ENTRYPOINT ["java", "-jar", "/application/app.jar"] \ No newline at end of file +FROM eclipse-temurin:21.0.2_13-jre-alpine + +WORKDIR /opt/app/ +COPY ./target/*.jar /opt/app/app.jar + +# Setup a non-root user context (security) +RUN addgroup -g 1000 tomcatgroup +RUN adduser -D -s / -u 1000 tomcatuser -G tomcatgroup +RUN mkdir /opt/app/temp-files +RUN chown -R 1000:1000 /opt/app + +USER 1000 + +ENTRYPOINT ["java", "-jar", "/opt/app/app.jar"] From 5a2a68e7ced2252acfbf681e840f6b3574183e4c Mon Sep 17 00:00:00 2001 From: Betty Becuwe <77614323+BettyB979@users.noreply.github.com> Date: Thu, 4 Apr 2024 10:26:27 +0200 Subject: [PATCH 111/111] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 9796a691..ffa8293c 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ fr.insee.survey platine-management - 2.1.2 + 2.1.3 platine-management REST API for communication between DB and Platine-Management UI and Platine-My-Surveys UI @@ -201,4 +201,4 @@ - \ No newline at end of file +