From 82070e6e206f137d62e607f78ebc1e1616add088 Mon Sep 17 00:00:00 2001 From: y72wvh Date: Wed, 22 Nov 2023 09:19:54 +0100 Subject: [PATCH] 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());