diff --git a/pom.xml b/pom.xml index c8c9107b3..05a429ee0 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.8 + 2.7.16 @@ -13,7 +13,7 @@ fr.insee.rmes Bauhaus-BO war - 3.6.1 + 3.6.2 Bauhaus-Back-Office Back-office services for Bauhaus https://github.com/InseeFr/Bauhaus-Back-Office @@ -28,18 +28,6 @@ http://www.insee.fr - - Alice Lambois - alice.lambois@insee.fr - - - Nicolas Laval - nicolas.laval@insee.fr - - - Olivier Pucher - olivier.pucher@insee.fr - Jérôme Bourgeois jerome.bourgeois@insee.fr @@ -49,19 +37,26 @@ bauhaus - 11 + 17 - 1.6.6 + 1.7.0 2.13.1 - 3.7.7 + 4.3.6 2.1.12 - 2.17.1 - 2.0.3 + 2.0.4 5.8.2 0.8.5 UTF-8 2.22.2 3.4.1 + 20230618 + 0.64.8 + 4.0.3 + 1.16 + 12.3 + + src/main/java/fr/insee/rmes/queries/**/*, @@ -85,11 +80,22 @@ spring-boot-starter-web - org.springframework.boot - spring-boot-starter-logging + org.apache.logging.log4j + log4j-to-slf4j + + org.springframework.boot + spring-boot-starter-tomcat + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + com.fasterxml.jackson.dataformat jackson-dataformat-xml @@ -97,13 +103,13 @@ org.zeroturnaround zt-zip - 1.14 + ${zt.version} jar com.sun.xml.bind jaxb-impl - 2.3.3 + ${jaxb.version} runtime @@ -133,15 +139,21 @@ org.springframework.boot spring-boot-starter-test + + + com.vaadin.external.google + android-json + + test - - - org.springframework.boot - spring-boot-starter-log4j2 + org.springframework.security + spring-security-test + test + org.springdoc @@ -154,6 +166,12 @@ org.eclipse.rdf4j rdf4j-repository-http ${rdf4j.version} + + + org.slf4j + jcl-over-slf4j + + org.eclipse.rdf4j @@ -170,10 +188,9 @@ org.json json - 20211205 + ${json.version} - org.apache.activemq @@ -186,15 +203,15 @@ - jakarta.jms - jakarta.jms-api + jakarta.jms + jakarta.jms-api net.sf.saxon Saxon-HE - 11.1.1 + ${saxon.version} xml-apis @@ -218,23 +235,13 @@ fr.opensagres.xdocreport.template.freemarker ${xdocreport.version} - - fr.opensagres.xdocreport - fr.opensagres.xdocreport.converter.odt.odfdom - ${xdocreport.version} - - - xerces - xercesImpl - - - + com.vladsch.flexmark - flexmark-all - 0.64.0 + flexmark-html2md-converter + 0.64.8 @@ -245,6 +252,9 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.tomcat.embed + diff --git a/src/main/java/fr/insee/rmes/Bauhaus.java b/src/main/java/fr/insee/rmes/Bauhaus.java index 7b5ba9a6c..f6cdf860e 100644 --- a/src/main/java/fr/insee/rmes/Bauhaus.java +++ b/src/main/java/fr/insee/rmes/Bauhaus.java @@ -1,24 +1,28 @@ package fr.insee.rmes; -import fr.insee.rmes.config.keycloak.KeycloakServerZoneConfiguration; -import org.springframework.boot.SpringApplication; +import fr.insee.rmes.config.PropertiesLogger; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication @ConfigurationPropertiesScan public class Bauhaus extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Bauhaus.class); - } - public static void main(String[] args) { - SpringApplication.run(Bauhaus.class, args); - } + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder applicationBuilder) { + return configureApplicationBuilder(applicationBuilder); + } + + public static void main(String[] args) { + configureApplicationBuilder(new SpringApplicationBuilder()).build().run(args); + } + + public static SpringApplicationBuilder configureApplicationBuilder(SpringApplicationBuilder springApplicationBuilder) { + return springApplicationBuilder.sources(Bauhaus.class) + .listeners(new PropertiesLogger()); + } + } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java index 2fa04eed6..d41524373 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java @@ -1,9 +1,7 @@ package fr.insee.rmes.bauhaus_services; -import fr.insee.rmes.exceptions.RmesNotFoundException; -import org.springframework.web.multipart.MultipartFile; - import fr.insee.rmes.exceptions.RmesException; +import org.springframework.web.multipart.MultipartFile; public interface ClassificationsService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java index e460ca1d3..36950ec70 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java @@ -1,7 +1,6 @@ package fr.insee.rmes.bauhaus_services; import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.webservice.ConceptsResources; import org.springframework.http.ResponseEntity; import javax.servlet.http.HttpServletResponse; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/GeographyService.java b/src/main/java/fr/insee/rmes/bauhaus_services/GeographyService.java index 71af46f78..d6c4b0d8f 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/GeographyService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/GeographyService.java @@ -1,10 +1,9 @@ package fr.insee.rmes.bauhaus_services; +import fr.insee.rmes.exceptions.RmesException; import org.eclipse.rdf4j.model.IRI; import org.json.JSONObject; -import fr.insee.rmes.exceptions.RmesException; - public interface GeographyService { /****************************************************************************************** diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/OperationsDocumentationsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/OperationsDocumentationsService.java index 1f83922e9..affe1f67d 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/OperationsDocumentationsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/OperationsDocumentationsService.java @@ -1,13 +1,12 @@ package fr.insee.rmes.bauhaus_services; -import java.io.IOException; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.model.operations.documentations.MSD; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.io.IOException; public interface OperationsDocumentationsService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/OrganizationsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/OrganizationsService.java index 82a818fe7..3c7c8f604 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/OrganizationsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/OrganizationsService.java @@ -1,11 +1,11 @@ package fr.insee.rmes.bauhaus_services; -import java.util.List; - import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.organizations.Organization; +import java.util.List; + public interface OrganizationsService { IdLabelTwoLangs getOrganization(String organizationIdentifier) throws RmesException; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationPublication.java index 20d0371e5..2821cc320 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationPublication.java @@ -1,5 +1,12 @@ package fr.insee.rmes.bauhaus_services.classifications; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.ErrorCodes; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesNotFoundException; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -10,15 +17,6 @@ import org.eclipse.rdf4j.repository.RepositoryResult; import org.springframework.stereotype.Component; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotFoundException; - @Component public class ClassificationPublication extends RdfService{ diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java index d51a3ee2e..85691856c 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java @@ -15,14 +15,14 @@ import fr.insee.rmes.persistance.ontologies.INSEE; import fr.insee.rmes.persistance.sparql_queries.classifications.*; import fr.insee.rmes.utils.XhtmlToMarkdownUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleIRI; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -39,7 +39,7 @@ public class ClassificationsImpl extends RdfService implements Classifications @Autowired private ClassificationPublication classificationPublication; - static final Logger logger = LogManager.getLogger(ClassificationsImpl.class); + static final Logger logger = LoggerFactory.getLogger(ClassificationsImpl.class); @Override public String getFamilies() throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java index e7ef505c1..01e8b96c1 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java @@ -10,10 +10,10 @@ import fr.insee.rmes.persistance.sparql_queries.classifications.ClassificationsQueries; import fr.insee.rmes.persistance.sparql_queries.classifications.ItemsQueries; import fr.insee.rmes.utils.XhtmlToMarkdownUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -27,7 +27,7 @@ public class ClassificationItemServiceImpl extends RdfService implements Classif ClassificationItemUtils classificationItemUtils; - static final Logger logger = LogManager.getLogger(ClassificationItemServiceImpl.class); + static final Logger logger = LoggerFactory.getLogger(ClassificationItemServiceImpl.class); @Override public String getClassificationItems(String id) throws RmesException{ diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeList.java b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeList.java index b5b6db74f..2f128c7a0 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeList.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeList.java @@ -1,9 +1,9 @@ package fr.insee.rmes.bauhaus_services.code_list; -import java.util.List; - import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; + public class CodeList { @Schema(description = "Notation", required = true) diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListPublication.java index c2b2f295e..17636c55a 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListPublication.java @@ -4,7 +4,6 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; @@ -54,7 +53,7 @@ public void publishCodeList(Resource codelist, boolean partial) throws RmesExcep } } - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); @@ -67,7 +66,7 @@ public void publishCodeList(Resource codelist, boolean partial) throws RmesExcep repoGestion.closeStatements(statements); con.close(); } - Resource codelistToPublishRessource = PublicationUtils.tranformBaseURIToPublish(codelist); + Resource codelistToPublishRessource = publicationUtils.tranformBaseURIToPublish(codelist); repositoryPublication.publishResource(codelistToPublishRessource, model, Constants.CODELIST); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java index 2748a323a..af550d19a 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java @@ -18,8 +18,6 @@ import fr.insee.rmes.persistance.sparql_queries.code_list.CodeListQueries; import fr.insee.rmes.utils.DateUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -27,6 +25,8 @@ import org.eclipse.rdf4j.model.vocabulary.*; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -49,7 +49,7 @@ public class CodeListServiceImpl extends RdfService implements CodeListService private static final String LAST_CODE_URI_SEGMENT = "lastCodeUriSegment"; - static final Logger logger = LogManager.getLogger(CodeListServiceImpl.class); + static final Logger logger = LoggerFactory.getLogger(CodeListServiceImpl.class); @Autowired FamOpeSerIndUtils famOpeSerIndUtils; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/LangService.java b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/LangService.java index 05121b0e3..fcf80682d 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/LangService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/LangService.java @@ -1,12 +1,11 @@ package fr.insee.rmes.bauhaus_services.code_list; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.CodeListService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.exceptions.RmesException; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; @Component public class LangService extends RdfService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java index 562b0bf9c..177441fec 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java @@ -10,9 +10,9 @@ import fr.insee.rmes.utils.XMLUtils; import fr.insee.rmes.webservice.ConceptsCollectionsResources; import org.apache.commons.text.CaseUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -25,7 +25,7 @@ @Service public class ConceptsCollectionServiceImpl extends RdfService implements ConceptsCollectionService { - static final Logger logger = LogManager.getLogger(ConceptsCollectionServiceImpl.class); + static final Logger logger = LoggerFactory.getLogger(ConceptsCollectionServiceImpl.class); @Autowired CollectionExportBuilder collectionExport; @@ -158,4 +158,4 @@ private String getFileNameForExport(CollectionForExport collection, ConceptsColl } return CaseUtils.toCamelCase(collection.getPrefLabelLg1(), false) + "-" + collection.getId(); } -} +} \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java index c877415bb..c32e4fb14 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java @@ -19,10 +19,10 @@ import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.utils.XMLUtils; import org.apache.commons.text.CaseUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -42,7 +42,7 @@ public class ConceptsImpl extends RdfService implements ConceptsService { private static final String THE_CONCEPT = "The concept "; - static final Logger logger = LogManager.getLogger(ConceptsImpl.class); + static final Logger logger = LoggerFactory.getLogger(ConceptsImpl.class); @Autowired diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionsUtils.java index cc3efa2d3..e7d85cee6 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionsUtils.java @@ -1,12 +1,16 @@ package fr.insee.rmes.bauhaus_services.concepts.collections; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.insee.rmes.bauhaus_services.concepts.publication.ConceptsPublication; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.ErrorCodes; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesUnauthorizedException; +import fr.insee.rmes.model.concepts.Collection; +import fr.insee.rmes.persistance.ontologies.INSEE; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; @@ -15,25 +19,19 @@ import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.json.JSONArray; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import fr.insee.rmes.bauhaus_services.concepts.publication.ConceptsPublication; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesUnauthorizedException; -import fr.insee.rmes.model.concepts.Collection; -import fr.insee.rmes.persistance.ontologies.INSEE; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; @Component public class CollectionsUtils extends RdfService{ - static final Logger logger = LogManager.getLogger(CollectionsUtils.class); + static final Logger logger = LoggerFactory.getLogger(CollectionsUtils.class); @Autowired ConceptsPublication conceptsPublication; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java index 73cf9ab7c..a26bf1874 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java @@ -1,27 +1,7 @@ package fr.insee.rmes.bauhaus_services.concepts.concepts; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.model.vocabulary.DC; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.SKOS; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.concepts.publication.ConceptsPublication; import fr.insee.rmes.bauhaus_services.links.LinksUtils; @@ -29,7 +9,6 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; @@ -38,19 +17,36 @@ import fr.insee.rmes.persistance.ontologies.INSEE; import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.utils.JSONUtils; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.model.vocabulary.DC; +import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.eclipse.rdf4j.model.vocabulary.SKOS; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; @Component public class ConceptsUtils extends RdfService { - private static final Logger logger = LogManager.getLogger(ConceptsUtils.class); - + private static final Logger logger = LoggerFactory.getLogger(ConceptsUtils.class); + @Autowired private ConceptsPublication conceptsPublication; - + @Autowired private NoteManager noteManager; - public String createID() throws RmesException { JSONObject json = repoGestion.getResponseAsObject(ConceptsQueries.lastConceptID()); if (json != null && !json.isEmpty()) { @@ -171,7 +167,7 @@ public void createRdfConcept(Concept concept) throws RmesException { repoGestion.loadConcept(conceptURI, model, notesToDeleteAndUpdate); } - public void conceptsValidation(JSONArray conceptsToValidate) throws RmesException { + private void conceptsValidation(JSONArray conceptsToValidate) throws RmesException { Model model = new LinkedHashModel(); List conceptsToValidateList = new ArrayList<>(); for (int i = 0; i < conceptsToValidate.length(); i++) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/publication/ConceptsPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/publication/ConceptsPublication.java index 7a9b180d2..da25a90bc 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/publication/ConceptsPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/publication/ConceptsPublication.java @@ -1,8 +1,12 @@ package fr.insee.rmes.bauhaus_services.concepts.publication; -import java.util.ArrayList; -import java.util.List; - +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.persistance.ontologies.XKOS; +import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Model; @@ -18,14 +22,8 @@ import org.jsoup.Jsoup; import org.springframework.stereotype.Component; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.persistance.ontologies.XKOS; -import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; +import java.util.ArrayList; +import java.util.List; @Component public class ConceptsPublication extends RdfService{ @@ -55,7 +53,7 @@ public void publishConcepts(JSONArray conceptsToPublish) throws RmesException { hasBroader = prepareOneTripleToPublicationAndCheckIfHasBroader(model, noteToClear, topConceptOfToDelete, con, st, hasBroader); } if (!hasBroader) { - model.add(PublicationUtils.tranformBaseURIToPublish(concept), SKOS.TOP_CONCEPT_OF, PublicationUtils.tranformBaseURIToPublish(RdfUtils.conceptScheme()), + model.add(publicationUtils.tranformBaseURIToPublish(concept), SKOS.TOP_CONCEPT_OF, publicationUtils.tranformBaseURIToPublish(RdfUtils.conceptScheme()), RdfUtils.conceptGraph()); } } catch (RepositoryException e) { @@ -68,7 +66,7 @@ public void publishConcepts(JSONArray conceptsToPublish) throws RmesException { publishMemberLinks(concept, model, con); con.close(); - Resource conceptToPublish = PublicationUtils.tranformBaseURIToPublish(concept); + Resource conceptToPublish = publicationUtils.tranformBaseURIToPublish(concept); repositoryPublication.publishConcept(conceptToPublish, model, noteToClear, topConceptOfToDelete); } @@ -80,38 +78,38 @@ private Boolean prepareOneTripleToPublicationAndCheckIfHasBroader(Model model, L List topConceptOfToDelete, RepositoryConnection con, Statement st, boolean hasBroader) throws RmesException { - Resource subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); Resource graph = st.getContext(); String predicat = RdfUtils.toString(st.getPredicate()); if (PublicationUtils.stringEndsWithItemFromList(predicat,notes)) { - model.add(subject, st.getPredicate(), PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), graph); publishExplanatoryNotes(con, RdfUtils.toURI(st.getObject().toString()), model); - noteToClear.add(PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject())); + noteToClear.add(publicationUtils.tranformBaseURIToPublish((Resource) st.getObject())); } // Other URI to transform else if (PublicationUtils.stringEndsWithItemFromList(predicat,links)) { - model.add(subject, st.getPredicate(), PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), graph); } else if (predicat.endsWith("related")) { - model.add(subject, st.getPredicate(), PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), graph); - model.add(PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), SKOS.RELATED, subject, graph); + model.add(publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), SKOS.RELATED, subject, graph); } else if (predicat.endsWith(Constants.REPLACES)) { - model.add(subject, st.getPredicate(), PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), graph); - model.add(PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), DCTERMS.IS_REPLACED_BY, subject, graph); + model.add(publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), DCTERMS.IS_REPLACED_BY, subject, graph); } else if (predicat.endsWith("broader")) { hasBroader = true; - model.add(subject, st.getPredicate(), PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), graph); - model.add(PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), SKOS.NARROWER, subject, graph); + model.add(publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), SKOS.NARROWER, subject, graph); } // Narrower links else if (predicat.endsWith("narrower")) { - Resource object = PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); + Resource object = publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); topConceptOfToDelete.add(object); model.add(subject, st.getPredicate(), object, graph); model.add(object, SKOS.BROADER, subject, graph); @@ -133,8 +131,8 @@ private void checkTopConceptOf(String conceptId, Model model) throws RmesExcept for (int i = 0; i < conceptsToCheck.length(); i++) { String id = conceptsToCheck.getJSONObject(i).getString("narrowerId"); if (!repoGestion.getResponseAsBoolean(ConceptsQueries.hasBroader(id))) { - model.add(PublicationUtils.tranformBaseURIToPublish(RdfUtils.conceptIRI(id)), - SKOS.TOP_CONCEPT_OF, PublicationUtils.tranformBaseURIToPublish(RdfUtils.conceptScheme()), + model.add(publicationUtils.tranformBaseURIToPublish(RdfUtils.conceptIRI(id)), + SKOS.TOP_CONCEPT_OF, publicationUtils.tranformBaseURIToPublish(RdfUtils.conceptScheme()), RdfUtils.conceptGraph()); } } @@ -150,7 +148,7 @@ private void publishExplanatoryNotes(RepositoryConnection con, Resource note, Mo while (statements.hasNext()) { Statement st = statements.next(); String predicat = RdfUtils.toString(st.getPredicate()); - subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); graph = st.getContext(); if (predicat.endsWith("conceptVersion")) { // nothing, wouldn't copy this attr @@ -171,7 +169,7 @@ private void publishExplanatoryNotes(RepositoryConnection con, Resource note, Mo if (subject == null) { throw new RmesException(HttpStatus.SC_NO_CONTENT, "subject can't be null", ""); } - model.add(PublicationUtils.tranformBaseURIToPublish(subject), XKOS.PLAIN_TEXT, plainText, graph); + model.add(publicationUtils.tranformBaseURIToPublish(subject), XKOS.PLAIN_TEXT, plainText, graph); } catch (RepositoryException e) { repoGestion.closeStatements(statements); throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), Constants.REPOSITORY_EXCEPTION); @@ -191,8 +189,8 @@ private void publishMemberLinks(Resource concept, Model model, RepositoryConnect try { while (statements.hasNext()) { Statement st = statements.next(); - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } } catch (RepositoryException e) { repoGestion.closeStatements(statements); @@ -217,8 +215,8 @@ public void publishCollection(JSONArray collectionsToValidate) throws RmesExcept Statement st = statements.next(); // Other URI to transform if (RdfUtils.toString(st.getPredicate()).endsWith("member")) { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } else if (RdfUtils.toString(st.getPredicate()).endsWith("isValidated") || (RdfUtils.toString(st.getPredicate()).endsWith(Constants.CREATOR)) || (RdfUtils.toString(st.getPredicate()).endsWith(Constants.CONTRIBUTOR))) { @@ -226,7 +224,7 @@ public void publishCollection(JSONArray collectionsToValidate) throws RmesExcept } // Literals else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); } } @@ -237,7 +235,7 @@ public void publishCollection(JSONArray collectionsToValidate) throws RmesExcept repoGestion.closeStatements(statements); con.close(); } - Resource collectionToPublish = PublicationUtils.tranformBaseURIToPublish(collection); + Resource collectionToPublish = publicationUtils.tranformBaseURIToPublish(collection); repositoryPublication.publishResource(collectionToPublish, model, Constants.COLLECTION); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/consutation_gestion/ConsultationGestionServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/consutation_gestion/ConsultationGestionServiceImpl.java index b6d01f11a..29d432b35 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/consutation_gestion/ConsultationGestionServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/consutation_gestion/ConsultationGestionServiceImpl.java @@ -1,12 +1,5 @@ package fr.insee.rmes.bauhaus_services.consutation_gestion; -import java.util.HashMap; -import java.util.Iterator; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Service; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; @@ -14,11 +7,24 @@ import fr.insee.rmes.model.ValidationStatus; import fr.insee.rmes.persistance.ontologies.IGEO; import fr.insee.rmes.persistance.ontologies.QB; +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Iterator; + +import static fr.insee.rmes.config.PropertiesKeys.CONCEPTS_BASE_URI; + @Service public class ConsultationGestionServiceImpl extends RdfService implements ConsultationGestionService { String defaultDate = "2020-01-01T00:00:00.000"; + @Value("${"+CONCEPTS_BASE_URI+"}") + private String conceptsBaseUri; + @Override public String getDetailedConcept(String id) throws RmesException { @@ -210,7 +216,7 @@ public JSONObject getComponent(String id) throws RmesException { HashMap params = new HashMap<>(); params.put("STRUCTURES_COMPONENTS_GRAPH", config.getStructuresComponentsGraph()); params.put("CODELIST_GRAPH", config.getCodeListGraph()); - params.put("CONCEPTS_BASE_URI", config.getConceptsBaseUri()); + params.put("CONCEPTS_BASE_URI", conceptsBaseUri); params.put("ID", id); params.put("LG1", config.getLg1()); params.put("LG2", config.getLg2()); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java index 0e0692d00..e42854139 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java @@ -1,24 +1,7 @@ package fr.insee.rmes.bauhaus_services.geography; -import java.io.IOException; -import java.util.UUID; - -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.SKOS; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Service; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.GeographyService; import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; @@ -33,6 +16,21 @@ import fr.insee.rmes.persistance.ontologies.GEO; import fr.insee.rmes.persistance.ontologies.IGEO; import fr.insee.rmes.persistance.sparql_queries.geography.GeoQueries; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.eclipse.rdf4j.model.vocabulary.SKOS; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.UUID; @Service public class GeographyServiceImpl extends RdfService implements GeographyService { @@ -41,7 +39,7 @@ public class GeographyServiceImpl extends RdfService implements GeographyService private static final String HAS_COMPOSITION = "hasComposition"; - static final Logger logger = LogManager.getLogger(GeographyServiceImpl.class); + static final Logger logger = LoggerFactory.getLogger(GeographyServiceImpl.class); @Override public String getGeoFeatures() throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServices.java b/src/main/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServices.java index 276ebb511..b5ec2e221 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServices.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServices.java @@ -7,8 +7,8 @@ import fr.insee.rmes.config.keycloak.KeycloakServerZoneConfiguration; import fr.insee.rmes.config.keycloak.ServerZone; import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -31,10 +31,10 @@ public class KeycloakServices { private final Map zonesByServer; private final Map zonesByUrl=new HashMap<>(); protected RestTemplate keycloakClient = new RestTemplate(); - static final Logger log = LogManager.getLogger(KeycloakServices.class); + static final Logger log = LoggerFactory.getLogger(KeycloakServices.class); private final Map keycloakServers; - static final Logger logger = LogManager.getLogger(KeycloakServices.class); + static final Logger logger = LoggerFactory.getLogger(KeycloakServices.class); public KeycloakServices( @Value("${fr.insee.rmes.bauhaus.keycloak.client.secret}") String secret, diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/links/LinksUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/links/LinksUtils.java index 5b836eb2c..47d81a094 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/links/LinksUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/links/LinksUtils.java @@ -1,14 +1,13 @@ package fr.insee.rmes.bauhaus_services.links; -import java.util.List; - +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.model.links.Link; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.SKOS; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.model.links.Link; +import java.util.List; public class LinksUtils { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NoteManager.java b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NoteManager.java index 6f988b81f..0c538e6b4 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NoteManager.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NoteManager.java @@ -1,15 +1,5 @@ package fr.insee.rmes.bauhaus_services.notes; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.concepts.Concept; @@ -17,6 +7,15 @@ import fr.insee.rmes.model.notes.VersionableNote; import fr.insee.rmes.model.notes.concepts.ConceptsDatedNoteTypes; import fr.insee.rmes.model.notes.concepts.ConceptsVersionnedNoteTypes; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; @Component public class NoteManager { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java index 7bcac66d4..8913cba43 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java @@ -1,16 +1,5 @@ package fr.insee.rmes.bauhaus_services.notes; -import java.time.LocalDateTime; -import java.util.List; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.exceptions.RmesException; @@ -22,6 +11,16 @@ import fr.insee.rmes.persistance.ontologies.PAV; import fr.insee.rmes.persistance.ontologies.XKOS; import fr.insee.rmes.persistance.sparql_queries.notes.NotesQueries; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.json.JSONArray; +import org.json.JSONObject; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; +import java.util.List; @Component public class NotesUtils extends RdfService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsDocumentationsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsDocumentationsImpl.java index 5dd6fdee4..480c10d28 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsDocumentationsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsDocumentationsImpl.java @@ -1,18 +1,5 @@ package fr.insee.rmes.bauhaus_services.operations; -import java.io.IOException; -import java.nio.charset.Charset; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.util.StreamUtils; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; import fr.insee.rmes.bauhaus_services.operations.documentations.DocumentationExport; @@ -29,11 +16,23 @@ import fr.insee.rmes.model.operations.documentations.MSD; import fr.insee.rmes.persistance.sparql_queries.operations.documentations.DocumentationsQueries; import fr.insee.rmes.utils.XhtmlToMarkdownUtils; +import org.json.JSONObject; +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.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.StreamUtils; + +import java.io.IOException; +import java.nio.charset.Charset; @Service public class OperationsDocumentationsImpl extends RdfService implements OperationsDocumentationsService { - static final Logger logger = LogManager.getLogger(OperationsDocumentationsImpl.class); + static final Logger logger = LoggerFactory.getLogger(OperationsDocumentationsImpl.class); @Value("classpath:bauhaus-sims.json") org.springframework.core.io.Resource simsDefaultValue; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java index 03cf6a467..ae1600671 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java @@ -1,48 +1,5 @@ package fr.insee.rmes.bauhaus_services.operations; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.StringReader; -import java.lang.reflect.Field; -import java.nio.file.Files; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.Resource; -import org.springframework.http.ContentDisposition; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; -import org.w3c.dom.Document; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.bauhaus_services.operations.families.FamiliesUtils; @@ -63,13 +20,42 @@ import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; import fr.insee.rmes.utils.EncodingType; import fr.insee.rmes.utils.ExportUtils; +import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONObject; +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.core.io.ByteArrayResource; +import org.springframework.core.io.Resource; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.w3c.dom.Document; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import java.io.*; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; @Service public class OperationsImpl extends RdfService implements OperationsService { private static final String ATTACHMENT = "attachment"; - static final Logger logger = LogManager.getLogger(OperationsImpl.class); + static final Logger logger = LoggerFactory.getLogger(OperationsImpl.class); @Value("classpath:bauhaus-sims.json") @@ -179,7 +165,6 @@ public String getOperationsWithReport(String idSeries) throws RmesException { @Override public String createSeries(String body) throws RmesException { - // TODO: check if there is already a series with the same name ? return seriesUtils.createSeries(body); } @@ -457,8 +442,8 @@ public String getIndicatorsForSearch() throws RmesException { @Override public String getIndicatorJsonByID(String id) throws RmesException { - JSONObject indic = indicatorsUtils.getIndicatorJsonById(id); - return indic.toString(); + JSONObject indicator = indicatorsUtils.getIndicatorJsonById(id); + return indicator.toString(); } @Override diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/ParentUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/ParentUtils.java index 53f17ce8c..4b106b410 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/ParentUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/ParentUtils.java @@ -1,15 +1,5 @@ package fr.insee.rmes.bauhaus_services.operations; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; @@ -23,12 +13,21 @@ import fr.insee.rmes.persistance.sparql_queries.operations.indicators.IndicatorsQueries; import fr.insee.rmes.persistance.sparql_queries.operations.operations.OperationsQueries; import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.eclipse.rdf4j.model.IRI; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; @Component public class ParentUtils extends RdfService{ - static final Logger logger = LogManager.getLogger(ParentUtils.class); + static final Logger logger = LoggerFactory.getLogger(ParentUtils.class); public String getDocumentationOwnersByIdSims(String idSims) throws RmesException { @@ -118,7 +117,7 @@ public JSONArray getSeriesCreators(String id) throws RmesException { } public JSONArray getSeriesCreators(IRI iri) throws RmesException { - return repoGestion.getResponseAsJSONList(OpSeriesQueries.getCreatorsBySeriesUri(RdfUtils.toString(iri))); + return repoGestion.getResponseAsJSONList(OpSeriesQueries.getCreatorsBySeriesUri("<" + RdfUtils.toString(iri) + ">")); } public String[] getDocumentationTargetTypeAndId(String idSims) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationPublication.java index 1a7e22e07..91805795c 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationPublication.java @@ -1,5 +1,14 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.operations.documentations.documents.DocumentsPublication; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.ErrorCodes; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesNotFoundException; +import fr.insee.rmes.external_services.notifications.NotificationsContract; +import fr.insee.rmes.external_services.notifications.RmesNotificationsImpl; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -11,17 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.operations.documentations.documents.DocumentsPublication; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotFoundException; -import fr.insee.rmes.external_services.notifications.NotificationsContract; -import fr.insee.rmes.external_services.notifications.RmesNotificationsImpl; - @Repository public class DocumentationPublication extends RdfService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java index d94d5aea0..5b7bfde57 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java @@ -1,25 +1,5 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.CodeListService; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.GeographyService; @@ -39,12 +19,31 @@ import fr.insee.rmes.utils.DateUtils; import fr.insee.rmes.utils.JSONUtils; import fr.insee.rmes.utils.XMLUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component public class DocumentationsRubricsUtils extends RdfService { - static final Logger logger = LogManager.getLogger(DocumentationsRubricsUtils.class); + static final Logger logger = LoggerFactory.getLogger(DocumentationsRubricsUtils.class); @Autowired private MetadataStructureDefUtils msdUtils; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java index ab25580ec..601dfdc69 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java @@ -1,29 +1,7 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.RDFS; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.CodeListService; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.OrganizationsService; @@ -33,12 +11,7 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotAcceptableException; -import fr.insee.rmes.exceptions.RmesNotFoundException; -import fr.insee.rmes.exceptions.RmesUnauthorizedException; +import fr.insee.rmes.exceptions.*; import fr.insee.rmes.model.ValidationStatus; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.model.operations.documentations.DocumentationRubric; @@ -48,12 +21,35 @@ import fr.insee.rmes.persistance.ontologies.SDMX_MM; import fr.insee.rmes.persistance.sparql_queries.operations.documentations.DocumentationsQueries; import fr.insee.rmes.utils.DateUtils; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.eclipse.rdf4j.model.vocabulary.RDF; +import org.eclipse.rdf4j.model.vocabulary.RDFS; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +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.http.HttpStatus; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static fr.insee.rmes.config.PropertiesKeys.OPERATIONS_BASE_URI; @Component public class DocumentationsUtils extends RdfService{ - static final Logger logger = LogManager.getLogger(DocumentationsUtils.class); + static final Logger logger = LoggerFactory.getLogger(DocumentationsUtils.class); @Autowired @@ -74,6 +70,9 @@ public class DocumentationsUtils extends RdfService{ @Autowired ParentUtils parentUtils; + @Value("${"+OPERATIONS_BASE_URI+"}") + private String operationsBaseUri; + /** * GETTER * @param idSims @@ -177,7 +176,7 @@ public String setMetadataReport(String id, String body, boolean create) throws R // Create or update rdf IRI seriesOrIndicatorUri = targetUri; - if (RdfUtils.toString(targetUri).contains(config.getOperationsBaseUri())) { + if (RdfUtils.toString(targetUri).contains(this.operationsBaseUri)) { seriesOrIndicatorUri = parentUtils.getSeriesUriByOperationId(idTarget); } if (create) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java index bc7541946..ffb3a0372 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java @@ -1,28 +1,27 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.RangeType; import fr.insee.rmes.persistance.sparql_queries.operations.documentations.DocumentationsQueries; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; @Component public class MetadataStructureDefUtils extends RdfService { private static final String RANGE = "range"; - static final Logger logger = LogManager.getLogger(MetadataStructureDefUtils.class); + static final Logger logger = LoggerFactory.getLogger(MetadataStructureDefUtils.class); public JSONObject getMetadataAttributeById(String id) throws RmesException{ diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsImpl.java index 1b6a2fc90..269bac206 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsImpl.java @@ -2,9 +2,9 @@ import fr.insee.rmes.bauhaus_services.DocumentsService; import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -15,7 +15,7 @@ @Service public class DocumentsImpl implements DocumentsService { - private static final Logger logger = LogManager.getLogger(DocumentsImpl.class); + private static final Logger logger = LoggerFactory.getLogger(DocumentsImpl.class); @Autowired DocumentsUtils documentsUtils; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsPublication.java index 64d5f3028..b0b2f0457 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsPublication.java @@ -1,21 +1,15 @@ package fr.insee.rmes.bauhaus_services.operations.documentations.documents; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.HashMap; -import java.util.Map; - +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.ErrorCodes; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesNotFoundException; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; +import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleIRI; import org.eclipse.rdf4j.repository.RepositoryConnection; @@ -23,18 +17,18 @@ import org.eclipse.rdf4j.repository.RepositoryResult; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.HashMap; +import java.util.Map; @Component public class DocumentsPublication extends RdfService{ @@ -43,7 +37,7 @@ public class DocumentsPublication extends RdfService{ DocumentsUtils docUtils; - static final Logger logger = LogManager.getLogger(DocumentsPublication.class); + static final Logger logger = LoggerFactory.getLogger(DocumentsPublication.class); public void publishAllDocumentsInSims(String idSims) throws RmesException { @@ -62,7 +56,7 @@ public void publishAllDocumentsInSims(String idSims) throws RmesException { // Change url in document (getModelToPublish) and publish the RDF Resource document = RdfUtils.objectIRIPublication(ObjectType.DOCUMENT,docId); - repositoryPublication.publishResource(document, getModelToPublish(docId,filename), ObjectType.DOCUMENT.getLabelType()); + repositoryPublication.publishResource(document, getModelToPublish(docId,filename), ObjectType.DOCUMENT.labelType()); } //Get all links @@ -70,7 +64,7 @@ public void publishAllDocumentsInSims(String idSims) throws RmesException { for (Object link : listLinks) { String id = docUtils.getIdFromJson((JSONObject)link).toString(); Resource linkResource = RdfUtils.objectIRIPublication(ObjectType.LINK,id); - repositoryPublication.publishResource(linkResource, getLinkModelToPublish(id), ObjectType.LINK.getLabelType()); + repositoryPublication.publishResource(linkResource, getLinkModelToPublish(id), ObjectType.LINK.labelType()); } @@ -108,15 +102,15 @@ private Model getModelToPublish(String documentId, String filename) throws RmesE while (documentStatements.hasNext()) { Statement st = documentStatements.next(); if (RdfUtils.toString(st.getPredicate()).endsWith(Constants.URL)) { - Resource subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); IRI predicate = RdfUtils - .createIRI(PublicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); + .createIRI(publicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); String newUrl = config.getDocumentsBaseurl() + "/"+ filename; logger.info("Publishing document : {}",newUrl); Value object = RdfUtils.toURI(newUrl); model.add(subject, predicate, object, st.getContext()); } else { - Resource subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); renameAndAddTripleToModel(model, st, subject); } } @@ -161,13 +155,13 @@ private Model getModelWithErrorToPublish(String documentId, String filename) thr } private void transformTuplesToPublish(String filename, Model model, Resource document, JSONArray tuples) { - Resource newSubject = PublicationUtils.tranformBaseURIToPublish(document); + Resource newSubject = publicationUtils.tranformBaseURIToPublish(document); Value object ; for (int i = 0; i < tuples.length(); i++) { JSONObject tuple = (JSONObject) tuples.get(i); String predicatString = tuple.getString("predicat"); - IRI predicate = (SimpleIRI) PublicationUtils.tranformBaseURIToPublish(RdfUtils.toURI(predicatString)); + IRI predicate = (SimpleIRI) publicationUtils.tranformBaseURIToPublish(RdfUtils.toURI(predicatString)); if (predicatString.endsWith(Constants.URL)) { String newUrl = config.getDocumentsBaseurl() + "/"+ filename; logger.info("Publishing document : {}",newUrl); @@ -176,7 +170,7 @@ private void transformTuplesToPublish(String filename, Model model, Resource doc String objectString = tuple.getString("obj"); try { object = RdfUtils.toURI(objectString); - object = PublicationUtils.tranformBaseURIToPublish((Resource) object); + object = publicationUtils.tranformBaseURIToPublish((Resource) object); }catch(IllegalArgumentException iAe) { object = RdfUtils.setLiteralString(objectString); @@ -199,7 +193,7 @@ private Model getLinkModelToPublish(String linkId) throws RmesException { } while (linkStatements.hasNext()) { Statement st = linkStatements.next(); - Resource subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); renameAndAddTripleToModel(model, st, subject); } @@ -217,10 +211,10 @@ private Model getLinkModelToPublish(String linkId) throws RmesException { public void renameAndAddTripleToModel(Model model, Statement st, Resource subject) { IRI predicate = RdfUtils - .createIRI(PublicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); + .createIRI(publicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); Value object = st.getObject(); if (st.getObject() instanceof Resource) { - object = PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); + object = publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); } model.add(subject, predicate, object, st.getContext()); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java index 965cc2524..71fd4d3a2 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java @@ -18,8 +18,6 @@ import fr.insee.rmes.utils.UriUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -30,6 +28,8 @@ import org.eclipse.rdf4j.model.vocabulary.RDFS; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.*; @@ -53,7 +53,7 @@ public class DocumentsUtils extends RdfService { private static final String SCHEME_FILE = "file://"; - static final Logger logger = LogManager.getLogger(DocumentsUtils.class); + static final Logger logger = LoggerFactory.getLogger(DocumentsUtils.class); @Autowired private LangService langService; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamiliesUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamiliesUtils.java index d1baa5202..88621e9c5 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamiliesUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamiliesUtils.java @@ -20,8 +20,6 @@ import fr.insee.rmes.utils.XhtmlToMarkdownUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; @@ -30,6 +28,8 @@ import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -40,7 +40,7 @@ public class FamiliesUtils extends RdfService { private static final String CAN_T_READ_REQUEST_BODY = "Can't read request body"; - static final Logger logger = LogManager.getLogger(FamiliesUtils.class); + static final Logger logger = LoggerFactory.getLogger(FamiliesUtils.class); @Autowired FamOpeSerIndUtils famOpeSerUtils; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamilyPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamilyPublication.java index 9beb4a786..f0b84426f 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamilyPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/families/FamilyPublication.java @@ -4,7 +4,6 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; @@ -47,7 +46,7 @@ public void publishFamily(String familyId) throws RmesException { } // Literals else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); @@ -62,7 +61,7 @@ public void publishFamily(String familyId) throws RmesException { repoGestion.closeStatements(statements); con.close(); } - Resource familyToPublishRessource = PublicationUtils.tranformBaseURIToPublish(family); + Resource familyToPublishRessource = publicationUtils.tranformBaseURIToPublish(family); repositoryPublication.publishResource(familyToPublishRessource, model, Constants.FAMILY); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java index ea2fd9cbe..139bd9856 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java @@ -1,17 +1,7 @@ package fr.insee.rmes.bauhaus_services.operations.famopeserind_utils; -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; @@ -20,11 +10,19 @@ import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.links.OperationsLink; import fr.insee.rmes.persistance.sparql_queries.operations.famOpeSerUtils.FamOpeSerQueries; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; @Component public class FamOpeSerIndUtils extends RdfService { - static final Logger logger = LogManager.getLogger(FamOpeSerIndUtils.class); + static final Logger logger = LoggerFactory.getLogger(FamOpeSerIndUtils.class); public String createId() throws RmesException { logger.info("Generate famOpeSer id"); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorPublication.java index 58b8d6bef..9481b87d1 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorPublication.java @@ -1,26 +1,24 @@ package fr.insee.rmes.bauhaus_services.operations.indicators; -import org.apache.http.HttpStatus; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.RepositoryResult; -import org.springframework.stereotype.Repository; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; import fr.insee.rmes.external_services.notifications.NotificationsContract; import fr.insee.rmes.external_services.notifications.RmesNotificationsImpl; +import org.apache.http.HttpStatus; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.eclipse.rdf4j.repository.RepositoryException; +import org.eclipse.rdf4j.repository.RepositoryResult; +import org.springframework.stereotype.Repository; @Repository public class IndicatorPublication extends RdfService { @@ -55,12 +53,12 @@ public void publishIndicator(String indicatorId) throws RmesException { || pred.endsWith(Constants.CONTRIBUTOR) || pred.endsWith(Constants.PUBLISHER) || pred.endsWith("accrualPeriodicity")) { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } // Literals else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); } // Other URI to transform : none @@ -74,7 +72,7 @@ public void publishIndicator(String indicatorId) throws RmesException { repoGestion.closeStatements(statements); con.close(); } - Resource indicatorToPublishRessource = PublicationUtils.tranformBaseURIToPublish(indicator); + Resource indicatorToPublishRessource = publicationUtils.tranformBaseURIToPublish(indicator); repositoryPublication.publishResource(indicatorToPublishRessource, model, "indicator"); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java index 0ba681d60..c65371ff3 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java @@ -9,10 +9,7 @@ import fr.insee.rmes.bauhaus_services.operations.ParentUtils; import fr.insee.rmes.bauhaus_services.operations.documentations.DocumentationsUtils; import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; -import fr.insee.rmes.bauhaus_services.rdf_utils.QueryUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.*; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; @@ -26,14 +23,14 @@ import fr.insee.rmes.utils.DateUtils; import fr.insee.rmes.utils.XMLUtils; import fr.insee.rmes.utils.XhtmlToMarkdownUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.vocabulary.*; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -44,7 +41,7 @@ @Component public class IndicatorsUtils extends RdfService { - static final Logger logger = LogManager.getLogger(IndicatorsUtils.class); + static final Logger logger = LoggerFactory.getLogger(IndicatorsUtils.class); @Autowired CodeListService codeListService; @@ -63,6 +60,8 @@ public class IndicatorsUtils extends RdfService { @Autowired private DocumentationsUtils documentationsUtils; + @Autowired + private UriUtils uriUtils; private void validate(Indicator indicator) throws RmesException { if(repoGestion.getResponseAsBoolean(IndicatorsQueries.checkPrefLabelUnicity(indicator.getId(), indicator.getPrefLabelLg1(), config.getLg1()))){ @@ -192,7 +191,7 @@ private void addOneOrganizationLink(String id, JSONObject object, IRI predicate) if (organizations.length() != 0) { for (int i = 0; i < organizations.length(); i++) { JSONObject orga = organizations.getJSONObject(i); - orga.put("type", ObjectType.ORGANIZATION.getLabelType()); + orga.put("type", ObjectType.ORGANIZATION.labelType()); } } object.put(predicate.getLocalName(), organizations); @@ -335,7 +334,7 @@ private void createRdfIndicator(Indicator indicator, ValidationStatus newStatus) List replaces = indicator.getReplaces(); if (replaces != null) { for (OperationsLink replace : replaces) { - String replaceUri = ObjectType.getCompleteUriGestion(replace.getType(), replace.getId()); + String replaceUri = this.uriUtils.getCompleteUriGestion(replace.getType(), replace.getId()); addReplacesAndReplacedBy(model, RdfUtils.toURI(replaceUri), indicURI); } } @@ -343,7 +342,7 @@ private void createRdfIndicator(Indicator indicator, ValidationStatus newStatus) List isReplacedBys = indicator.getIsReplacedBy(); if (isReplacedBys != null) { for (OperationsLink isRepl : isReplacedBys) { - String isReplUri = ObjectType.getCompleteUriGestion(isRepl.getType(), isRepl.getId()); + String isReplUri = this.uriUtils.getCompleteUriGestion(isRepl.getType(), isRepl.getId()); addReplacesAndReplacedBy(model, indicURI, RdfUtils.toURI(isReplUri)); } } @@ -374,7 +373,7 @@ public String setIndicatorValidation(String id) throws RmesException { private void addOneWayLink(Model model, IRI indicURI, List links, IRI linkPredicate) { if (links != null) { for (OperationsLink oneLink : links) { - String linkedObjectUri = ObjectType.getCompleteUriGestion(oneLink.getType(), oneLink.getId()); + String linkedObjectUri = this.uriUtils.getCompleteUriGestion(oneLink.getType(), oneLink.getId()); RdfUtils.addTripleUri(indicURI, linkPredicate ,linkedObjectUri, model, RdfUtils.productsGraph()); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationPublication.java index a7d98f67b..71ea30cd8 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationPublication.java @@ -1,5 +1,14 @@ package fr.insee.rmes.bauhaus_services.operations.operations; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.operations.ParentUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.ErrorCodes; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesNotFoundException; +import fr.insee.rmes.exceptions.RmesUnauthorizedException; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -12,17 +21,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.operations.ParentUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.ErrorCodes; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotFoundException; -import fr.insee.rmes.exceptions.RmesUnauthorizedException; - @Component public class OperationPublication extends RdfService{ @@ -51,14 +49,14 @@ public void publishOperation(String operationId, JSONObject operationJson) throw Statement st = statements.next(); // Other URI to transform if (RdfUtils.toString(st.getPredicate()).endsWith("isPartOf")) { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } else if (PublicationUtils.stringEndsWithItemFromList(RdfUtils.toString(st.getPredicate()), ignoredAttrs)) { // nothing, wouldn't copy this attr } // Literals else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); } addHasPartStatements(model, operation, con); @@ -70,7 +68,7 @@ public void publishOperation(String operationId, JSONObject operationJson) throw repoGestion.closeStatements(statements); con.close(); } - Resource operationToPublishRessource = PublicationUtils.tranformBaseURIToPublish(operation); + Resource operationToPublishRessource = publicationUtils.tranformBaseURIToPublish(operation); repositoryPublication.publishResource(operationToPublishRessource, model, "operation"); } @@ -93,8 +91,8 @@ private void addHasPartStatements(Model model, Resource operation, RepositoryCon while (hasPartStatements.hasNext()) { Statement hpst = hasPartStatements.next(); - model.add(PublicationUtils.tranformBaseURIToPublish(hpst.getSubject()), hpst.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) hpst.getObject()), hpst.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(hpst.getSubject()), hpst.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) hpst.getObject()), hpst.getContext()); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationsUtils.java index 821d7c94b..fe19facbe 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/OperationsUtils.java @@ -17,8 +17,6 @@ import fr.insee.rmes.persistance.sparql_queries.operations.operations.OperationsQueries; import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; import fr.insee.rmes.utils.DateUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; @@ -27,6 +25,8 @@ import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -35,7 +35,7 @@ @Component public class OperationsUtils extends RdfService{ - static final Logger logger = LogManager.getLogger(OperationsUtils.class); + static final Logger logger = LoggerFactory.getLogger(OperationsUtils.class); @Autowired private FamOpeSerIndUtils famOpeSerIndUtils; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/VarBookExportBuilder.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/VarBookExportBuilder.java index fe2b7331c..1cfba37f8 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/VarBookExportBuilder.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/operations/VarBookExportBuilder.java @@ -1,23 +1,15 @@ package fr.insee.rmes.bauhaus_services.operations.operations; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactoryConfigurationError; - +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.exceptions.RmesNotAcceptableException; +import fr.insee.rmes.utils.DocumentBuilders; +import fr.insee.rmes.utils.StringUtils; +import fr.insee.rmes.utils.XMLUtils; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.fusesource.hawtbuf.ByteArrayInputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -25,19 +17,25 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.exceptions.RmesNotAcceptableException; -import fr.insee.rmes.utils.DocumentBuilders; -import fr.insee.rmes.utils.StringUtils; -import fr.insee.rmes.utils.XMLUtils; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactoryConfigurationError; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; @Component public class VarBookExportBuilder { private static final String REFERENCE = "Reference"; - static final Logger logger = LogManager.getLogger(VarBookExportBuilder.class); + static final Logger logger = LoggerFactory.getLogger(VarBookExportBuilder.class); public String getData(String xml) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesPublication.java index 32433255b..7102e758d 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesPublication.java @@ -1,29 +1,27 @@ package fr.insee.rmes.bauhaus_services.operations.series; -import org.apache.http.HttpStatus; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.RepositoryResult; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.operations.ParentUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; import fr.insee.rmes.exceptions.ErrorCodes; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; import fr.insee.rmes.exceptions.RmesUnauthorizedException; import fr.insee.rmes.external_services.notifications.NotificationsContract; import fr.insee.rmes.external_services.notifications.RmesNotificationsImpl; +import org.apache.http.HttpStatus; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.eclipse.rdf4j.repository.RepositoryException; +import org.eclipse.rdf4j.repository.RepositoryResult; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; @Repository public class SeriesPublication extends RdfService { @@ -81,7 +79,7 @@ public void publishSeries(String seriesId, JSONObject serieJson) throws RmesExce } // Literals else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext() @@ -101,7 +99,7 @@ public void publishSeries(String seriesId, JSONObject serieJson) throws RmesExce repoGestion.closeStatements(hasPartStatements); con.close(); } - Resource seriesToPublishRessource = PublicationUtils.tranformBaseURIToPublish(series); + Resource seriesToPublishRessource = publicationUtils.tranformBaseURIToPublish(series); repositoryPublication.publishResource(seriesToPublishRessource, model, "serie"); } @@ -114,9 +112,9 @@ public void addStatementsToModel(Model model, RepositoryResult statem } public void transformSubjectAndObject(Model model, Statement statement) { - model.add(PublicationUtils.tranformBaseURIToPublish(statement.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(statement.getSubject()), statement.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) statement.getObject()), + publicationUtils.tranformBaseURIToPublish((Resource) statement.getObject()), statement.getContext()); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java index 83d9fc088..126cafeaf 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java @@ -12,6 +12,7 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.QueryUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.UriUtils; import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; import fr.insee.rmes.exceptions.*; import fr.insee.rmes.model.ValidationStatus; @@ -22,8 +23,6 @@ import fr.insee.rmes.utils.*; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; @@ -31,6 +30,8 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -40,8 +41,6 @@ @Component public class SeriesUtils extends RdfService { - - private static final String ID_SERIE = "idSerie"; @Autowired @@ -65,7 +64,9 @@ public class SeriesUtils extends RdfService { @Autowired private DocumentationsUtils documentationsUtils; - private static final Logger logger = LogManager.getLogger(SeriesUtils.class); + private static final Logger logger = LoggerFactory.getLogger(SeriesUtils.class); + @Autowired + private UriUtils uriUtils; /*READ*/ @@ -318,7 +319,7 @@ private void createRdfSeries(Series series, IRI familyURI, ValidationStatus newS List replaces = series.getReplaces(); Optional.ofNullable(replaces) .orElseGet(Collections::emptyList).stream().filter(repl -> !repl.isEmpty()).forEach(replace -> { - String replUri = ObjectType.getCompleteUriGestion(replace.getType(), replace.getId()); + String replUri = this.uriUtils.getCompleteUriGestion(replace.getType(), replace.getId()); addReplacesAndReplacedBy(model, RdfUtils.toURI(replUri), seriesURI); }); @@ -326,7 +327,7 @@ private void createRdfSeries(Series series, IRI familyURI, ValidationStatus newS List isReplacedBys = series.getIsReplacedBy(); Optional.ofNullable(isReplacedBys) .orElseGet(Collections::emptyList).stream().filter(isRepl -> !isRepl.isEmpty()).forEach(isRepl -> { - String isReplUri = ObjectType.getCompleteUriGestion(isRepl.getType(), isRepl.getId()); + String isReplUri = this.uriUtils.getCompleteUriGestion(isRepl.getType(), isRepl.getId()); addReplacesAndReplacedBy(model, seriesURI, RdfUtils.toURI(isReplUri)); }); @@ -350,7 +351,7 @@ private void addOperationLinks(List links, IRI predicate, Model if (links != null) { for (OperationsLink link : links) { if (!link.isEmpty()) { - String linkUri = ObjectType.getCompleteUriGestion(link.getType(), link.getId()); + String linkUri = this.uriUtils.getCompleteUriGestion(link.getType(), link.getId()); RdfUtils.addTripleUri(seriesURI, predicate, linkUri, model, RdfUtils.operationsGraph()); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationUtils.java index 5f570eabe..16554beae 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationUtils.java @@ -1,10 +1,5 @@ package fr.insee.rmes.bauhaus_services.organizations; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.QueryUtils; @@ -12,6 +7,10 @@ import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.organizations.OrganizationQueries; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; @Component public class OrganizationUtils extends RdfService { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationsServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationsServiceImpl.java index f8d8d6d42..3ac20bea2 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationsServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/organizations/OrganizationsServiceImpl.java @@ -1,16 +1,5 @@ package fr.insee.rmes.bauhaus_services.organizations; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.OrganizationsService; import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; @@ -20,6 +9,16 @@ import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.organizations.Organization; import fr.insee.rmes.persistance.sparql_queries.organizations.OrganizationQueries; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; @Service public class OrganizationsServiceImpl extends RdfService implements OrganizationsService { @@ -30,7 +29,7 @@ public class OrganizationsServiceImpl extends RdfService implements Organizatio @Autowired FamOpeSerIndUtils famOpeSerUtils; - static final Logger logger = LogManager.getLogger(OrganizationsServiceImpl.class); + static final Logger logger = LoggerFactory.getLogger(OrganizationsServiceImpl.class); @Override public String getOrganizationJsonString(String organizationIdentifier) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/FreeMarkerUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/FreeMarkerUtils.java index 6f22a66b2..76d89e2ac 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/FreeMarkerUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/FreeMarkerUtils.java @@ -1,22 +1,21 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Map; - -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import fr.insee.rmes.config.freemarker.FreemarkerConfig; import fr.insee.rmes.exceptions.RmesException; import freemarker.template.Template; import freemarker.template.TemplateException; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Map; public class FreeMarkerUtils { - static final Logger logger = LogManager.getLogger(FreeMarkerUtils.class); + static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtils.class); private FreeMarkerUtils() { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/ObjectType.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/ObjectType.java index 8c4c91036..7dd0b9fd9 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/ObjectType.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/ObjectType.java @@ -1,273 +1,87 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.persistance.ontologies.*; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.FOAF; import org.eclipse.rdf4j.model.vocabulary.SKOS; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.persistance.ontologies.GEO; -import fr.insee.rmes.persistance.ontologies.INSEE; -import fr.insee.rmes.persistance.ontologies.ORG; -import fr.insee.rmes.persistance.ontologies.QB; -import fr.insee.rmes.persistance.ontologies.SDMX_MM; -public enum ObjectType { - CONCEPT{ - @Override - public String getLabelType() {return Constants.CONCEPT;} - @Override - public IRI getUri() {return SKOS.CONCEPT;} - @Override - public String getBaseUri() {return config.getConceptsBaseUri();} - }, - COLLECTION{ - @Override - public String getLabelType() {return Constants.COLLECTION;} - @Override - public IRI getUri() {return SKOS.COLLECTION;} - @Override - public String getBaseUri() {return config.getCollectionsBaseUri();} - }, - FAMILY{ - @Override - public String getLabelType() {return Constants.FAMILY;} - @Override - public IRI getUri() {return INSEE.FAMILY;} - @Override - public String getBaseUri() {return config.getOpFamiliesBaseUri();} - }, - SERIES{ - @Override - public String getLabelType() {return "series";} - @Override - public IRI getUri() {return INSEE.SERIES;} - @Override - public String getBaseUri() {return config.getOpSeriesBaseUri();} - }, - OPERATION{ - @Override - public String getLabelType() {return "operation";} - @Override - public IRI getUri() {return INSEE.OPERATION;} - @Override - public String getBaseUri() {return config.getOperationsBaseUri();} - }, - INDICATOR{ - @Override - public String getLabelType() {return "indicator";} - @Override - public IRI getUri() {return INSEE.INDICATOR;} - @Override - public String getBaseUri() {return config.getProductsBaseUri();} - }, - DOCUMENTATION{ - @Override - public String getLabelType() {return "documentation";} - @Override - public IRI getUri() {return SDMX_MM.METADATA_REPORT;} - @Override - public String getBaseUri() {return config.getDocumentationsBaseUri();} - }, - DOCUMENT{ - @Override - public String getLabelType() {return Constants.DOCUMENT;} - @Override - public IRI getUri() {return FOAF.DOCUMENT;} - @Override - public String getBaseUri() {return config.getDocumentsBaseUri();} - }, - LINK{ - @Override - public String getLabelType() {return "link";} - @Override - public IRI getUri() {return FOAF.DOCUMENT;} - @Override - public String getBaseUri() {return config.getLinksBaseUri();} - }, - GEO_STAT_TERRITORY{ - @Override - public String getLabelType() {return "geoFeature";} - @Override - public IRI getUri() {return GEO.FEATURE;} - @Override - public String getBaseUri() {return config.getDocumentationsGeoBaseUri();} - }, - ORGANIZATION{ - @Override - public String getLabelType() {return "organization";} - @Override - public IRI getUri() {return ORG.ORGANIZATION;} - @Override - public String getBaseUri() {return "";} - }, - STRUCTURE{ - @Override - public String getLabelType() {return "structure";} - @Override - public IRI getUri() {return QB.DATA_STRUCTURE_DEFINITION;} - @Override - public String getBaseUri() {return config.getStructuresBaseUri();} - }, - CODE_LIST{ - @Override - public String getLabelType() {return Constants.CODELIST;} - @Override - public IRI getUri() {return QB.CODE_LIST;} - @Override - public String getBaseUri() {return config.getCodeListBaseUri();} - }, - MEASURE_PROPERTY{ - @Override - public String getLabelType() {return "measureProperty";} - @Override - public IRI getUri() {return QB.MEASURE_PROPERTY;} - @Override - public String getBaseUri() {return config.getStructuresComponentsBaseUri() + "mesure";} - }, - ATTRIBUTE_PROPERTY{ - @Override - public String getLabelType() {return "attributeProperty";} - @Override - public IRI getUri() {return QB.ATTRIBUTE_PROPERTY;} - @Override - public String getBaseUri() {return config.getStructuresComponentsBaseUri() + "attribut";} - }, - DIMENSION_PROPERTY{ - @Override - public String getLabelType() {return "dimensionProperty";} - @Override - public IRI getUri() {return QB.DIMENSION_PROPERTY;} - @Override - public String getBaseUri() {return config.getStructuresComponentsBaseUri() + "dimension";} - }, +import javax.validation.constraints.NotNull; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.function.UnaryOperator; +import static fr.insee.rmes.config.PropertiesKeys.*; +import static java.util.function.UnaryOperator.identity; - UNDEFINED{ - @Override - public String getLabelType() {return Constants.UNDEFINED;} - @Override - public IRI getUri() {return null;} - @Override - public String getBaseUri() {return "";} - }; - - private static Config config; +public enum ObjectType { + CONCEPT(Constants.CONCEPT,SKOS.CONCEPT, CONCEPTS_BASE_URI, identity()), + COLLECTION(Constants.COLLECTION, SKOS.COLLECTION, COLLECTIONS_BASE_URI,identity()), + FAMILY(Constants.FAMILY, INSEE.FAMILY, OP_FAMILIES_BASE_URI, identity()), + SERIES("series", INSEE.SERIES, OP_SERIES_BASE_URI, identity()), + OPERATION("operation", INSEE.OPERATION, OPERATIONS_BASE_URI, identity()), + INDICATOR("indicator", INSEE.INDICATOR, PRODUCTS_BASE_URI, identity()), + DOCUMENTATION("documentation", SDMX_MM.METADATA_REPORT, DOCUMENTATIONS_BASE_URI, identity()), + DOCUMENT(Constants.DOCUMENT, FOAF.DOCUMENT, DOCUMENTS_BASE_URI, identity()), + LINK("link", FOAF.DOCUMENT, LINKS_BASE_URI, identity()), + GEO_STAT_TERRITORY("geoFeature", GEO.FEATURE, DOCUMENTATIONS_GEO_BASE_URI, identity()), + ORGANIZATION("organization", ORG.ORGANIZATION, null, s->""), + STRUCTURE("structure", QB.DATA_STRUCTURE_DEFINITION, STRUCTURES_BASE_URI, identity()), + CODE_LIST(Constants.CODELIST, QB.CODE_LIST, CODE_LIST_BASE_URI, identity()), + MEASURE_PROPERTY("measureProperty", QB.MEASURE_PROPERTY, STRUCTURES_COMPONENTS_BASE_URI, s->s+"mesure"), + ATTRIBUTE_PROPERTY("attributeProperty", QB.ATTRIBUTE_PROPERTY, STRUCTURES_COMPONENTS_BASE_URI, s->s+"attribut"), + + DIMENSION_PROPERTY("dimensionProperty", QB.DIMENSION_PROPERTY, STRUCTURES_COMPONENTS_BASE_URI, s->s+"dimension"), + + UNDEFINED(Constants.UNDEFINED, null, null,s->""); - protected void setConfig(Config configParam) { - config = configParam; + private final IRI uri; + @NotNull + private final String labelType; + private final String baseUriPropertyName; + private final UnaryOperator baseUriModifier; + + ObjectType(String labelType, IRI uri, String baseUriPropertyName, UnaryOperator baseUriModifier){ + this.uri=uri; + this.labelType=labelType; + this.baseUriPropertyName=baseUriPropertyName; + this.baseUriModifier=baseUriModifier; } - - - @Component - public static class ConfigServiceInjector { - @Autowired - private Config config; - - @PostConstruct - public void postConstruct() { - for (ObjectType objectType : EnumSet.allOf(ObjectType.class)) - objectType.setConfig(config); - } - } - - - - - ObjectType(){ + public static Optional getEnumByLabel(String labelType) { + return Arrays.stream(values()).filter(e->e.labelType.equals(labelType)).findAny(); } - public abstract IRI getUri() ; - public abstract String getLabelType() ; - public abstract String getBaseUri(); - - - private static Map lookupLabel = new HashMap<>(); - private static Map lookupUri = new HashMap<>(); - - static { - // Populate out lookup when enum is created - for (ObjectType e : ObjectType.values()) { - lookupLabel.put(e.getLabelType(), e); - lookupUri.put(e.getUri(), e); - } - } - - /** - * Get Enum type by label - * @param label - * @return - */ - public static ObjectType getEnum(String labelType) { - return lookupLabel.get(labelType)!=null ? lookupLabel.get(labelType): UNDEFINED; - } - - /** - * Get URI by label - * @param label - * @return - */ - public static IRI getUriByLabel(String labelType) { - return getEnum(labelType).getUri(); - } - - /** - * Get URI by label - * @param label - * @return - */ - public static String getBaseUriByLabel(String labelType) { - return getEnum(labelType).getBaseUri(); - } /** * Get Enum type by URI - * @param labelType - * @return */ public static ObjectType getEnum(IRI uri) { - return lookupUri.get(uri)!=null ? lookupUri.get(uri): UNDEFINED; + return Arrays.stream(values()).filter(e->Objects.equals(e.uri, uri)) + .findAny() + .orElse(UNDEFINED); } /** * Get label by URI - * @param labelType - * @return */ public static String getLabelType(IRI uri) { - return getEnum(uri).getLabelType(); - } - - - /** - * Get label by URI - * @param label - * @return - */ - public static String getCompleteUriGestion(String labelType, String id) { - String baseUri = getBaseUriByLabel(labelType); - return config.getBaseUriGestion() + baseUri + "/" + id; + return getEnum(uri).labelType; } - - public String getBaseUriPublication(){ - return config.getBaseUriPublication() + this.getBaseUri() ; + public String baseUriPropertyName() { + return this.baseUriPropertyName; } - public String getBaseUriGestion() { - return config.getBaseUriGestion() + this.getBaseUri() ; + public UnaryOperator baseUriModifier() { + return baseUriModifier; } + public String labelType() { + return labelType; + } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/PublicationUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/PublicationUtils.java index 96b13a77f..d49535c1e 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/PublicationUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/PublicationUtils.java @@ -1,42 +1,39 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; -import java.util.Arrays; - +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.model.ValidationStatus; import org.eclipse.rdf4j.model.Resource; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.model.ValidationStatus; +import javax.validation.constraints.NotNull; +import java.util.Arrays; + +import static fr.insee.rmes.config.PropertiesKeys.BASE_URI_GESTION; +import static fr.insee.rmes.config.PropertiesKeys.BASE_URI_PUBLICATION; +import static java.util.Objects.requireNonNull; @Service -public abstract class PublicationUtils { - - @Autowired - private static Config config; - - private PublicationUtils() { - throw new IllegalStateException("Utility class"); - } - - public static Resource tranformBaseURIToPublish(Resource resource) { - if (!resource.toString().contains(config.getBaseUriGestion())) return resource; - String newResource = resource.toString().replace(config.getBaseUriGestion(), config.getBaseUriPublication()); - return RdfUtils.toURI(newResource); - } - - public static boolean stringEndsWithItemFromList(String inputStr, String[] items) { - return Arrays.stream(items).parallel().anyMatch(inputStr::endsWith); - } - - public static boolean isPublished(String status) { - return status.equals(ValidationStatus.UNPUBLISHED.getValue()) || status.equals(Constants.UNDEFINED); - } - - public static void setConfig(Config config) { - PublicationUtils.config = config; - } - - +public record PublicationUtils(String baseUriGestion, String baseUriPublication) { + public PublicationUtils(@Value("${" + BASE_URI_GESTION + "}") String baseUriGestion, + @Value("${" + BASE_URI_PUBLICATION + "}") String baseUriPublication) { + this.baseUriGestion = baseUriGestion; + this.baseUriPublication = baseUriPublication; + } + + public Resource tranformBaseURIToPublish(Resource resource) { + if (!resource.toString().contains(this.baseUriGestion)) return resource; + String newResource = resource.toString().replace(this.baseUriGestion, this.baseUriPublication); + return RdfUtils.toURI(newResource); + } + + public static boolean stringEndsWithItemFromList(@NotNull String inputStr, @NotNull String[] items) { + return Arrays.stream(items).parallel().anyMatch(requireNonNull(inputStr)::endsWith); + } + + public static boolean isPublished(String status) { + return ValidationStatus.UNPUBLISHED.getValue().equals(status) || Constants.UNDEFINED.equals(status); + } + + } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/QueryUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/QueryUtils.java index 1f3024a73..e87306c6d 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/QueryUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/QueryUtils.java @@ -1,11 +1,10 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; +import fr.insee.rmes.bauhaus_services.Constants; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.json.JSONArray; import org.json.JSONObject; -import fr.insee.rmes.bauhaus_services.Constants; - public class QueryUtils { public static final String PREFIXES = diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfService.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfService.java index c34d29655..e1a6ad3f9 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfService.java @@ -1,15 +1,9 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.Value; -import org.springframework.beans.factory.annotation.Autowired; - import fr.insee.rmes.config.Config; import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; -import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.eclipse.rdf4j.model.*; +import org.springframework.beans.factory.annotation.Autowired; public abstract class RdfService { @@ -24,14 +18,17 @@ public abstract class RdfService { @Autowired protected StampsRestrictionsService stampsRestrictionsService; + + @Autowired + protected PublicationUtils publicationUtils; public void transformTripleToPublish(Model model, Statement st) { - Resource subject = PublicationUtils.tranformBaseURIToPublish(st.getSubject()); + Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject()); IRI predicateIRI = RdfUtils - .createIRI(PublicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); + .createIRI(publicationUtils.tranformBaseURIToPublish(st.getPredicate()).stringValue()); Value object = st.getObject(); if (st.getObject() instanceof Resource) { - object = PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); + object = publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()); } model.add(subject, predicateIRI, object, st.getContext()); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfUtils.java index f21d7920e..d0449e100 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RdfUtils.java @@ -11,25 +11,23 @@ import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XSD; -import org.springframework.stereotype.Service; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; -@Service public class RdfUtils { + + private RdfUtils(){} private static Config config; + private static UriUtils uriUtils; + private static final String DATE_FORMAT = "yyyy-MM-dd"; static ValueFactory factory = SimpleValueFactory.getInstance(); - - public static Resource blankNode(){ - return factory.createBNode(); - } public static String getBaseGraph(){ return config.getBaseGraph(); @@ -82,11 +80,11 @@ public static Resource conceptScheme(){ } public static IRI objectIRI(ObjectType objType, String id) { - return factory.createIRI(objType.getBaseUriGestion() + "/" + id); + return factory.createIRI(uriUtils.getBaseUriGestion(objType) + "/" + id); } public static IRI objectIRIPublication(ObjectType objType, String id) { - return factory.createIRI(objType.getBaseUriPublication() + "/" + id); + return factory.createIRI(uriUtils.getBaseUriPublication(objType) + "/" + id); } public static IRI structureComponentAttributeIRI(String id) { @@ -108,7 +106,7 @@ public static IRI conceptIRI(String id) { return objectIRI(ObjectType.CONCEPT, id); } public static IRI conceptIRI() { - return factory.createIRI(ObjectType.CONCEPT.getBaseUriGestion()); + return factory.createIRI(uriUtils.getBaseUriGestion(ObjectType.CONCEPT)); } public static IRI collectionIRI(String id) { @@ -149,7 +147,7 @@ public static IRI createIRI(String uri){ public static IRI versionableNoteIRI(String conceptId, VersionableNote versionableNote) { return RdfUtils.factory.createIRI( - ObjectType.CONCEPT.getBaseUriGestion() + uriUtils.getBaseUriGestion(ObjectType.CONCEPT) + "/" + conceptId + "/" + versionableNote.getPath() + "/v" + versionableNote.getVersion() @@ -159,7 +157,7 @@ public static IRI versionableNoteIRI(String conceptId, VersionableNote versionab public static IRI previousVersionableNoteIRI(String conceptId, VersionableNote versionableNote) { String version = String.valueOf(Integer.parseInt(versionableNote.getVersion()) - 1); return RdfUtils.factory.createIRI( - ObjectType.CONCEPT.getBaseUriGestion() + uriUtils.getBaseUriGestion(ObjectType.CONCEPT) + "/" + conceptId + "/" + versionableNote.getPath() + "/v" + version @@ -168,7 +166,7 @@ public static IRI previousVersionableNoteIRI(String conceptId, VersionableNote v public static IRI datableNoteIRI(String conceptId, DatableNote datableNote) { String parsedDate = DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now()); - return RdfUtils.factory.createIRI(ObjectType.CONCEPT.getBaseUriGestion() + "/" + conceptId + "/" + datableNote.getPath() + return RdfUtils.factory.createIRI(uriUtils.getBaseUriGestion(ObjectType.CONCEPT) + "/" + conceptId + "/" + datableNote.getPath() + "/" + parsedDate + "/" + datableNote.getLang()); } @@ -277,6 +275,10 @@ public static IRI createXSDIRI(String suffix){ public static void setConfig(Config config) { RdfUtils.config = config; } + + public static void setUriUtils(UriUtils uriUtils){ + RdfUtils.uriUtils=uriUtils; + } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java index bf78db98b..aa554868a 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java @@ -4,8 +4,6 @@ import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.ontologies.EVOC; import fr.insee.rmes.persistance.ontologies.INSEE; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.SKOS; @@ -16,8 +14,9 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.DependsOn; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; @@ -28,7 +27,6 @@ import java.util.List; @Component("RepositoryGestion") -@DependsOn("AppContext") public class RepositoryGestion { @Autowired @@ -41,9 +39,9 @@ public class RepositoryGestion { private static final String FAILURE_REPLACE_GRAPH = "Failure replace graph : "; private static final String FAILURE_DELETE_OBJECT = "Failure delete object"; - static final Logger logger = LogManager.getLogger(RepositoryGestion.class); + static final Logger logger = LoggerFactory.getLogger(RepositoryGestion.class); - @PostConstruct + @PostConstruct public void init() { repositoryUtils.initRepository(config.getRdfServerGestion(), config.getRepositoryIdGestion()); @@ -128,18 +126,18 @@ public RepositoryResult getHasPartStatements(RepositoryConnection con throws RmesException { return getStatementsPredicatObject(con, DCTERMS.HAS_PART,object); } - + public RepositoryResult getReplacesStatements(RepositoryConnection con, Resource object) throws RmesException { return getStatementsPredicatObject(con, DCTERMS.REPLACES,object); } - + public RepositoryResult getIsReplacedByStatements(RepositoryConnection con, Resource object) throws RmesException { return getStatementsPredicatObject(con, DCTERMS.IS_REPLACED_BY,object); } - - + + private RepositoryResult getStatementsPredicatObject(RepositoryConnection con, IRI predicate, Resource object) throws RmesException { @@ -163,7 +161,7 @@ public File getGraphAsFile(String context) throws RmesException { return repositoryUtils.getAllGraphsInZip(repositoryUtils.initRepository(config.getRdfServerGestion(), config.getRepositoryIdGestion())); } - + public String[] getAllGraphs() throws RmesException { return repositoryUtils.getAllGraphs(repositoryUtils.initRepository(config.getRdfServerGestion(), config.getRepositoryIdGestion())); @@ -190,13 +188,13 @@ public void loadConcept(IRI concept, Model model, List> notesToDeleteA conn.remove(note, EVOC.NOTE_LITERAL, null); } // links to delete - clearConceptLinks(concept, conn); + clearConceptLinks(concept); loadSimpleObject(concept, model, conn); } catch (RepositoryException e) { throwsRmesException(e, "Failure load concept : " + concept); - } + } } public void deleteTripletByPredicateAndValue(Resource object, IRI predicate, Resource graph, RepositoryConnection conn, Value value) throws RmesException { @@ -299,7 +297,7 @@ public void replaceGraph(Resource graph, Model model, RepositoryConnection conn) } } - + public HttpStatus persistFile(InputStream input, RDFFormat format, String graph) throws RmesException { return repositoryUtils.persistFile(input, format, graph, repositoryUtils.initRepository(config.getRdfServerGestion(), config.getRepositoryIdGestion()), null); @@ -348,8 +346,8 @@ public void objectValidation(IRI ressourceURI, Model model) throws RmesException } } - public void clearConceptLinks(Resource concept, RepositoryConnection conn) throws RmesException { - conn = repositoryUtils.initRepository(config.getRdfServerGestion(), + public void clearConceptLinks(Resource concept) throws RmesException { + RepositoryConnection conn = repositoryUtils.initRepository(config.getRdfServerGestion(), config.getRepositoryIdGestion()).getConnection(); List typeOfLink = Arrays.asList(SKOS.BROADER, SKOS.NARROWER, SKOS.RELATED, DCTERMS.IS_REPLACED_BY); getStatementsAndRemove(concept, conn, typeOfLink); @@ -438,7 +436,7 @@ private static void throwsRmesException(Exception e, String details) throws Rmes } public void loadSimpleObject(IRI geoIRI, Model model) throws RmesException { - loadSimpleObject(geoIRI, model, null); + loadSimpleObject(geoIRI, model, null); } public RepositoryConnection getConnection() throws RmesException { @@ -465,4 +463,5 @@ public void overrideTriplets(IRI simsUri, Model model, Resource graph) throws Rm public RepositoryResult getCompleteGraph(RepositoryConnection con, Resource graphIri) throws RmesException { return repositoryUtils.getCompleteGraph(con,graphIri); } + } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiator.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiator.java index 8f6358605..1bf9902df 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiator.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiator.java @@ -4,9 +4,6 @@ import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.http.HTTPRepository; -import java.util.Map; -import java.util.Objects; - public interface RepositoryInitiator { static RepositoryInitiator newInstance(Type type, KeycloakServices keycloakServices) { switch (type) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthent.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthent.java index 23134597f..a922b202a 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthent.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthent.java @@ -1,12 +1,11 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; import fr.insee.rmes.bauhaus_services.keycloak.KeycloakServices; - import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.http.HTTPRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; @@ -18,7 +17,7 @@ public class RepositoryInitiatorWithAuthent implements RepositoryInitiator { private final Map repositories=new HashMap<>(); - static final Logger logger = LogManager.getLogger(RepositoryInitiatorWithAuthent.class); + static final Logger logger = LoggerFactory.getLogger(RepositoryInitiatorWithAuthent.class); public RepositoryInitiatorWithAuthent(KeycloakServices keycloakServices) { this.keycloakServices=keycloakServices; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryPublication.java index 94ca66629..c05b739bd 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryPublication.java @@ -1,10 +1,7 @@ package fr.insee.rmes.bauhaus_services.rdf_utils; import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.config.Config; import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -19,10 +16,12 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +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.http.HttpStatus; -import javax.annotation.PostConstruct; import java.io.File; import java.io.InputStream; import java.util.Arrays; @@ -36,9 +35,11 @@ */ @org.springframework.stereotype.Repository("RepositoryPublication") public class RepositoryPublication{ - - @Autowired - protected Config config; + private final String rdfServerPublicationExt; + private final String idRepositoryPublicationExt; + private final String rdfServerPublicationInt; + private final String idRepositoryPublicationInt; + private final RepositoryUtils repositoryUtils; private static final String THREE_PARAMS_LOG = "{} {} {}"; @@ -46,22 +47,18 @@ public class RepositoryPublication{ private static final String FAILED = " failed"; - @Autowired - private RepositoryUtils repositoryUtils; - - - static final Logger logger = LogManager.getLogger(RepositoryPublication.class); - - @PostConstruct - public void init() { - repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication()); - repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne()); - } - + static final Logger logger = LoggerFactory.getLogger(RepositoryPublication.class); - - public void setConfig(Config config) { - this.config = config; + public RepositoryPublication(@Value("${fr.insee.rmes.bauhaus.sesame.publication.sesameServer}") String rdfServerPublicationExt, @Value("${fr.insee.rmes.bauhaus.sesame.publication.repository}") String idRepositoryPublicationExt, + @Value("${fr.insee.rmes.bauhaus.sesame.publication.interne.repository}") String rdfServerPublicationInt, @Value("${fr.insee.rmes.bauhaus.sesame.publication.interne.repository}") String idRepositoryPublicationInt, + @Autowired RepositoryUtils repositoryUtils ) { + this.rdfServerPublicationExt=rdfServerPublicationExt; + this.idRepositoryPublicationExt=idRepositoryPublicationExt; + this.repositoryUtils=repositoryUtils; + this.rdfServerPublicationInt=rdfServerPublicationInt; + this.idRepositoryPublicationInt=idRepositoryPublicationInt; + repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt); + repositoryUtils.initRepository(rdfServerPublicationInt,idRepositoryPublicationInt); } @@ -73,7 +70,7 @@ public void setConfig(Config config) { * @throws RmesException */ public String getResponse(String query) throws RmesException { - return repositoryUtils.getResponse(query, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.getResponse(query, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } /** @@ -84,7 +81,7 @@ public String getResponse(String query) throws RmesException { * @throws RmesException */ public String getResponseInternalPublication(String query) throws RmesException { - return repositoryUtils.getResponse(query, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); + return RepositoryUtils.getResponse(query, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); } /** @@ -95,7 +92,7 @@ public String getResponseInternalPublication(String query) throws RmesException * @throws RmesException */ public JSONArray getResponseAsArray(String query) throws RmesException { - return repositoryUtils.getResponseAsArray(query, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.getResponseAsArray(query, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } /** @@ -106,7 +103,7 @@ public JSONArray getResponseAsArray(String query) throws RmesException { * @throws RmesException */ public JSONObject getResponseAsObject(String query) throws RmesException { - return repositoryUtils.getResponseAsObject(query, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.getResponseAsObject(query, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } /** @@ -118,7 +115,7 @@ public JSONObject getResponseAsObject(String query) throws RmesException { * @throws JSONException */ public Boolean getResponseAsBoolean(String query) throws RmesException { - return repositoryUtils.getResponseForAskQuery(query, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.getResponseForAskQuery(query, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } /** @@ -129,17 +126,17 @@ public Boolean getResponseAsBoolean(String query) throws RmesException { * @throws RmesException */ public HttpStatus executeUpdate(String updateQuery) throws RmesException { - HttpStatus status = repositoryUtils.executeUpdate(updateQuery, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); + HttpStatus status = RepositoryUtils.executeUpdate(updateQuery, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); if (status.is2xxSuccessful() ) { - status = repositoryUtils.executeUpdate(updateQuery, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + status = RepositoryUtils.executeUpdate(updateQuery, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } return status; } public void publishConcept(Resource concept, Model model, List noteToClear, List topConceptOfToDelete) throws RmesException { - publishConcept(concept, model, noteToClear,topConceptOfToDelete, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); - publishConcept(concept, model, noteToClear,topConceptOfToDelete, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + publishConcept(concept, model, noteToClear,topConceptOfToDelete, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); + publishConcept(concept, model, noteToClear,topConceptOfToDelete, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } private void publishConcept(Resource concept, Model model, List noteToClear, @@ -173,8 +170,8 @@ private void publishConcept(Resource concept, Model model, List noteTo } public void publishResource(Resource resource, Model model, String type) throws RmesException { - publishResource(resource, model, type, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); - publishResource(resource, model, type, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + publishResource(resource, model, type, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); + publishResource(resource, model, type, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } private static void publishResource(Resource resource, Model model, String type, Repository repo) throws RmesException { @@ -194,22 +191,22 @@ private static void publishResource(Resource resource, Model model, String type, } public void publishContext(Resource graph, Model model, String type) throws RmesException { - publishContext(graph, model, type, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); - publishContext(graph, model, type, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + publishContext(graph, model, type, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); + publishContext(graph, model, type, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } public HttpStatus persistFile(InputStream input, RDFFormat format, String graph) throws RmesException { - return repositoryUtils.persistFile(input, format, graph, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne()), repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.persistFile(input, format, graph, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt), repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } public File getGraphAsFile(String context) throws RmesException { - if (context != null) return repositoryUtils.getCompleteGraphInTrig(repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication()), context); - return repositoryUtils.getAllGraphsInZip(repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + if (context != null) return RepositoryUtils.getCompleteGraphInTrig(repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt), context); + return RepositoryUtils.getAllGraphsInZip(repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } public String[] getAllGraphs() throws RmesException { - return repositoryUtils.getAllGraphs(repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); + return RepositoryUtils.getAllGraphs(repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); } private static void publishContext(Resource context, Model model, String type, Repository repo) throws RmesException { @@ -229,8 +226,8 @@ private static void publishContext(Resource context, Model model, String type, R } public void clearStructureAndComponentForAllRepositories(Resource structure) throws RmesException { - repositoryUtils.clearStructureAndComponents(structure, repositoryUtils.initRepository(config.getRdfServerPublication(), config.getRepositoryIdPublication())); - repositoryUtils.clearStructureAndComponents(structure, repositoryUtils.initRepository(config.getRdfServerPublicationInterne(), config.getRepositoryIdPublicationInterne())); + RepositoryUtils.clearStructureAndComponents(structure, repositoryUtils.initRepository(rdfServerPublicationExt, idRepositoryPublicationExt)); + RepositoryUtils.clearStructureAndComponents(structure, repositoryUtils.initRepository(rdfServerPublicationInt, idRepositoryPublicationInt)); } private void clearConceptLinks(Resource concept, RepositoryConnection conn) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java index 72066822c..806391618 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java @@ -5,8 +5,7 @@ import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.ontologies.QB; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.eclipse.rdf4j.common.exception.RDF4JException; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; @@ -26,7 +25,8 @@ import org.eclipse.rdf4j.rio.trig.TriGWriter; import org.json.JSONArray; import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -45,8 +45,8 @@ public class RepositoryUtils { private static final String RESULTS = "results"; private static final String EXECUTE_QUERY_FAILED = "Execute query failed : "; - static final Logger logger = LogManager.getLogger(RepositoryUtils.class); - private RepositoryInitiator repositoryInitiator; + static final Logger logger = LoggerFactory.getLogger(RepositoryUtils.class); + private final RepositoryInitiator repositoryInitiator; public RepositoryUtils(KeycloakServices keycloakServices, @Value("${fr.insee.rmes.bauhaus.rdf.auth}")RepositoryInitiator.Type type){ @@ -95,6 +95,7 @@ public static HttpStatus executeUpdate(String updateQuery,Repository repository) update = conn.prepareUpdate(QueryLanguage.SPARQL, queryWithPrefixes); update.execute(); conn.close(); + logTrace("Repo {} --- Executed update --- \n{}", repository, queryWithPrefixes); } catch (RepositoryException e) { logger.error("{} {} {}",EXECUTE_QUERY_FAILED, updateQuery, repository); logger.error(e.getMessage()); @@ -102,7 +103,14 @@ public static HttpStatus executeUpdate(String updateQuery,Repository repository) } return(HttpStatus.OK); } - + + private static void logTrace(String message, Repository repository, String queryWithPrefixes) { + if (logger.isTraceEnabled()){ + var repoUrl=repository instanceof HTTPRepository httpRepository ? httpRepository.getRepositoryURL():"unknown ("+repository.getClass()+")"; + logger.trace(message, repoUrl, queryWithPrefixes); + } + } + /** * Method which aims to load a file in database * @param graph @@ -281,16 +289,25 @@ public static String[] getAllGraphs(Repository repo) throws RmesException { */ public static String executeQuery(RepositoryConnection conn, String query) throws RmesException { TupleQuery tupleQuery = null; - OutputStream stream = new ByteArrayOutputStream(); + String result; try { + var stream = new ByteArrayOutputStream(); tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.evaluate(new SPARQLResultsJSONWriter(stream)); - } catch (RepositoryException e) { - logAndThrowError(query, e); + result= stream.toString(); + traceLogResult(conn, query, result); + } catch (RDF4JException e) { + logAndThrowError(query, e); + result=""; } - return stream.toString(); + return result; } - + + private static void traceLogResult(RepositoryConnection conn, String query, String result) { + logTrace("Repo {} --- Executed query --- \n{}", conn.getRepository(), query); + logger.trace("--- Results ---\n{}", result); + } + /** * Method which aims to execute a sparql ASK query * @@ -302,8 +319,10 @@ public static boolean executeAskQuery(RepositoryConnection conn, String query) t BooleanQuery tupleQuery = null; try { tupleQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, query); - return tupleQuery.evaluate(); - } catch (RepositoryException e) { + var result = tupleQuery.evaluate(); + traceLogResult(conn, query, Boolean.toString(result)); + return result; + } catch (RDF4JException e) { logAndThrowError(query, e); } return false; @@ -323,13 +342,13 @@ public static String getResponse(String query, Repository repository) throws Rme String queryWithPrefixes = QueryUtils.PREFIXES + query; response = executeQuery(conn, queryWithPrefixes); conn.close(); - } catch (RepositoryException e) { + } catch (RDF4JException e) { logAndThrowError(query, e); } return response; } - private static void logAndThrowError(String query, RepositoryException e) throws RmesException { + private static void logAndThrowError(String query, RDF4JException e) throws RmesException { logger.error("{} {}",EXECUTE_QUERY_FAILED, query); logger.error(e.getMessage()); throw new RmesException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), EXECUTE_QUERY_FAILED + query); @@ -349,7 +368,7 @@ public static boolean getResponseForAskQuery(String query, Repository repository String queryWithPrefixes = QueryUtils.PREFIXES + query; response = executeAskQuery(conn, queryWithPrefixes); conn.close(); - } catch (RepositoryException e) { + } catch (RDF4JException e) { logAndThrowError(query, e); } return response; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/UriUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/UriUtils.java new file mode 100644 index 000000000..2331a1e9f --- /dev/null +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/UriUtils.java @@ -0,0 +1,49 @@ +package fr.insee.rmes.bauhaus_services.rdf_utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +import static fr.insee.rmes.config.PropertiesKeys.BASE_URI_GESTION; +import static fr.insee.rmes.config.PropertiesKeys.BASE_URI_PUBLICATION; + +@Component +public record UriUtils( String baseUriPublication, String baseUriGestion, PropertiesFinder propertiesFinder) { + + public UriUtils(@Value("${"+BASE_URI_PUBLICATION+"}") String baseUriPublication, + @Value("${"+BASE_URI_GESTION+"}") String baseUriGestion, + @Autowired PropertiesFinder propertiesFinder){ + this.baseUriPublication=baseUriPublication; + this.baseUriGestion=baseUriGestion; + this.propertiesFinder=propertiesFinder; + RdfUtils.setUriUtils(this); + } + + public String getBaseUriPublication(ObjectType objectType){ + return baseUriPublication + getBaseUri(objectType).orElse(""); + } + + public String getBaseUriGestion(ObjectType objectType) { + return this.baseUriGestion + getBaseUri(objectType).orElse(""); + } + + /** + * Get label by URI + */ + public String getCompleteUriGestion(String labelType, String id) { + var enumByLabel=ObjectType.getEnumByLabel(labelType); + return enumByLabel.map(this::getBaseUriGestion).orElse(ObjectType.UNDEFINED.baseUriModifier().apply("")) + + "/" + id; + } + + private Optional getBaseUri(ObjectType objectType){ + return propertiesFinder.findByName(objectType.baseUriPropertyName()) + .map(objectType.baseUriModifier()); + } + + public interface PropertiesFinder { + Optional findByName(String name); + } +} diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImpl.java index 924e8632c..821a2e824 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImpl.java @@ -1,24 +1,8 @@ package fr.insee.rmes.bauhaus_services.stamps; -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; -import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProvider; import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; import fr.insee.rmes.config.auth.user.AuthorizeMethodDecider; import fr.insee.rmes.config.auth.user.User; @@ -26,134 +10,91 @@ import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.persistance.sparql_queries.operations.indicators.IndicatorsQueries; import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; +import org.eclipse.rdf4j.model.IRI; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; +import java.util.List; +import java.util.Map; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import java.util.stream.Stream; -@Service -public class StampsRestrictionServiceImpl implements StampsRestrictionsService { - - @Autowired - protected RepositoryGestion repoGestion; - - static final Logger logger = LogManager.getLogger(StampsRestrictionServiceImpl.class); +import static fr.insee.rmes.utils.StringUtils.urisAsString; - @Autowired - Config config; - - - @Autowired - private AuthorizeMethodDecider authorizeMethodDecider; +@Service +public record StampsRestrictionServiceImpl(RepositoryGestion repoGestion, AuthorizeMethodDecider authorizeMethodDecider, UserProvider userProvider) implements StampsRestrictionsService { + + private static final Logger logger = LoggerFactory.getLogger(StampsRestrictionServiceImpl.class); @Override public boolean isConceptOrCollectionOwner(IRI uri) throws RmesException { - User user = getUser(); - if (authorizeMethodDecider.isAdmin(user)) { - return true; - } - String uriAsString = "<" + RdfUtils.toString(uri) + ">"; - JSONObject owner = repoGestion.getResponseAsObject(ConceptsQueries.getOwner(uriAsString)); - Boolean isConceptOwner = true; - if (!owner.getString(Constants.OWNER).equals(user.getStamp())) { - isConceptOwner = false; - } - return isConceptOwner; + return isConceptsOrCollectionsOwner(List.of(uri)); } @Override public boolean isConceptsOrCollectionsOwner(List uris) throws RmesException { - User user = getUser(); - if (authorizeMethodDecider.isAdmin(user)) { + if (authorizeMethodDecider.isAdmin()) { return true; } - StringBuilder sb = new StringBuilder(); - uris.forEach(u -> sb.append("<" + RdfUtils.toString(u) + "> ")); - String uriAsString = sb.toString(); - JSONArray owners = repoGestion.getResponseAsArray(ConceptsQueries.getOwner(uriAsString)); - Boolean isConceptsOwner = true; - for (int i = 0; i < owners.length(); i++) { - if (!owners.getJSONObject(i).getString(Constants.OWNER).equals(user.getStamp())) { - isConceptsOwner = false; - } - } - return isConceptsOwner; + return isConceptOwner(uris); } + private boolean isConceptOwner(List uris) throws RmesException { + return isOwnerForModule(uris, ConceptsQueries::getOwner, Constants.OWNER); + } + private boolean isConceptManager(IRI uri) throws RmesException { + return isManagerForModule(uri, ConceptsQueries::getManager, Constants.MANAGER); + } - - public void setFakeUser(String user) throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure( - DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JSONObject userObject = new JSONObject(user); - - JSONArray roles = userObject.getJSONArray("roles"); - - new User("fakeUser",roles, userObject.getString(Constants.STAMP)); + protected boolean isSeriesManager(IRI uri) throws RmesException { + return isOwnerForModule(List.of(uri), OpSeriesQueries::getCreatorsBySeriesUri, Constants.CREATORS); } + private boolean isIndicatorCreator(IRI iri) throws RmesException { + return isOwnerForModule(List.of(iri), IndicatorsQueries::getCreatorsByIndicatorUri, Constants.CREATORS); + } - private boolean isConceptOwner(List uris) throws RmesException { - User user = getUser(); - StringBuilder sb = new StringBuilder(); - uris.forEach(u -> sb.append("<" + RdfUtils.toString(u) + "> ")); - String uriAsString = sb.toString(); - JSONArray owners = repoGestion.getResponseAsArray(ConceptsQueries.getOwner(uriAsString)); - Boolean isConceptOwner = true; - for (int i = 0; i < owners.length(); i++) { - if (!owners.getJSONObject(i).getString(Constants.OWNER).equals(user.getStamp())) { - isConceptOwner = false; - } - } - return isConceptOwner; + private boolean isManagerForModule(IRI uri, QueryGenerator queryGenerator, String stampKey) throws RmesException { + logger.trace("Check management access for {} with stamp {}",uri, stampKey); + return checkResponsabilityForModule(List.of(uri), queryGenerator, stampKey, Stream::anyMatch); } - private boolean isConceptManager(List uris) throws RmesException { - User user = getUser(); - StringBuilder sb = new StringBuilder(); - uris.forEach(u -> sb.append("<" + RdfUtils.toString(u) + "> ")); - String uriAsString = sb.toString(); - JSONArray managers = repoGestion.getResponseAsArray(ConceptsQueries.getManager(uriAsString)); - Boolean isConceptManager = true; - for (int i = 0; i < managers.length(); i++) { - if (!managers.getJSONObject(i).getString(Constants.MANAGER).equals(user.getStamp())) { - isConceptManager = false; - } - } - return isConceptManager; + private boolean isOwnerForModule(List uris, QueryGenerator queryGenerator, String stampKey) throws RmesException { + logger.trace("Check ownership for {} with stamp {}",uris, stampKey); + return checkResponsabilityForModule(uris, queryGenerator, stampKey, Stream::allMatch); } - public boolean isSeriesManager(IRI uri) throws RmesException { - User user = getUser(); - JSONArray managers = repoGestion.getResponseAsArray(OpSeriesQueries.getCreatorsBySeriesUri(RdfUtils.toString(uri))); - Boolean isSeriesManager = false; - for (int i = 0; i < managers.length(); i++) { - if (managers.getJSONObject(i).getString(Constants.CREATORS).equals(user.getStamp())) { - isSeriesManager = true; - } - } - return isSeriesManager; + private boolean checkResponsabilityForModule(List uris, QueryGenerator queryGenerator, String stampKey, BiPredicate, Predicate> predicateMatcher) throws RmesException { + JSONArray owners = repoGestion.getResponseAsArray(queryGenerator.generate(urisAsString(uris))); + var stamp=getUser().getStamp(); + return StringUtils.hasLength(stamp) && + predicateMatcher.test(owners.toList().stream() + .map(o-> findStamp(o, stampKey)), + stamp::equals // apply predicate `stamp::equals` to the stream of stamps returned at the previous line + ); } - private boolean isIndicatorManager(IRI iri) throws RmesException { - User user = getUser(); - String uriAsString = "<" + RdfUtils.toString(iri) + "> "; - JSONArray creators = repoGestion.getResponseAsArray(IndicatorsQueries.getCreatorsByIndicatorUri(uriAsString)); - Boolean isIndicatorManager = false; - if (creators.length() > 0) { - for (int i = 0; i < creators.length(); i++) { - if (creators.getJSONObject(i).getString(Constants.CREATORS).equals(user.getStamp())) { - isIndicatorManager = true; - } - } + private Object findStamp(Object o, String stampKey) { + if (o instanceof JSONObject jsonObject) { + return jsonObject.get(stampKey); + } + if (o instanceof Map, ?> map) { + return map.get(stampKey); } - return isIndicatorManager; + return null; } + private boolean canModifyOrValidateIndicator(IRI iri) throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || (isIndicatorManager(iri) && authorizeMethodDecider.isIndicatorContributor(user))); + return (authorizeMethodDecider.isAdmin() || (isIndicatorCreator(iri) && authorizeMethodDecider.isIndicatorContributor())); } @Override @@ -168,19 +109,17 @@ public boolean canValidateIndicator(IRI uri) throws RmesException { @Override public boolean canModifySims(IRI seriesOrIndicatorUri) throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || authorizeMethodDecider.isCnis(user) || (isSeriesManager(seriesOrIndicatorUri) && authorizeMethodDecider.isSeriesContributor(user)) - || (isIndicatorManager(seriesOrIndicatorUri) && authorizeMethodDecider.isIndicatorContributor(user))); + return (authorizeMethodDecider.isAdmin() || authorizeMethodDecider.isCnis() || (isSeriesManager(seriesOrIndicatorUri) && authorizeMethodDecider.isSeriesContributor()) + || (isIndicatorCreator(seriesOrIndicatorUri) && authorizeMethodDecider.isIndicatorContributor())); } @Override - public boolean canCreateConcept() throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || authorizeMethodDecider.isConceptsContributor(user)); + public boolean canCreateConcept() { + return (authorizeMethodDecider.isAdmin() || authorizeMethodDecider.isConceptsContributor()); } @Override - public boolean canCreateFamily() throws RmesException { + public boolean canCreateFamily() { return canCreateFamilySeriesOrIndicator(); } @@ -189,46 +128,40 @@ private boolean canCreateFamilySeriesOrIndicator() { } @Override - public boolean canCreateSeries() throws RmesException { + public boolean canCreateSeries() { return canCreateFamilySeriesOrIndicator(); } @Override - public boolean canCreateIndicator() throws RmesException { + public boolean canCreateIndicator() { return canCreateFamilySeriesOrIndicator(); } @Override public boolean canCreateOperation(IRI seriesURI) throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || (isSeriesManager(seriesURI) && authorizeMethodDecider.isSeriesContributor(user))); + return (authorizeMethodDecider.isAdmin() || (isSeriesManager(seriesURI) && authorizeMethodDecider.isSeriesContributor())); } @Override public boolean canCreateSims(IRI seriesOrIndicatorUri) throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || (isSeriesManager(seriesOrIndicatorUri) && authorizeMethodDecider.isSeriesContributor(user)) - || (isIndicatorManager(seriesOrIndicatorUri) && authorizeMethodDecider.isIndicatorContributor(user))); + return (authorizeMethodDecider.isAdmin() || (isSeriesManager(seriesOrIndicatorUri) && authorizeMethodDecider.isSeriesContributor()) + || (isIndicatorCreator(seriesOrIndicatorUri) && authorizeMethodDecider.isIndicatorContributor())); } @Override - public boolean canDeleteSims() throws RmesException { + public boolean canDeleteSims() { return authorizeMethodDecider.isAdmin(); } @Override public boolean canModifyConcept(IRI uri) throws RmesException { - User user = getUser(); - List uris = new ArrayList<>(); - uris.add(uri); - return (authorizeMethodDecider.isAdmin(user) || authorizeMethodDecider.isConceptsContributor(user) || (isConceptManager(uris) && authorizeMethodDecider.isConceptContributor(user)) - || (isConceptOwner(uris)) && authorizeMethodDecider.isConceptCreator(user)); + return authorizeMethodDecider.isAdmin() || authorizeMethodDecider.isConceptsContributor() || (isConceptManager(uri) && authorizeMethodDecider.isConceptContributor()) + || (isConceptOwner(List.of(uri)) && authorizeMethodDecider.isConceptCreator()); } @Override public boolean canModifySeries(IRI uri) throws RmesException { - User user = getUser(); - return ((isSeriesManager(uri) && authorizeMethodDecider.isSeriesContributor(user)) || authorizeMethodDecider.isAdmin(user) || authorizeMethodDecider.isCnis(user) ); + return ((isSeriesManager(uri) && authorizeMethodDecider.isSeriesContributor()) || authorizeMethodDecider.isAdmin() || authorizeMethodDecider.isCnis() ); } @Override @@ -238,29 +171,21 @@ public boolean canModifyOperation(IRI seriesURI) throws RmesException { @Override public boolean canValidateSeries(IRI uri) throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || (isSeriesManager(uri) && authorizeMethodDecider.isSeriesContributor(user))); - } - - @Override - public boolean canValidateOperation(IRI seriesURI) throws RmesException { - return canValidateSeries(seriesURI); + return (authorizeMethodDecider.isAdmin() || (isSeriesManager(uri) && authorizeMethodDecider.isSeriesContributor())); } @Override - public boolean canManageDocumentsAndLinks() throws RmesException { - User user = getUser(); - return (authorizeMethodDecider.isAdmin(user) || authorizeMethodDecider.isSeriesContributor(user) || authorizeMethodDecider.isIndicatorContributor(user)); + public boolean canManageDocumentsAndLinks() { + return (authorizeMethodDecider.isAdmin() || authorizeMethodDecider.isSeriesContributor() || authorizeMethodDecider.isIndicatorContributor()); } @Override - public boolean canValidateClassification(IRI uri) throws RmesException { + public boolean canValidateClassification(IRI uri) { return authorizeMethodDecider.isAdmin(); } - @Override - public User getUser() throws RmesException { - return authorizeMethodDecider.getUser(); + private User getUser() { + return this.userProvider.findUserDefaultToEmpty(); } @Override @@ -268,6 +193,8 @@ public boolean isAdmin() { return authorizeMethodDecider.isAdmin(); } - + private interface QueryGenerator { + String generate(String query) throws RmesException; + } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java index 8a0c56f1e..ca5fe2f44 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java @@ -1,23 +1,21 @@ package fr.insee.rmes.bauhaus_services.structures.impl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.webjars.NotFoundException; - import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.structures.StructureComponent; import fr.insee.rmes.bauhaus_services.structures.utils.StructureComponentUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; import fr.insee.rmes.persistance.sparql_queries.structures.StructureQueries; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; @Service public class StructureComponentImpl extends RdfService implements StructureComponent { - static final Logger logger = LogManager.getLogger(StructureComponentImpl.class); + static final Logger logger = LoggerFactory.getLogger(StructureComponentImpl.class); @Autowired StructureComponentUtils structureComponentUtils; @@ -96,7 +94,7 @@ public String createComponent( String body) throws RmesException { public void deleteComponent(String id) throws RmesException { JSONObject response = this.getComponentObject(id); if(response.keySet().isEmpty()){ - throw new NotFoundException("This component does not exist"); + throw new RmesNotFoundException("Not Found","component with "+id+" not found"); } String type = response.getString("type"); structureComponentUtils.deleteComponent(response, id, type); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java index 11e02e136..300b754d9 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java @@ -1,12 +1,5 @@ package fr.insee.rmes.bauhaus_services.structures.impl; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import fr.insee.rmes.bauhaus_services.CodeListService; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; @@ -17,11 +10,17 @@ import fr.insee.rmes.persistance.ontologies.QB; import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.persistance.sparql_queries.structures.StructureQueries; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; @Service public class StructureImpl extends RdfService implements StructureService { - static final Logger logger = LogManager.getLogger(StructureImpl.class); + static final Logger logger = LoggerFactory.getLogger(StructureImpl.class); @Autowired StructureUtils structureUtils; @@ -90,8 +89,7 @@ else if(type.equalsIgnoreCase(RdfUtils.toString(QB.DIMENSION_PROPERTY))){ try { codeList.put("codes", new JSONArray(this.codeListService.geCodesListByIRI(component.getString(Constants.CODELIST)))); } catch (RmesException e) { - logger.error("Cannot fetch code list of the structure {}" , id); - logger.error(e); + logger.error("Cannot fetch code list of the structure "+id, e); } component.put(Constants.CODELIST, codeList); @@ -102,8 +100,7 @@ else if(type.equalsIgnoreCase(RdfUtils.toString(QB.DIMENSION_PROPERTY))){ JSONObject concept = repoGestion.getResponseAsObject(ConceptsQueries.conceptQueryForDetailStructure(component.getString(Constants.CONCEPT))); component.put(Constants.CONCEPT, concept); } catch (RmesException e) { - logger.error("Cannot fetch concept of the structure {}" , id); - logger.error(e); + logger.error("Cannot fetch concept of the structure " +id, e); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/ComponentPublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/ComponentPublication.java index 17d5a9959..b12184417 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/ComponentPublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/ComponentPublication.java @@ -1,5 +1,10 @@ package fr.insee.rmes.bauhaus_services.structures.utils; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.RmesException; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; @@ -11,13 +16,6 @@ import org.eclipse.rdf4j.repository.RepositoryResult; import org.springframework.stereotype.Repository; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.RmesException; - @Repository public class ComponentPublication extends RdfService { @@ -40,11 +38,11 @@ public void publishComponent(Resource component, IRI type) throws RmesException || pred.endsWith(Constants.CODELIST) || pred.endsWith(Constants.CONCEPT) || pred.endsWith("range")) { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); @@ -59,7 +57,7 @@ public void publishComponent(Resource component, IRI type) throws RmesException repoGestion.closeStatements(statements); con.close(); } - Resource componentToPublishRessource = PublicationUtils.tranformBaseURIToPublish(component); + Resource componentToPublishRessource = publicationUtils.tranformBaseURIToPublish(component); repositoryPublication.publishResource(componentToPublishRessource, model, RdfUtils.toString(type)); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java index 49cd67e2a..7cba2e1ad 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java @@ -19,8 +19,6 @@ import fr.insee.rmes.utils.DateUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -28,6 +26,8 @@ import org.eclipse.rdf4j.model.vocabulary.*; import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -36,11 +36,12 @@ @Component public class StructureComponentUtils extends RdfService { + static final Logger logger = LoggerFactory.getLogger(StructureComponentUtils.class); + private static final String MAX_LENGTH = "maxLength"; private static final String MIN_LENGTH = "minLength"; private static final String PATTERN = "pattern"; private static final String IO_EXCEPTION = "IOException"; - static final Logger logger = LogManager.getLogger(StructureComponentUtils.class); public static final String VALIDATED = "Validated"; public static final String MODIFIED = "Modified"; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructurePublication.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructurePublication.java index a20eca6ba..e554ff287 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructurePublication.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructurePublication.java @@ -1,5 +1,10 @@ package fr.insee.rmes.bauhaus_services.structures.utils; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.exceptions.RmesException; import org.apache.http.HttpStatus; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Resource; @@ -10,13 +15,6 @@ import org.eclipse.rdf4j.repository.RepositoryResult; import org.springframework.stereotype.Repository; -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.rdf_utils.PublicationUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.exceptions.RmesException; - @Repository public class StructurePublication extends RdfService { @@ -33,20 +31,20 @@ private void copyTriplet(Resource structure, Model model, RepositoryConnection c if (PublicationUtils.stringEndsWithItemFromList(pred,denyList)) { // nothing, wouldn't copy this attr } else if(pred.endsWith("component")){ - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); copyTriplet((Resource) st.getObject(), model, con, new String[]{"identifier", "created", "modified"}); } else if(pred.endsWith("attribute") || pred.endsWith("measure") || pred.endsWith("dimension")){ - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), - PublicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), + publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()), st.getContext()); } else { - model.add(PublicationUtils.tranformBaseURIToPublish(st.getSubject()), + model.add(publicationUtils.tranformBaseURIToPublish(st.getSubject()), st.getPredicate(), st.getObject(), st.getContext()); @@ -69,7 +67,7 @@ public void publish(Resource structure) throws RmesException { this.copyTriplet(structure, model, con, new String[]{"validationState", Constants.CREATOR, Constants.CONTRIBUTOR}); con.close(); - Resource structureToPublish = PublicationUtils.tranformBaseURIToPublish(structure); + Resource structureToPublish = publicationUtils.tranformBaseURIToPublish(structure); repositoryPublication.clearStructureAndComponentForAllRepositories(structureToPublish); repositoryPublication.publishResource(structureToPublish, model, "Structure"); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java index 951974a2c..311f9e183 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java @@ -1,30 +1,7 @@ package fr.insee.rmes.bauhaus_services.structures.utils; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Model; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.eclipse.rdf4j.model.vocabulary.DC; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.model.vocabulary.RDFS; -import org.eclipse.rdf4j.model.vocabulary.SKOS; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; @@ -41,12 +18,29 @@ import fr.insee.rmes.persistance.ontologies.QB; import fr.insee.rmes.persistance.sparql_queries.structures.StructureQueries; import fr.insee.rmes.utils.DateUtils; +import org.apache.http.HttpStatus; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.impl.LinkedHashModel; +import org.eclipse.rdf4j.model.vocabulary.*; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; @Component public class StructureUtils extends RdfService { private static final String IO_EXCEPTION = "IOException"; - static final Logger logger = LogManager.getLogger(StructureUtils.class); + static final Logger logger = LoggerFactory.getLogger(StructureUtils.class); public static final String ATTACHMENT = "attachment"; public static final String REQUIRED = "required"; public static final String ORDER = "order"; @@ -77,12 +71,10 @@ public JSONArray formatStructuresForSearch(JSONArray structures) throws RmesExce public JSONObject formatStructure(JSONObject structure, String id) throws RmesException { structure.put(Constants.ID, id); - JSONArray componentDefinitions = new JSONArray(); JSONArray componentDefinitionsFlat = repoGestion.getResponseAsArray(StructureQueries.getComponentsForStructure(id)); - for (int i = 0; i < componentDefinitionsFlat.length(); i++) { JSONObject componentDefinitionFlat = componentDefinitionsFlat.getJSONObject(i); JSONArray attachmentsArray = repoGestion.getResponseAsArray(StructureQueries.getStructuresAttachments(id, componentDefinitionFlat.getString(COMPONENT_DEFINITION_ID))); @@ -95,7 +87,7 @@ public JSONObject formatStructure(JSONObject structure, String id) throws RmesEx JSONObject componentDefinition= new JSONObject(); - componentDefinition.put(ATTACHMENT, attachments); + componentDefinition.put(ATTACHMENT, attachments); if(componentDefinitionFlat.has(REQUIRED)){ @@ -111,7 +103,6 @@ public JSONObject formatStructure(JSONObject structure, String id) throws RmesEx } if(componentDefinitionFlat.has(COMPONENT_DEFINITION_MODIFIED)){ componentDefinition.put("modified", componentDefinitionFlat.getString(COMPONENT_DEFINITION_MODIFIED)); - } if(componentDefinitionFlat.has(COMPONENT_DEFINITION_ID)){ componentDefinition.put(Constants.ID, componentDefinitionFlat.getString(COMPONENT_DEFINITION_ID)); @@ -330,7 +321,6 @@ public void createRdfComponentSpecification(IRI structureIRI, ComponentDefinitio } MutualizedComponent component = componentDefinition.getComponent(); if (component.getType().equals(RdfUtils.toString(QB.DIMENSION_PROPERTY))) { - model.add(componentSpecificationIRI, QB.DIMENSION, getDimensionIRI(component.getId()), graph); } if (component.getType().equals(RdfUtils.toString(QB.ATTRIBUTE_PROPERTY))) { diff --git a/src/main/java/fr/insee/rmes/config/ApplicationContext.java b/src/main/java/fr/insee/rmes/config/ApplicationContext.java deleted file mode 100644 index 00b65e76c..000000000 --- a/src/main/java/fr/insee/rmes/config/ApplicationContext.java +++ /dev/null @@ -1,30 +0,0 @@ -package fr.insee.rmes.config; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; - -@Configuration("AppContext") -public class ApplicationContext { - - @Autowired - Config config; - -// @Bean -// public HttpClientBuilder httpClientBuilder() -// throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { -// SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); -// SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); -// return HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLSocketFactory(sslsf); -// } - - - @PostConstruct - public void setUp() { - config.printMajorConfig(); - } - - - -} diff --git a/src/main/java/fr/insee/rmes/config/Config.java b/src/main/java/fr/insee/rmes/config/Config.java index cc79f9827..1cee5b012 100644 --- a/src/main/java/fr/insee/rmes/config/Config.java +++ b/src/main/java/fr/insee/rmes/config/Config.java @@ -4,31 +4,22 @@ import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.external_services.authentication.user_roles_manager.Sugoi; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; +import static fr.insee.rmes.config.PropertiesKeys.*; + + @Configuration public class Config { - - private final Logger logger = LogManager.getLogger(Config.class); /******************************************************/ /** GLOBAL CONF ***********************************/ /******************************************************/ - @Value("${fr.insee.rmes.bauhaus.appHost}") - private String appHost; - - @Value("${fr.insee.rmes.bauhaus.env}") - private String env; - - @Value("${fr.insee.rmes.bauhaus.force.ssl}") - private boolean requiresSsl = false; @Value("${fr.insee.rmes.bauhaus.lg1}") private String lg1; @@ -38,12 +29,6 @@ public class Config { @Value("${fr.insee.rmes.bauhaus.baseGraph}") private String baseGraph; - @Value("${fr.insee.rmes.bauhaus.api.host}") - private String swaggerHost; - @Value("${fr.insee.rmes.bauhaus.api.basepath}") //getSwaggerUrl to have the complete URL - private String swaggerBasepath; - - /******************************************************/ /** DATABASES ***********************************/ /******************************************************/ @@ -53,27 +38,10 @@ public class Config { private String idRepositoryGestion; @Value("${fr.insee.rmes.bauhaus.sesame.gestion.baseURI}") private String baseUriGestion; - @Value("${fr.insee.rmes.bauhaus.sesame.publication.sesameServer}") - private String rdfServerPublicationExt; - @Value("${fr.insee.rmes.bauhaus.sesame.publication.repository}") - private String idRepositoryPublicationExt; - @Value("${fr.insee.rmes.bauhaus.sesame.publication.interne.sesameServer}") - private String rdfServerPublicationInt; - @Value("${fr.insee.rmes.bauhaus.sesame.publication.interne.repository}") - private String idRepositoryPublicationInt; - @Value("${fr.insee.rmes.bauhaus.sesame.publication.baseURI}") - private String baseUriPublication; /******************************************************/ /** EXTERNAL SERVICES *********************************/ /******************************************************/ - //MAIL SENDER - @Value("${fr.insee.rmes.bauhaus.spoc.url}") - private String spocServiceUrl; - @Value("${fr.insee.rmes.bauhaus.spoc.user}") - private String spocUser; - @Value("${fr.insee.rmes.bauhaus.spoc.password}") - private String spocPassword; //BROKER @Value("${fr.insee.rmes.bauhaus.broker.url}") @@ -86,12 +54,9 @@ public class Config { //AUTHENTICATION @Value("${fr.insee.rmes.bauhaus.ldap.url}") private String ldapUrl; - @Value("${jwt.stamp-claim}") - private String stampClaim; - @Value("${jwt.role-claim}") - private String roleClaim; - @Value("${jwt.id-claim}") - private String idClaim; + + + //LDAP //LDAP @@ -105,29 +70,19 @@ public class Config { private String sugoiApp; @Value("${fr.insee.rmes.bauhaus.sugoi.realm}") private String sugoiRealm; - @Value("${fr.insee.rmes.bauhaus.sugoi.ui}") - private String sugoiUi; /******************************************************/ /** CONCEPTS ***********************************/ /******************************************************/ - - @Value("${fr.insee.rmes.bauhaus.concepts.defaultContributor}") - private String defaultContributor; - @Value("${fr.insee.rmes.bauhaus.concepts.defaultMailSender}") - private String defaultMailSender; - @Value("${fr.insee.rmes.bauhaus.concepts.maxLengthScopeNote}") - private String maxLengthScopeNote; + @Value("${fr.insee.rmes.bauhaus.concepts.graph}") //Getter with baseGraph private String conceptsGraph; @Value("${fr.insee.rmes.bauhaus.concepts.scheme}") private String conceptsScheme; - @Value("${fr.insee.rmes.bauhaus.concepts.baseURI}") - private String conceptsBaseUri; - @Value("${fr.insee.rmes.bauhaus.collections.baseURI}") - private String collectionsBaseUri; + + /******************************************************/ @@ -141,14 +96,8 @@ public class Config { /******************************************************/ @Value("${fr.insee.rmes.bauhaus.operations.graph}") //Getter with baseGraph private String operationsGraph; - @Value("${fr.insee.rmes.bauhaus.operations.baseURI}") - private String operationsBaseUri; - @Value("${fr.insee.rmes.bauhaus.operations.series.baseURI}") - private String opSeriesBaseUri; - @Value("${fr.insee.rmes.bauhaus.operations.families.baseURI}") - private String opFamiliesBaseUri; - @Value("${fr.insee.rmes.bauhaus.documentations.baseURI}") - private String documentationsBaseUri; + + @Value("${fr.insee.rmes.bauhaus.documentations.graph}") //Getter with baseGraph private String documentationsGraph; @Value("${fr.insee.rmes.bauhaus.documentations.msd.graph}") //Getter with baseGraph @@ -157,16 +106,14 @@ public class Config { private String msdConceptsGraph; @Value("${fr.insee.rmes.bauhaus.documentation.geographie.graph}") //Getter with baseGraph private String documentationsGeoGraph; - @Value("${fr.insee.rmes.bauhaus.documentation.geographie.baseURI}") - private String documentationsGeoBaseUri; + @Value("${fr.insee.rmes.bauhaus.documentation.titlePrefixLg1}") private String documentationsTitlePrefixLg1; @Value("${fr.insee.rmes.bauhaus.documentation.titlePrefixLg2}") private String documentationsTitlePrefixLg2; - @Value("${fr.insee.rmes.bauhaus.links.baseURI}") + @Value("${"+LINKS_BASE_URI+"}") private String linksBaseUri; - @Value("${fr.insee.rmes.bauhaus.documents.baseURI}") - private String documentsBaseUri; + @Value("${fr.insee.rmes.bauhaus.documents.graph}") //Getter with baseGraph private String documentsGraph; @Value("${fr.insee.rmes.bauhaus.storage.document.gestion}") @@ -188,20 +135,15 @@ public class Config { /******************************************************/ @Value("${fr.insee.rmes.bauhaus.structures.graph}") //Getter with baseGraph private String structuresGraph; - @Value("${fr.insee.rmes.bauhaus.structures.baseURI}") - private String structuresBaseUri; + @Value("${fr.insee.rmes.bauhaus.structures.components.graph}") //Getter with baseGraph private String structuresComponentsGraph; - @Value("${fr.insee.rmes.bauhaus.structures.components.baseURI}") - private String structuresComponentsBaseUri; /******************************************************/ /** CODE LISTS ***********************************/ /******************************************************/ @Value("${fr.insee.rmes.bauhaus.codelists.graph}") //Getter with baseGraph private String codeListsGraph; - @Value("${fr.insee.rmes.bauhaus.codeList.baseURI}") - private String codeListsBaseUri; /******************************************************/ /** ORGANIZATIONS ***********************************/ @@ -218,41 +160,12 @@ public class Config { @Value("${fr.insee.rmes.bauhaus.geographie.graph}") //Getter with baseGraph private String geographyGraph; - - + @Value("${"+CODE_LIST_BASE_URI+"}") + private String codeListBaseUri; + @Value("${"+DOCUMENTS_BASE_URI+"}") + private String documentsBaseUri; - /******************************************************/ - /** PRINTER ***********************************/ - /******************************************************/ - public void printMajorConfig() { - logger.info("*********************** CONFIG USED ***********************************"); - - logger.info("ENV : {}", env); - - logger.info("SERVEUR RDF : "); - - logger.info(" GESTION : {} _ REPO : {} _ BASEURI : {}",rdfServerGestion,idRepositoryGestion, baseUriGestion); - logger.info(" PUB EXTERNE : {} _ REPO : {} _ BASEURI : {}",rdfServerPublicationExt, idRepositoryPublicationExt, baseUriPublication); - logger.info(" PUB INTERNE : {} _ REPO : {}",rdfServerPublicationInt,idRepositoryPublicationInt); - - logger.info("DOCUMENT STORAGE : "); - - logger.info(" GESTION : {}", documentsStorageGestion); - logger.info(" PUB EXTERNE : {}", documentsStoragePublicationExt); - logger.info(" PUB INTERNE : {}", documentsStoragePublicationInt); - - - - logger.info("*********************** END CONFIG USED ***********************************"); - - - } - - public Config() { - //constructor for spring - } - /******************************************************/ /** INIT STATIC ***********************************/ /******************************************************/ @@ -261,25 +174,12 @@ private void init() { GenericQueries.setConfig(this); RdfUtils.setConfig(this); Sugoi.setConfig(this); - PublicationUtils.setConfig(this); } /******************************************************/ /** GETTERS ***********************************/ /******************************************************/ - public String getAppHost() { - return appHost; - } - - public String getEnv() { - return env; - } - - public boolean isRequiresSsl() { - return requiresSsl; - } - public String getLg1() { return lg1; } @@ -304,37 +204,6 @@ public String getBaseUriGestion() { return baseUriGestion; } - public String getRdfServerPublication() { - return rdfServerPublicationExt; - } - - public String getRepositoryIdPublication() { - return idRepositoryPublicationExt; - } - - public String getRdfServerPublicationInterne() { - return rdfServerPublicationInt; - } - - public String getRepositoryIdPublicationInterne() { - return idRepositoryPublicationInt; - } - - public String getBaseUriPublication() { - return baseUriPublication; - } - - public String getDefaultContributor() { - return defaultContributor; - } - - public String getDefaultMailSender() { - return defaultMailSender; - } - - public String getMaxLengthScopeNote() { - return maxLengthScopeNote; - } public String getConceptsGraph() { return baseGraph + conceptsGraph; @@ -344,14 +213,6 @@ public String getConceptsScheme() { return conceptsScheme; } - public String getConceptsBaseUri() { - return conceptsBaseUri; - } - - public String getCollectionsBaseUri() { - return collectionsBaseUri; - } - public String getClassifFamiliesGraph() { return baseGraph + classifFamiliesGraph; } @@ -360,30 +221,10 @@ public String getOperationsGraph() { return baseGraph + operationsGraph; } - public String getOperationsBaseUri() { - return operationsBaseUri; - } - - public String getOpSeriesBaseUri() { - return opSeriesBaseUri; - } - - public String getOpFamiliesBaseUri() { - return opFamiliesBaseUri; - } - - public String getDocumentationsBaseUri() { - return documentationsBaseUri; - } - public String getDocumentationsGraph() { return baseGraph + documentationsGraph; } - public String getDocumentsBaseUri() { - return documentsBaseUri; - } - public String getMsdGraph() { return baseGraph + msdGraph; } @@ -396,10 +237,6 @@ public String getDocumentationsGeoGraph() { return baseGraph + documentationsGeoGraph; } - public String getDocumentationsGeoBaseUri() { - return documentationsGeoBaseUri; - } - public String getDocumentationsTitlePrefixLg1() { return documentationsTitlePrefixLg1; } @@ -408,10 +245,6 @@ public String getDocumentationsTitlePrefixLg2() { return documentationsTitlePrefixLg2; } - public String getLinksBaseUri() { - return linksBaseUri; - } - public String getDocumentsGraph() { return baseGraph + documentsGraph; } @@ -444,26 +277,14 @@ public String getStructuresGraph() { return baseGraph + structuresGraph; } - public String getStructuresBaseUri() { - return structuresBaseUri; - } - public String getStructuresComponentsGraph() { return baseGraph + structuresComponentsGraph; } - public String getStructuresComponentsBaseUri() { - return structuresComponentsBaseUri; - } - public String getCodeListGraph() { return baseGraph + codeListsGraph; } - public String getCodeListBaseUri() { - return codeListsBaseUri; - } - public String getOrganizationsGraph() { return baseGraph + organizationsGraph; } @@ -476,18 +297,6 @@ public String getGeographyGraph() { return baseGraph + geographyGraph; } - public String getSpocServiceUrl() { - return spocServiceUrl; - } - - public String getSpocUser() { - return spocUser; - } - - public String getSpocPassword() { - return spocPassword; - } - public String getBrokerUrl() { return brokerUrl; } @@ -504,18 +313,6 @@ public String getLdapUrl() { return ldapUrl; } - public String getStampclaim() { - return stampClaim; - } - - public String getRoleclaim() { - return roleClaim; - } - - public String getIdclaim() { - return idClaim; - } - public String getSugoiUrl() { return sugoiUrl; } @@ -536,20 +333,15 @@ public String getSugoiRealm() { return sugoiRealm; } - public String getSugoiUi() { - return sugoiUi; - } - - public String getSwaggerHost() { - return swaggerHost; + public String getCodeListBaseUri() { + return this.codeListBaseUri; } - public String getSwaggerBasepath() { - return swaggerBasepath; + public String getLinksBaseUri() { + return this.linksBaseUri; } - public String getSwaggerUrl() { - return (requiresSsl ? "https" : "http") + "://" + swaggerHost + "/" + swaggerBasepath; + public String getDocumentsBaseUri() { + return this.documentsBaseUri; } - } \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/config/LogRequestFilter.java b/src/main/java/fr/insee/rmes/config/LogRequestFilter.java index 95dd5297d..11bb5b0cf 100644 --- a/src/main/java/fr/insee/rmes/config/LogRequestFilter.java +++ b/src/main/java/fr/insee/rmes/config/LogRequestFilter.java @@ -1,7 +1,8 @@ package fr.insee.rmes.config; -import javax.servlet.http.HttpServletRequest; - +import fr.insee.rmes.config.auth.UserProvider; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -9,42 +10,54 @@ import org.springframework.stereotype.Component; import org.springframework.web.filter.AbstractRequestLoggingFilter; -import fr.insee.rmes.config.auth.user.AuthorizeMethodDecider; -import fr.insee.rmes.config.auth.user.User; +import javax.servlet.http.HttpServletRequest; +import java.util.Optional; + +import static java.util.Optional.empty; +//TODO Test @Component public class LogRequestFilter extends AbstractRequestLoggingFilter { - private static final Logger log = LoggerFactory.getLogger(LogRequestFilter.class); - - @Autowired - private AuthorizeMethodDecider decider; - - @Override - protected void beforeRequest(HttpServletRequest request, String message) { - String logRequest = this.getFormatLogRequest(request, message, getIdUser()); - log.info("START {}", logRequest); - } - - @Override - protected void afterRequest(HttpServletRequest request, String message) { - String logRequest = this.getFormatLogRequest(request, message, getIdUser()); - log.info("END {}", logRequest); - } - - private String getFormatLogRequest(HttpServletRequest request, String message, String idep) { - StringBuilder sb = - new StringBuilder("From ").append(request.getServerName()).append(" by user ").append(idep) - .append(" call ").append(StringUtils.substringBetween(message, "[", "]")); - if (StringUtils.isNotEmpty(request.getQueryString())) { - sb.append(request.getQueryString()); + private static final Logger log = LoggerFactory.getLogger(LogRequestFilter.class); + + private final UserProvider userProvider; + + public LogRequestFilter(@Autowired UserProvider userProvider) { + this.userProvider = userProvider; } - return sb.toString(); - } - private String getIdUser() { - User currentUser = decider.getUser(); - return currentUser == null ? "No authentication needed" : currentUser.getId() + " " + currentUser.getStamp(); - } + @Override + protected void beforeRequest(HttpServletRequest request, String message) { + String logRequest = this.getFormatLogRequest(request, message, getIdUser()); + log.info("START {}", logRequest); + } + + @Override + protected void afterRequest(HttpServletRequest request, String message) { + String logRequest = this.getFormatLogRequest(request, message, getIdUser()); + log.info("END {}", logRequest); + } + + private String getFormatLogRequest(HttpServletRequest request, String message, String idep) { + StringBuilder sb = + new StringBuilder("From ").append(request.getServerName()).append(" by user ").append(idep) + .append(" call ").append(StringUtils.substringBetween(message, "[", "]")); + if (StringUtils.isNotEmpty(request.getQueryString())) { + sb.append(request.getQueryString()); + } + return sb.toString(); + } + + private String getIdUser() { + Optional currentUser; + try { + currentUser = userProvider.findUser(); + } catch (RmesException e) { + logger.error("while authenticating user", e); + currentUser = empty(); + } + return currentUser.map(user -> user.id() + " " + user.getStamp()).orElse("No authentication needed"); + } } diff --git a/src/main/java/fr/insee/rmes/config/PropertiesKeys.java b/src/main/java/fr/insee/rmes/config/PropertiesKeys.java new file mode 100644 index 000000000..438fcb864 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/PropertiesKeys.java @@ -0,0 +1,36 @@ +package fr.insee.rmes.config; + +public record PropertiesKeys() { + + public static final String CORS_ALLOWED_ORIGIN="fr.insee.rmes.bauhaus.cors.allowedOrigin"; + public static final String STRUCTURES_COMPONENTS_BASE_URI ="fr.insee.rmes.bauhaus.structures.components.baseURI"; + + public static final String CODE_LIST_BASE_URI ="fr.insee.rmes.bauhaus.codeList.baseURI"; + public static final String STRUCTURES_BASE_URI ="fr.insee.rmes.bauhaus.structures.baseURI"; + + public static final String DOCUMENTATIONS_GEO_BASE_URI ="fr.insee.rmes.bauhaus.documentation.geographie.baseURI"; + + public static final String LINKS_BASE_URI ="fr.insee.rmes.bauhaus.links.baseURI"; + + public static final String CONCEPTS_BASE_URI ="fr.insee.rmes.bauhaus.concepts.baseURI"; + + public static final String COLLECTIONS_BASE_URI ="fr.insee.rmes.bauhaus.collections.baseURI"; + + public static final String OPERATIONS_BASE_URI ="fr.insee.rmes.bauhaus.operations.baseURI"; + + + public static final String OP_FAMILIES_BASE_URI ="fr.insee.rmes.bauhaus.operations.families.baseURI"; + + public static final String OP_SERIES_BASE_URI ="fr.insee.rmes.bauhaus.operations.series.baseURI"; + + public static final String PRODUCTS_BASE_URI ="fr.insee.rmes.bauhaus.products.baseURI"; + + public static final String DOCUMENTATIONS_BASE_URI ="fr.insee.rmes.bauhaus.documentations.baseURI"; + + public static final String DOCUMENTS_BASE_URI ="fr.insee.rmes.bauhaus.documents.baseURI"; + + public static final String BASE_URI_GESTION ="fr.insee.rmes.bauhaus.sesame.gestion.baseURI"; + + public static final String BASE_URI_PUBLICATION ="fr.insee.rmes.bauhaus.sesame.publication.baseURI"; + +} diff --git a/src/main/java/fr/insee/rmes/config/PropertiesLogger.java b/src/main/java/fr/insee/rmes/config/PropertiesLogger.java new file mode 100644 index 000000000..da67f57d6 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/PropertiesLogger.java @@ -0,0 +1,177 @@ +package fr.insee.rmes.config; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.core.env.AbstractEnvironment; +import org.springframework.core.env.EnumerablePropertySource; +import org.springframework.core.env.Environment; +import org.springframework.core.env.PropertySource; +import org.springframework.lang.NonNull; + +import java.util.*; +import java.util.function.Supplier; + +public class PropertiesLogger implements ApplicationListener { + + private static final Logger log= LoggerFactory.getLogger(PropertiesLogger.class); + public static final String PROPERTY_KEY_FOR_PREFIXES = "fr.insee.properties.log.key.prefixes"; + public static final String PROPERTY_KEY_FOR_MORE_HIDDEN = "fr.insee.properties.log.key.hidden.more"; + public static final String PROPERTY_KEY_FOR_SOURCES_IGNORED = "fr.insee.properties.log.sources.ignored"; + public static final String PROPERTY_KEY_FOR_SOURCES_SELECT = "fr.insee.properties.log.key.select"; + private static final Set baseMotsCaches = Set.of("password", "pwd", "jeton", "token", "secret", "credential", "pw"); + private static final Set prefixesAffichesParDefaut= Set.of("fr.insee","logging","keycloak","spring","application","server","springdoc","management"); + private static final Set propertySourcesIgnoreesParDefaut = Set.of("systemProperties", "systemEnvironment"); + private static final PropertySelectorEnum PROPERTY_SELECTOR_PAR_DEFAUT = PropertySelectorEnum.PREFIX; + + + private final Collection propertySourceNames=new ArrayList<>(); + private Set hiddensProps; + private Set ignoredPropertySources; + private PropertySelector propertySelector; + private static Set prefixForSelectedProps; + + @Override + public void onApplicationEvent(@NonNull ApplicationEnvironmentPreparedEvent event) { + Environment environment=event.getEnvironment(); + + var props= new StringBuilder(); + this.hiddensProps = getMoreHiddenPropsFromPropertyAndMerge(environment); + prefixForSelectedProps = environment.getProperty(PROPERTY_KEY_FOR_PREFIXES, Set.class, prefixesAffichesParDefaut); + this.ignoredPropertySources = environment.getProperty(PROPERTY_KEY_FOR_SOURCES_IGNORED, Set.class, propertySourcesIgnoreesParDefaut); + var propertySelectorType=this.getSelectorFromProperty(environment.getProperty(PROPERTY_KEY_FOR_SOURCES_SELECT)) + .orElse(PROPERTY_SELECTOR_PAR_DEFAUT); + debug(()->"Logging "+propertySelectorType.forLogging()); + this.propertySelector=propertySelectorType.propertySelector(); + + ((AbstractEnvironment) environment).getPropertySources().stream() + .filter(this::isEnumerable) + .filter(this::sourceWillBeProcessed) + .map(this::rememberPropertySourceNameThenCast) + .map(EnumerablePropertySource::getPropertyNames) + .flatMap(Arrays::stream) + .distinct() + .filter(Objects::nonNull) + .filter(this::filterFromPropertySelector) + .forEach(key-> props.append(key).append(" = ") + .append(resoutValeurAvecMasquePwd(key, environment)) + .append(System.lineSeparator())); + props.append("============================================================================"); + props.insert(0, """ + =============================================================================================== + Valeurs des properties pour : + %s + =============================================================================================== + """.formatted(this.propertySourceNames.stream().reduce("",(l, e)->l+System.lineSeparator()+"- "+e ))); + info(props::toString); + + } + + private static Set getMoreHiddenPropsFromPropertyAndMerge(Environment environment) { + Set moreProps = environment.getProperty(PROPERTY_KEY_FOR_MORE_HIDDEN, Set.class); + var retour = baseMotsCaches; + if (moreProps != null){ + retour=new HashSet(moreProps); + retour.addAll(baseMotsCaches); + } + return retour; + } + + private Optional getSelectorFromProperty(String property) { + if(property!=null){ + try{ + return Optional.of(PropertySelectorEnum.valueOf(property)); + }catch (IllegalArgumentException ie){ + trace(()->"Impossible de convertir "+property+" en une constante de PropertySelectorEnum. Le PropertySelector par défaut sera utilisé."); + } + } + return Optional.empty(); + } + + private boolean filterFromPropertySelector(@NonNull String s) { + if (! this.propertySelector.filter(s)){ + debug(()->s+ " ne commence pas par un des prefix retenus pour être loguée"); + return false; + } + return true; + } + + private boolean sourceWillBeProcessed(PropertySource> propertySource) { + + if (ignoredPropertySources.contains(propertySource.getName())){ + debug(()->propertySource+ " sera ignorée"); + return false; + } + return true; + } + + private EnumerablePropertySource> rememberPropertySourceNameThenCast(PropertySource> propertySource) { + this.propertySourceNames.add(propertySource.getName()); + return (EnumerablePropertySource>) propertySource; + } + + private boolean isEnumerable(PropertySource> propertySource) { + if (! (propertySource instanceof EnumerablePropertySource)){ + debug(()->propertySource+ " n'est pas EnumerablePropertySource : impossible à lister"); + return false; + } + return true; + } + + private void debug(Supplier messageForDebug) { + if (log.isDebugEnabled()){ + log.debug(messageForDebug.get()); + } + } + + private void trace(Supplier messageForDebug) { + if (log.isTraceEnabled()){ + log.trace(messageForDebug.get()); + } + } + + private void info(Supplier messageForDebug) { + if (log.isInfoEnabled()){ + log.info(messageForDebug.get()); + } + } + + private Object resoutValeurAvecMasquePwd(String key, Environment environment) { + if (hiddensProps.stream().anyMatch(key::contains)) { + return "******"; + } + return environment.getProperty(key); + + } + + + @FunctionalInterface + private interface PropertySelector { + boolean filter(String s); + } + + private enum PropertySelectorEnum { + ALL(s->true, ()->"all properties"), + NONE(s->false, ()->"no properties"), + PREFIX(k->prefixForSelectedProps.stream().anyMatch(k::startsWith), () -> "properties starting with "+ prefixForSelectedProps); + + private final PropertySelector propertySelector; + private final Supplier logString; + + PropertySelectorEnum(PropertySelector propertySelector, Supplier logString) { + this.propertySelector=propertySelector; + this.logString=logString; + } + + public PropertySelector propertySelector() { + return propertySelector; + } + + public String forLogging(){ + return logString.get(); + } + + } +} + diff --git a/src/main/java/fr/insee/rmes/config/auth/AuthType.java b/src/main/java/fr/insee/rmes/config/auth/AuthType.java index 1b2b3d4f8..d627bd8ae 100644 --- a/src/main/java/fr/insee/rmes/config/auth/AuthType.java +++ b/src/main/java/fr/insee/rmes/config/auth/AuthType.java @@ -1,11 +1,9 @@ package fr.insee.rmes.config.auth; -import fr.insee.rmes.config.Config; - public class AuthType { - public static String getAuthType(Config config) { - if (config.getEnv().equals("pre-prod") || config.getEnv().equals("prod") || config.getEnv().equals("PROD")) return "OpenIDConnectAuth"; + public static String getAuthType(String env) { + if (env.equals("pre-prod") || env.equals("prod") || env.equals("PROD")) return "OpenIDConnectAuth"; else return "NoAuthImpl"; } diff --git a/src/main/java/fr/insee/rmes/config/auth/UserProvider.java b/src/main/java/fr/insee/rmes/config/auth/UserProvider.java new file mode 100644 index 000000000..567a55c3c --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/UserProvider.java @@ -0,0 +1,29 @@ +package fr.insee.rmes.config.auth; + +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +import static java.util.Optional.empty; + + +public interface UserProvider { + + Logger logger = LoggerFactory.getLogger(UserProvider.class); + + Optional findUser() throws RmesException; + + default User findUserDefaultToEmpty() { + Optional currentUser; + try { + currentUser = findUser(); + } catch (RmesException e) { + logger.info("while authenticating user => default to empty", e); + currentUser= empty(); + } + return currentUser.orElse(User.EMPTY_USER); + } +} diff --git a/src/main/java/fr/insee/rmes/config/auth/UserProviderFromSecurityContext.java b/src/main/java/fr/insee/rmes/config/auth/UserProviderFromSecurityContext.java new file mode 100644 index 000000000..fc7cfde80 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/UserProviderFromSecurityContext.java @@ -0,0 +1,20 @@ +package fr.insee.rmes.config.auth; + +import fr.insee.rmes.config.auth.security.UserDecoder; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +public record UserProviderFromSecurityContext(UserDecoder userDecoder) implements UserProvider{ + + @Override + public Optional findUser() throws RmesException { + return this.userDecoder.fromPrincipal(SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + } + + +} diff --git a/src/main/java/fr/insee/rmes/config/auth/roles/Roles.java b/src/main/java/fr/insee/rmes/config/auth/roles/Roles.java index d197d0f40..965069ff5 100644 --- a/src/main/java/fr/insee/rmes/config/auth/roles/Roles.java +++ b/src/main/java/fr/insee/rmes/config/auth/roles/Roles.java @@ -8,7 +8,6 @@ private Roles() { public static final String ADMIN = "Administrateur_RMESGNCS"; - public static final String USER = "Utilisateur_RMESGNCS"; /* Concepts */ public static final String CONCEPTS_CONTRIBUTOR = "Gestionnaire_ensemble_concepts_RMESGNCS"; diff --git a/src/main/java/fr/insee/rmes/config/auth/security/CommonSecurityConfiguration.java b/src/main/java/fr/insee/rmes/config/auth/security/CommonSecurityConfiguration.java new file mode 100644 index 000000000..a7dd9bba3 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/security/CommonSecurityConfiguration.java @@ -0,0 +1,60 @@ +package fr.insee.rmes.config.auth.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; +import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import java.util.List; +import java.util.Optional; + +import static fr.insee.rmes.config.PropertiesKeys.CORS_ALLOWED_ORIGIN; + +@Configuration +public class CommonSecurityConfiguration { + + private static final Logger logger= LoggerFactory.getLogger(CommonSecurityConfiguration.class); + + public static final String DEFAULT_ROLE_PREFIX = null ; + private final Optional allowedOrigin ; + + public CommonSecurityConfiguration(@Value("${"+CORS_ALLOWED_ORIGIN+"}") Optional allowedOrigin){ + this.allowedOrigin=allowedOrigin; + } + + + @Bean + public CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration configuration = new CorsConfiguration(); + logger.info("Allowed origins : {}", allowedOrigin); + configuration.setAllowedOrigins(List.of(allowedOrigin.orElse("*"))); + configuration.setAllowedMethods(List.of("*")); + configuration.setAllowedHeaders(List.of("*")); + UrlBasedCorsConfigurationSource source = new + UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) + public static class CustomGlobalMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { + + @Override + protected MethodSecurityExpressionHandler createExpressionHandler() { + logger.trace("Initializing GlobalMethodSecurityConfiguration with DefaultRolePrefix = {}",DEFAULT_ROLE_PREFIX); + var expressionHandler = new DefaultMethodSecurityExpressionHandler(); + expressionHandler.setDefaultRolePrefix(DEFAULT_ROLE_PREFIX); + return expressionHandler; + } + + } + +} diff --git a/src/main/java/fr/insee/rmes/config/auth/security/DefaultSecurityContext.java b/src/main/java/fr/insee/rmes/config/auth/security/DefaultSecurityContext.java index 0c78d23fb..f6951e218 100644 --- a/src/main/java/fr/insee/rmes/config/auth/security/DefaultSecurityContext.java +++ b/src/main/java/fr/insee/rmes/config/auth/security/DefaultSecurityContext.java @@ -1,72 +1,51 @@ package fr.insee.rmes.config.auth.security; -import static org.springframework.security.config.Customizer.withDefaults; - -import java.util.List; -import java.util.Optional; - +import fr.insee.rmes.config.auth.user.User; 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.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.security.web.SecurityFilterChain; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.config.auth.user.User; -import fr.insee.rmes.config.auth.user.UserProvider; +import java.util.Optional; + +import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled=false, prePostEnabled = true) -@ConditionalOnMissingBean(OpenIDConnectSecurityContext.class) -public class DefaultSecurityContext extends WebSecurityConfigurerAdapter { +@ConditionalOnExpression("!'PROD'.equalsIgnoreCase('${fr.insee.rmes.bauhaus.env}')") +public class DefaultSecurityContext { private static final Logger logger = LoggerFactory.getLogger(DefaultSecurityContext.class); + private final boolean requiresSsl; - @Autowired - Config config; - - @Value("${fr.insee.rmes.bauhaus.cors.allowedOrigin}") - private Optional allowedOrigin; - - @Override - protected void configure(HttpSecurity http) throws Exception { + public DefaultSecurityContext(@Value("${fr.insee.rmes.bauhaus.force.ssl}") boolean requiresSsl){ + this.requiresSsl=requiresSsl; + } + + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf().disable(); http.cors(withDefaults()) - .authorizeRequests().anyRequest().permitAll(); - if (config.isRequiresSsl()) { + .authorizeRequests().anyRequest().permitAll(); + if (requiresSsl) { http.antMatcher("/**").requiresChannel().anyRequest().requiresSecure(); } - + logger.info("Default authentication activated - no auth "); + + return http.build(); + } - - @Bean - public CorsConfigurationSource corsConfigurationSource() { - CorsConfiguration configuration = new CorsConfiguration(); - logger.info("Allowed origins : {}", allowedOrigin); - String ao = allowedOrigin.isPresent() ? allowedOrigin.get() : allowedOrigin.orElse("*"); - configuration.setAllowedOrigins(List.of(ao)); - configuration.setAllowedMethods(List.of("*")); - configuration.setAllowedHeaders(List.of("*")); - UrlBasedCorsConfigurationSource source = new - UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", configuration); - return source; - } - + @Bean - public UserProvider getUserProvider() { - return auth -> new User(); + public UserDecoder getUserProvider() { + return principal -> Optional.of(User.FAKE_USER); } } \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContext.java b/src/main/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContext.java index 6a2ca0ee3..7f99b8a17 100644 --- a/src/main/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContext.java +++ b/src/main/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContext.java @@ -1,108 +1,136 @@ package fr.insee.rmes.config.auth.security; -import static org.springframework.security.config.Customizer.withDefaults; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; - +import com.nimbusds.jose.shaded.json.JSONObject; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; 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.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.json.JsonParser; -import org.springframework.boot.json.JsonParserFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.http.HttpStatus; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.config.auth.user.User; -import fr.insee.rmes.config.auth.user.UserProvider; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static fr.insee.rmes.config.auth.security.CommonSecurityConfiguration.DEFAULT_ROLE_PREFIX; +import static java.util.Optional.*; +import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled = true) @ConditionalOnExpression("'PROD'.equalsIgnoreCase('${fr.insee.rmes.bauhaus.env}')") -public class OpenIDConnectSecurityContext extends WebSecurityConfigurerAdapter { - - private static final Logger logger = LoggerFactory.getLogger(OpenIDConnectSecurityContext.class); - - @Value("${fr.insee.rmes.bauhaus.cors.allowedOrigin}") - private Optional allowedOrigin; - - @Autowired - Config config; - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement().disable(); - - http.cors(withDefaults()) - .authorizeRequests() - .antMatchers("/init","/stamps","/disseminationStatus","/roles","/agents").permitAll() //PublicResources - .antMatchers("/healthcheck").permitAll() - .antMatchers("/swagger-ui/*").permitAll() - .antMatchers("/v3/api-docs/swagger-config", "/v3/api-docs").permitAll() - .antMatchers("/openapi.json").permitAll() - .antMatchers("/documents/document/*/file").permitAll() - .antMatchers("/operations/operation/codebook").permitAll() - .antMatchers(HttpMethod.OPTIONS).permitAll() - .anyRequest().authenticated() - .and() - .oauth2ResourceServer() - .jwt(); - if (config.isRequiresSsl()) - http.antMatcher("/**").requiresChannel().anyRequest().requiresSecure(); - - logger.info("OpenID authentication activated "); - - } - - - @Bean - public UserProvider getUserProvider() { - return auth -> { - if ("anonymousUser".equals(auth.getPrincipal())) return null; //init request, or request without authentication - final Jwt jwt = (Jwt) auth.getPrincipal(); - Map claims = jwt.getClaims(); - JsonParser parser = JsonParserFactory.getJsonParser(); - Map listeRoles = parser.parseMap(claims.get(config.getRoleclaim()).toString()); - List roles = Arrays.asList( - listeRoles.get("roles").toString() - .substring(1,listeRoles.get("roles").toString().length() - 1) //remove [] - .replace(" ", "") //remove all spaces - .split(",") - ); - String stamp = claims.get(config.getStampclaim()).toString(); - String id = claims.get(config.getIdclaim()).toString(); - logger.debug("Current User is {}, {} with roles {}",id,stamp,roles); - return new User(id,roles, stamp); - }; - } - - @Bean - public CorsConfigurationSource corsConfigurationSource() { - CorsConfiguration configuration = new CorsConfiguration(); - logger.info("Allowed origins : {}", allowedOrigin); - String ao = allowedOrigin.isPresent() ? allowedOrigin.get() : allowedOrigin.orElse("*"); - configuration.setAllowedOrigins(List.of(ao)); - configuration.setAllowedMethods(List.of("*")); - configuration.setAllowedHeaders(List.of("*")); - UrlBasedCorsConfigurationSource source = new - UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", configuration); - return source; - } - +public class OpenIDConnectSecurityContext { + + private static final Logger logger = LoggerFactory.getLogger(OpenIDConnectSecurityContext.class); + + public static final String TIMBRE_ANONYME = "bauhausGuest_STAMP"; + private static final Stream EMPTY_ROLES = Stream.empty(); + public static final String LOG_INFO_DEFAULT_STAMP = "User {} uses default stamp"; + public static final String[] PUBLIC_RESOURCES_ANT_PATTERNS = {"/init", "/stamps", "/disseminationStatus", "/roles"}; + + private final String stampClaim; + + private final String roleClaim; + + private final String idClaim; + + private final boolean requiresSsl; + private final String keyForRolesInRoleClaim; + + public OpenIDConnectSecurityContext(@Value("${jwt.stamp-claim}") String stampClaim, @Value("${jwt.role-claim}") String roleClaim, @Value("${jwt.id-claim}") String idClaim, @Value("${fr.insee.rmes.bauhaus.force.ssl}") boolean requiresSsl, @Value("${jwt.role-claim.roles}") String keyForRolesInRoleClaim) { + this.stampClaim = stampClaim; + this.roleClaim = roleClaim; + this.idClaim = idClaim; + this.requiresSsl = requiresSsl; + this.keyForRolesInRoleClaim = keyForRolesInRoleClaim; + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.sessionManagement().disable() + .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) + .cors(withDefaults()) + .csrf(AbstractHttpConfigurer::disable) + .authorizeRequests() + .antMatchers(PUBLIC_RESOURCES_ANT_PATTERNS).permitAll() //PublicResources + .antMatchers("/healthcheck").permitAll() + .antMatchers("/swagger-ui/*").permitAll() + .antMatchers("/v3/api-docs/swagger-config", "/v3/api-docs").permitAll() + .antMatchers("/openapi.json").permitAll() + .antMatchers("/documents/document/*/file").permitAll() + .antMatchers("/operations/operation/codebook").permitAll() + .antMatchers(HttpMethod.OPTIONS).permitAll() + .anyRequest().authenticated() + .expressionHandler(webSecurityExpressionHandler()); + + if (requiresSsl) { + http.antMatcher("/**").requiresChannel().anyRequest().requiresSecure(); + } + logger.info("OpenID authentication activated "); + + return http.build(); + } + + private DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() { + var expressionHandler = new DefaultWebSecurityExpressionHandler(); + expressionHandler.setDefaultRolePrefix(DEFAULT_ROLE_PREFIX); + return expressionHandler; + } + @Bean + public JwtAuthenticationConverter jwtAuthenticationConverter() { + var jwtAuthenticationConverter = new JwtAuthenticationConverter(); + jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(this::extractAuthoritiesFromJwt); + jwtAuthenticationConverter.setPrincipalClaimName(idClaim); + return jwtAuthenticationConverter; + } + + @Bean + public UserDecoder userDecoder() { + return principal -> "anonymousUser".equals(principal) ? + empty() : + of(buildUserFromToken(((Jwt) principal).getClaims())); + } + + public User buildUserFromToken(Map claims) throws RmesException { + if (claims.isEmpty()) { + throw new RmesException(HttpStatus.UNAUTHORIZED, "Must be authentified", "empty claims for JWT"); + } + var id = (String) claims.get(idClaim); + var stamp = ofNullable((String) claims.get(stampClaim)); + if (stamp.isEmpty()) { + logger.info(LOG_INFO_DEFAULT_STAMP, id); + stamp = of(TIMBRE_ANONYME); + } + var roles=extractRoles(claims).toList(); + + logger.debug("Current User is {}, {} with roles {}", id, stamp, roles); + return new User(id, roles, stamp.get()); + } + + private Collection extractAuthoritiesFromJwt(Jwt jwt){ + return extractRoles(jwt.getClaims()).map(SimpleGrantedAuthority::new) + .map(a->(GrantedAuthority)a).toList(); + } + + private Stream extractRoles(Map claims){ + var objectForRoles = (JSONObject) claims.get(roleClaim); + return objectForRoles == null ? EMPTY_ROLES : ((List) (objectForRoles.get(keyForRolesInRoleClaim))).stream(); + } + + } diff --git a/src/main/java/fr/insee/rmes/config/auth/security/UserDecoder.java b/src/main/java/fr/insee/rmes/config/auth/security/UserDecoder.java new file mode 100644 index 000000000..85f0c2e56 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/security/UserDecoder.java @@ -0,0 +1,11 @@ +package fr.insee.rmes.config.auth.security; + +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; + +import java.util.Optional; + +public interface UserDecoder { + + Optional fromPrincipal(Object principal) throws RmesException; +} diff --git a/src/main/java/fr/insee/rmes/config/auth/security/restrictions/StampsRestrictionsService.java b/src/main/java/fr/insee/rmes/config/auth/security/restrictions/StampsRestrictionsService.java index 3695439a1..d7d456f25 100644 --- a/src/main/java/fr/insee/rmes/config/auth/security/restrictions/StampsRestrictionsService.java +++ b/src/main/java/fr/insee/rmes/config/auth/security/restrictions/StampsRestrictionsService.java @@ -1,12 +1,9 @@ package fr.insee.rmes.config.auth.security.restrictions; -import java.util.List; - -import com.fasterxml.jackson.core.JsonProcessingException; +import fr.insee.rmes.exceptions.RmesException; import org.eclipse.rdf4j.model.IRI; -import fr.insee.rmes.config.auth.user.User; -import fr.insee.rmes.exceptions.RmesException; +import java.util.List; public interface StampsRestrictionsService { @@ -14,11 +11,6 @@ public interface StampsRestrictionsService { * USER */ - User getUser() throws RmesException; - - void setFakeUser(String user) throws JsonProcessingException; - - /* * CONCEPTS AND COLLECTIONS */ @@ -60,9 +52,6 @@ public interface StampsRestrictionsService { boolean canCreateOperation(IRI seriesURI) throws RmesException; boolean canModifyOperation(IRI seriesURI) throws RmesException; - - boolean canValidateOperation(IRI seriesURI) throws RmesException; - /* @@ -74,8 +63,6 @@ public interface StampsRestrictionsService { boolean canValidateSeries(IRI uri) throws RmesException; - boolean isSeriesManager(IRI uri) throws RmesException; - /* * FAMILIES (OPERATION MODULE) */ diff --git a/src/main/java/fr/insee/rmes/config/auth/user/AuthorizeMethodDecider.java b/src/main/java/fr/insee/rmes/config/auth/user/AuthorizeMethodDecider.java index 764aeece6..90e0243de 100644 --- a/src/main/java/fr/insee/rmes/config/auth/user/AuthorizeMethodDecider.java +++ b/src/main/java/fr/insee/rmes/config/auth/user/AuthorizeMethodDecider.java @@ -1,140 +1,55 @@ package fr.insee.rmes.config.auth.user; -import org.json.JSONArray; +import fr.insee.rmes.config.auth.roles.Roles; 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; +import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Component; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.config.auth.roles.Roles; - @Component("AuthorizeMethodDecider") -public class AuthorizeMethodDecider { +public record AuthorizeMethodDecider(PreAuthorizeChecker preAuthorizeChecker) { private static final Logger logger = LoggerFactory.getLogger(AuthorizeMethodDecider.class); - private User fakeUser; - - @Autowired - private UserProvider userProvider; - - @Autowired - Config config; - - public User getUser() { - if (config.getEnv().equals("pre-prod") || config.getEnv().equals("prod") || config.getEnv().equals("PROD")) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - User currentUser = userProvider.getUser(authentication); - logger.debug("Current user has stamp {}", currentUser == null ? "" : currentUser.getStamp()); - return currentUser; - } - return dvOrQfUser(); + public boolean isAdmin() { + return checkIfHasRole(Roles.ADMIN); } - private User dvOrQfUser() { - if (this.fakeUser != null) { - return this.fakeUser; + private boolean checkIfHasRole(String roleToCheck) { + logger.debug("Check if user is {}", roleToCheck); + try { + this.preAuthorizeChecker.hasRole(roleToCheck); + return true; + } catch (AccessDeniedException denied) { + return false; } - - JSONArray roles = new JSONArray(); - roles.put("ROLE_offline_access"); - roles.put("Administrateur_RMESGNCS"); - roles.put("ROLE_uma_authorization"); - return new User("fakeUser",roles, "fakeStampForDvAndQf"); } - public boolean isAdmin() { - User user = getUser(); - return isAdmin(user); - } - - public boolean isAdmin(User user) { - logger.info("Check if user is admin"); - return hasRole(user,Roles.ADMIN); - } - public boolean isIndicatorContributor() { - User user = getUser(); - return isIndicatorContributor(user); + return checkIfHasRole(Roles.INDICATOR_CONTRIBUTOR); } - - public boolean isIndicatorContributor(User user) { - logger.info("Check if user is indicator's contributor"); - return hasRole(user,Roles.INDICATOR_CONTRIBUTOR); - } - + public boolean isConceptsContributor() { - User user = getUser(); - return isConceptsContributor(user); - } - public boolean isConceptsContributor(User user) { - logger.info("Check if user is concepts' contributor"); - return hasRole(user,Roles.CONCEPTS_CONTRIBUTOR); + return checkIfHasRole(Roles.CONCEPTS_CONTRIBUTOR); } - public boolean isConceptContributor() { - User user = getUser(); - return isConceptContributor(user); - } - public boolean isConceptContributor(User user) { - logger.info("Check if user is concept's contributor"); - return hasRole(user,Roles.CONCEPT_CONTRIBUTOR); - } - - public boolean isConceptCreator() { - User user = getUser(); - return isConceptCreator(user); + public boolean isConceptContributor() { + return checkIfHasRole(Roles.CONCEPT_CONTRIBUTOR); } - public boolean isConceptCreator(User user) { - logger.info("Check if user is concept's creator"); - return hasRole(user,Roles.CONCEPT_CREATOR); - } - public boolean isSeriesContributor() { - User user = getUser(); - return isSeriesContributor(user); + public boolean isConceptCreator() { + return checkIfHasRole(Roles.CONCEPT_CREATOR); } - public boolean isSeriesContributor(User user) { - logger.info("Check if user is series' contributor"); - return hasRole(user,Roles.SERIES_CONTRIBUTOR); + public boolean isSeriesContributor() { + return checkIfHasRole(Roles.SERIES_CONTRIBUTOR); } public boolean isCnis() { - User user = getUser(); - return isCnis(user); - } - - public boolean isCnis(User user) { - logger.info("Check if user is CNIS' contributor"); - return hasRole(user,Roles.CNIS); - } - - public boolean isCollectionCreator() { - User user = getUser(); - return isCollectionCreator(user); - } - - private boolean isCollectionCreator(User user) { - logger.info("Check if user is collection's creator"); - return hasRole(user,Roles.COLLECTION_CREATOR); - } - - private boolean hasRole(User user, String role) { - Boolean hasRole = false; - JSONArray roles = user.getRoles(); - for (int i = 0; i < roles.length(); i++) { - if (roles.getString(i).equals(role)||roles.getString(i).equals(Roles.SPRING_PREFIX + role)) { - hasRole = true; - } - } - return hasRole; + return checkIfHasRole(Roles.CNIS); } diff --git a/src/main/java/fr/insee/rmes/config/auth/user/PreAuthorizeChecker.java b/src/main/java/fr/insee/rmes/config/auth/user/PreAuthorizeChecker.java new file mode 100644 index 000000000..68b68399c --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/user/PreAuthorizeChecker.java @@ -0,0 +1,12 @@ +package fr.insee.rmes.config.auth.user; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Component; + +@Component +public class PreAuthorizeChecker { + @PreAuthorize("hasRole(#ignoredTestedRole)") + public void hasRole(String ignoredTestedRole) { + //empty method to check that user has role `testedRole` with @PreAuthorize + } +} diff --git a/src/main/java/fr/insee/rmes/config/auth/user/Stamp.java b/src/main/java/fr/insee/rmes/config/auth/user/Stamp.java new file mode 100644 index 000000000..5d65267f1 --- /dev/null +++ b/src/main/java/fr/insee/rmes/config/auth/user/Stamp.java @@ -0,0 +1,4 @@ +package fr.insee.rmes.config.auth.user; + +public record Stamp(String stamp) { +} diff --git a/src/main/java/fr/insee/rmes/config/auth/user/User.java b/src/main/java/fr/insee/rmes/config/auth/user/User.java index 5565adc36..87cd97e3f 100644 --- a/src/main/java/fr/insee/rmes/config/auth/user/User.java +++ b/src/main/java/fr/insee/rmes/config/auth/user/User.java @@ -1,59 +1,25 @@ package fr.insee.rmes.config.auth.user; -import java.util.Collection; import java.util.List; -import org.json.JSONArray; -import org.springframework.security.core.GrantedAuthority; +public record User(String id, List roles, Stamp stamp) { -public class User { - - private JSONArray roles; - private String stamp = ""; - - private String id; - - private Collection authorities; - - public User() { - super(); - } - - public User(String id, JSONArray roles, String stamp) { - this.id=id; - this.roles = roles; - this.stamp = stamp; - } - - public User(String id, List roles, String stamp) { - this.id=id; - this.roles = new JSONArray(roles); - this.stamp = stamp; - } - - public JSONArray getRoles() { - return roles; - } - public void setRoles(JSONArray roles) { - this.roles = roles; - } - public String getStamp() { - return stamp; - } - public void setStamp(String stamp) { - this.stamp = stamp; + public static final User FAKE_USER=new User("fakeUser",List.of("ROLE_offline_access", "Administrateur_RMESGNCS", "ROLE_uma_authorization"), "fakeStampForDvAndQf"); + public static final User EMPTY_USER = new User(); + + private User() { + this(null, List.of(), ""); } - public Collection getAuthorities() { - return authorities; - } - public String getId() { - return id; + public User(String id, List roles, String stamp){ + this(id, roles, new Stamp(stamp)); } - public void setId(String id) { - this.id = id; + public boolean hasRole(String role) { + return roles.contains(role); } - + public String getStamp(){ + return stamp.stamp(); + } } diff --git a/src/main/java/fr/insee/rmes/config/auth/user/UserProvider.java b/src/main/java/fr/insee/rmes/config/auth/user/UserProvider.java deleted file mode 100644 index 46b461ae9..000000000 --- a/src/main/java/fr/insee/rmes/config/auth/user/UserProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -package fr.insee.rmes.config.auth.user; - -import org.springframework.security.core.Authentication; - -@FunctionalInterface -public interface UserProvider { - - User getUser(Authentication authentication); - -} \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/config/freemarker/FreemarkerConfig.java b/src/main/java/fr/insee/rmes/config/freemarker/FreemarkerConfig.java index 570543e73..25201a2f2 100644 --- a/src/main/java/fr/insee/rmes/config/freemarker/FreemarkerConfig.java +++ b/src/main/java/fr/insee/rmes/config/freemarker/FreemarkerConfig.java @@ -1,23 +1,22 @@ package fr.insee.rmes.config.freemarker; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Locale; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - import freemarker.cache.FileTemplateLoader; import freemarker.cache.MultiTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateExceptionHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Locale; public class FreemarkerConfig { - static final Logger logger = LogManager.getLogger(FreemarkerConfig.class); + static final Logger logger = LoggerFactory.getLogger(FreemarkerConfig.class); static Configuration cfg; diff --git a/src/main/java/fr/insee/rmes/config/keycloak/KeycloakServer.java b/src/main/java/fr/insee/rmes/config/keycloak/KeycloakServer.java index c7a2f3108..ef054aa87 100644 --- a/src/main/java/fr/insee/rmes/config/keycloak/KeycloakServer.java +++ b/src/main/java/fr/insee/rmes/config/keycloak/KeycloakServer.java @@ -1,7 +1,5 @@ package fr.insee.rmes.config.keycloak; -import java.net.URL; - public class KeycloakServer { private String secret; diff --git a/src/main/java/fr/insee/rmes/config/keycloak/ServerZone.java b/src/main/java/fr/insee/rmes/config/keycloak/ServerZone.java index 21ac5b1d5..e3a500fca 100644 --- a/src/main/java/fr/insee/rmes/config/keycloak/ServerZone.java +++ b/src/main/java/fr/insee/rmes/config/keycloak/ServerZone.java @@ -1,7 +1,7 @@ package fr.insee.rmes.config.keycloak; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; @@ -9,7 +9,7 @@ public class ServerZone { private Zone zone; - static final Logger logger = LogManager.getLogger(ServerZone.class); + static final Logger logger = LoggerFactory.getLogger(ServerZone.class); public ServerZone(){ } diff --git a/src/main/java/fr/insee/rmes/config/swagger/OpenApiConfiguration.java b/src/main/java/fr/insee/rmes/config/swagger/OpenApiConfiguration.java index fe877cd99..d548b3b15 100644 --- a/src/main/java/fr/insee/rmes/config/swagger/OpenApiConfiguration.java +++ b/src/main/java/fr/insee/rmes/config/swagger/OpenApiConfiguration.java @@ -1,21 +1,16 @@ package fr.insee.rmes.config.swagger; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; - -import fr.insee.rmes.config.Config; import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; import io.swagger.v3.oas.annotations.security.SecurityScheme; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.servers.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; -//@("/") -@DependsOn("AppContext") @Configuration @SecurityScheme(//add Authorize button in swagger name = "bearerAuth", @@ -25,20 +20,15 @@ ) public class OpenApiConfiguration { - private static final Logger logger = LogManager.getLogger(OpenApiConfiguration.class); - - @Value("${fr.insee.rmes.bauhaus.version}") - private String projectVersion; + private static final Logger logger = LoggerFactory.getLogger(OpenApiConfiguration.class); + @Bean - public OpenAPI customOpenAPI(Config config) { + public OpenAPI customOpenAPI(@Value("${fr.insee.rmes.bauhaus.api.ssl}") boolean swaggerUseSSL, @Value("${fr.insee.rmes.bauhaus.api.host}") String swaggerHost, @Value("${fr.insee.rmes.bauhaus.api.basepath}") String swaggerBasepath, @Value("${fr.insee.rmes.bauhaus.version}") String projectVersion) { Server server = new Server(); - server.setUrl(config.getSwaggerUrl()); - logger.info("______________________________________________________________________"); - logger.info("____________________SWAGGER HOST : {}_________________________________________________", config.getSwaggerHost()); - logger.info("____________________SWAGGER BASEPATH : {} _________________________________________________", config.getSwaggerBasepath()); - logger.info("____________________SWAGGER CONFIG : {} _________________________________________________", config.getSwaggerUrl()); - logger.info("______________________________________________________________________"); + var swaggerUrl = (swaggerUseSSL ? "https" : "http")+"://"+ swaggerHost + "/" + swaggerBasepath; + server.setUrl(swaggerUrl); + logger.info("____________________SWAGGER CONFIG : {} _________________________________________________", swaggerUrl); return new OpenAPI() .addServersItem(server) .info(new Info() diff --git a/src/main/java/fr/insee/rmes/config/swagger/model/application/Roles.java b/src/main/java/fr/insee/rmes/config/swagger/model/application/Roles.java deleted file mode 100644 index aa97ffb17..000000000 --- a/src/main/java/fr/insee/rmes/config/swagger/model/application/Roles.java +++ /dev/null @@ -1,16 +0,0 @@ -package fr.insee.rmes.config.swagger.model.application; - -import io.swagger.v3.oas.annotations.media.Schema; - -public class Roles { - - @Schema(description = "Id", required = true, example = "Id of role") - public String id; - - @Schema(description = "Label", required = true, example = "Role label") - public String label; - - @Schema(description = "Persons", required = true) - public Persons persons; - -} diff --git a/src/main/java/fr/insee/rmes/config/swagger/model/code_list/CodeList.java b/src/main/java/fr/insee/rmes/config/swagger/model/code_list/CodeList.java index 8c33ef026..356ab5c91 100644 --- a/src/main/java/fr/insee/rmes/config/swagger/model/code_list/CodeList.java +++ b/src/main/java/fr/insee/rmes/config/swagger/model/code_list/CodeList.java @@ -1,9 +1,9 @@ package fr.insee.rmes.config.swagger.model.code_list; -import java.util.List; - import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; + public class CodeList { @Schema(description="Code list's notation") diff --git a/src/main/java/fr/insee/rmes/exceptions/BauhausErrorListener.java b/src/main/java/fr/insee/rmes/exceptions/BauhausErrorListener.java index 7f01e071a..74910ffcb 100644 --- a/src/main/java/fr/insee/rmes/exceptions/BauhausErrorListener.java +++ b/src/main/java/fr/insee/rmes/exceptions/BauhausErrorListener.java @@ -1,14 +1,14 @@ package fr.insee.rmes.exceptions; -import javax.xml.transform.ErrorListener; -import javax.xml.transform.TransformerException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; +import javax.xml.transform.ErrorListener; +import javax.xml.transform.TransformerException; + public class BauhausErrorListener implements ErrorListener { private static final Marker fatal = MarkerFactory.getMarker("FATAL"); diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/LdapConnexion.java b/src/main/java/fr/insee/rmes/external_services/authentication/LdapConnexion.java index 47332b0c3..fd41316df 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/LdapConnexion.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/LdapConnexion.java @@ -1,19 +1,17 @@ package fr.insee.rmes.external_services.authentication; -import java.util.Hashtable; +import fr.insee.rmes.config.Config; +import fr.insee.rmes.exceptions.RmesException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; - -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.rmes.config.Config; -import fr.insee.rmes.exceptions.RmesException; +import java.util.Hashtable; @Service public class LdapConnexion { @@ -21,7 +19,7 @@ public class LdapConnexion { @Autowired Config config; - static final Logger logger = LogManager.getLogger(LdapConnexion.class); + static final Logger logger = LoggerFactory.getLogger(LdapConnexion.class); public DirContext getLdapContext() throws NamingException, RmesException { if(config.getLdapUrl() != null && !config.getLdapUrl().isEmpty()) { diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/stamps/RmesStampsImpl.java b/src/main/java/fr/insee/rmes/external_services/authentication/stamps/RmesStampsImpl.java index 384c10630..5ce1ddcb4 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/stamps/RmesStampsImpl.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/stamps/RmesStampsImpl.java @@ -1,26 +1,16 @@ package fr.insee.rmes.external_services.authentication.stamps; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; +import fr.insee.rmes.config.auth.security.UserDecoder; +import fr.insee.rmes.config.auth.user.Stamp; +import fr.insee.rmes.config.auth.user.User; import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.external_services.authentication.LdapConnexion; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service -public class RmesStampsImpl implements StampsService { - - @Autowired - StampsRestrictionsService stampsRestrictionService; - - @Autowired - LdapConnexion ldapConnexion; - - @Autowired - Config config; +public record RmesStampsImpl(UserDecoder userDecoder) implements StampsService { + public static final List stamps = List.of( "DG33-C990", @@ -291,16 +281,15 @@ public class RmesStampsImpl implements StampsService { "SSM-DEPS" ); + @Override public List getStamps() { return stamps; } @Override - public String getStamp() throws RmesException { - JSONObject jsonStamp = new JSONObject(); - jsonStamp.put("stamp",stampsRestrictionService.getUser().getStamp()); - return jsonStamp.toString(); + public Stamp findStampFrom(Object principal) throws RmesException { + return this.userDecoder.fromPrincipal(principal).map(User::stamp).orElse(null); } } diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/stamps/StampsService.java b/src/main/java/fr/insee/rmes/external_services/authentication/stamps/StampsService.java index 5af168ce2..963544623 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/stamps/StampsService.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/stamps/StampsService.java @@ -1,5 +1,6 @@ package fr.insee.rmes.external_services.authentication.stamps; +import fr.insee.rmes.config.auth.user.Stamp; import fr.insee.rmes.exceptions.RmesException; import java.util.List; @@ -8,5 +9,5 @@ public interface StampsService { List getStamps() throws RmesException; - String getStamp() throws RmesException; + Stamp findStampFrom(Object principal) throws RmesException; } diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/RmesUserRolesManagerImpl.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/RmesUserRolesManagerImpl.java index a5f4c6051..19de8434c 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/RmesUserRolesManagerImpl.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/RmesUserRolesManagerImpl.java @@ -1,22 +1,7 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeSet; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Service; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.Config; import fr.insee.rmes.config.auth.roles.UserRolesManagerService; @@ -28,6 +13,19 @@ import fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel.UsersSugoi; import fr.insee.rmes.utils.JSONComparator; import fr.insee.rmes.utils.RestTemplateUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; @Service public class RmesUserRolesManagerImpl implements UserRolesManagerService { @@ -43,7 +41,7 @@ public class RmesUserRolesManagerImpl implements UserRolesManagerService { @Autowired RestTemplateUtils restTemplateUtils; - static final Logger logger = LogManager.getLogger(RmesUserRolesManagerImpl.class); + static final Logger logger = LoggerFactory.getLogger(RmesUserRolesManagerImpl.class); private static final String SUGOI_REALM_SEARCH_PATH = "/realms/"; private static final String SUGOI_APP_SEARCH_PATH = "/applications/"; diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/Sugoi.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/Sugoi.java index 72e418a25..da0b4d8ed 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/Sugoi.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/Sugoi.java @@ -1,7 +1,7 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager; -import java.util.Arrays; - +import fr.insee.rmes.config.Config; +import fr.insee.rmes.exceptions.RmesException; import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; @@ -10,13 +10,12 @@ import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.exceptions.RmesException; +import java.util.Arrays; public class Sugoi { @@ -27,7 +26,7 @@ private Sugoi() { private static Config config; - static final Logger logger = LogManager.getLogger(Sugoi.class); + static final Logger logger = LoggerFactory.getLogger(Sugoi.class); private static void execute(HttpRequestBase httpMethod) throws RmesException{ /* add authentication params */ diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Application.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Application.java index 2e75e34ff..b056d07da 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Application.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Application.java @@ -1,18 +1,12 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel; +import com.fasterxml.jackson.annotation.*; + +import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "name", diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Attributes.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Attributes.java index b7d81519a..5b4456725 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Attributes.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Attributes.java @@ -1,18 +1,12 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel; +import com.fasterxml.jackson.annotation.*; + +import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "phone_number", diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Group.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Group.java index 275ffa64e..4f9b249e9 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Group.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/Group.java @@ -1,18 +1,12 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel; +import com.fasterxml.jackson.annotation.*; + +import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "name", diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UserSugoi.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UserSugoi.java index e1b8ade63..af0f04db1 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UserSugoi.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UserSugoi.java @@ -1,19 +1,13 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel; +import com.fasterxml.jackson.annotation.*; + +import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "lastName", diff --git a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UsersSugoi.java b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UsersSugoi.java index de6890685..4f23be272 100644 --- a/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UsersSugoi.java +++ b/src/main/java/fr/insee/rmes/external_services/authentication/user_roles_manager/sugoiModel/UsersSugoi.java @@ -1,18 +1,12 @@ package fr.insee.rmes.external_services.authentication.user_roles_manager.sugoiModel; +import com.fasterxml.jackson.annotation.*; + +import javax.annotation.Generated; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "results", diff --git a/src/main/java/fr/insee/rmes/external_services/export/ClasspathUriResolver.java b/src/main/java/fr/insee/rmes/external_services/export/ClasspathUriResolver.java index 3a9a4df01..f8afe4132 100644 --- a/src/main/java/fr/insee/rmes/external_services/export/ClasspathUriResolver.java +++ b/src/main/java/fr/insee/rmes/external_services/export/ClasspathUriResolver.java @@ -1,13 +1,13 @@ package fr.insee.rmes.external_services.export; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ClasspathUriResolver implements URIResolver { static final Logger logger = LoggerFactory.getLogger(ClasspathUriResolver.class); diff --git a/src/main/java/fr/insee/rmes/external_services/export/XDocReport.java b/src/main/java/fr/insee/rmes/external_services/export/XDocReport.java index e482258d4..ea8930a1a 100644 --- a/src/main/java/fr/insee/rmes/external_services/export/XDocReport.java +++ b/src/main/java/fr/insee/rmes/external_services/export/XDocReport.java @@ -1,23 +1,5 @@ package fr.insee.rmes.external_services.export; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - import fr.insee.rmes.bauhaus_services.operations.operations.VarBookExportBuilder; import fr.insee.rmes.exceptions.RmesException; import fr.opensagres.xdocreport.converter.ConverterTypeTo; @@ -28,6 +10,16 @@ import fr.opensagres.xdocreport.template.IContext; import fr.opensagres.xdocreport.template.TemplateEngineKind; import freemarker.ext.dom.NodeModel; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import java.io.*; @Component public class XDocReport { @@ -35,7 +27,7 @@ public class XDocReport { @Autowired VarBookExportBuilder varBookExport; - static final Logger logger = LogManager.getLogger(XDocReport.class); + static final Logger logger = LoggerFactory.getLogger(XDocReport.class); public OutputStream exportVariableBookInPdf(String xmlFilename, String odtTemplate) throws RmesException { // 1) Load DOCX into XWPFDocument diff --git a/src/main/java/fr/insee/rmes/external_services/notifications/DefaultNotificationsImpl.java b/src/main/java/fr/insee/rmes/external_services/notifications/DefaultNotificationsImpl.java index 22fcbad1c..120e56c80 100644 --- a/src/main/java/fr/insee/rmes/external_services/notifications/DefaultNotificationsImpl.java +++ b/src/main/java/fr/insee/rmes/external_services/notifications/DefaultNotificationsImpl.java @@ -1,11 +1,11 @@ package fr.insee.rmes.external_services.notifications; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DefaultNotificationsImpl implements NotificationsContract { - static final Logger logger = LogManager.getLogger(DefaultNotificationsImpl.class); + static final Logger logger = LoggerFactory.getLogger(DefaultNotificationsImpl.class); public void notifyConceptCreation(String id, String uri) { logger.info("Notification : concept creation, id : {}, uri {}", id, uri); diff --git a/src/main/java/fr/insee/rmes/external_services/notifications/RmesNotificationsImpl.java b/src/main/java/fr/insee/rmes/external_services/notifications/RmesNotificationsImpl.java index 505237df2..8553dbdc0 100644 --- a/src/main/java/fr/insee/rmes/external_services/notifications/RmesNotificationsImpl.java +++ b/src/main/java/fr/insee/rmes/external_services/notifications/RmesNotificationsImpl.java @@ -1,25 +1,17 @@ package fr.insee.rmes.external_services.notifications; -import java.util.Arrays; - -import javax.annotation.PostConstruct; -import javax.jms.Connection; -import javax.jms.DeliveryMode; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; -import javax.jms.TextMessage; - +import fr.insee.rmes.config.Config; +import fr.insee.rmes.exceptions.RmesException; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.exceptions.RmesException; +import javax.annotation.PostConstruct; +import javax.jms.*; +import java.util.Arrays; @Service public class RmesNotificationsImpl implements NotificationsContract { @@ -38,7 +30,7 @@ public void init() { private static final long DELAY = 1; private static final long DUREE_VIE_MESSAGE = 300000; - static final Logger logger = LogManager.getLogger(RmesNotificationsImpl.class); + static final Logger logger = LoggerFactory.getLogger(RmesNotificationsImpl.class); @Override public void notifyConceptCreation(String id, String uri) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/model/concepts/Concept.java b/src/main/java/fr/insee/rmes/model/concepts/Concept.java index ac0566902..6a76031a8 100644 --- a/src/main/java/fr/insee/rmes/model/concepts/Concept.java +++ b/src/main/java/fr/insee/rmes/model/concepts/Concept.java @@ -1,12 +1,12 @@ package fr.insee.rmes.model.concepts; -import java.time.LocalDateTime; -import java.util.List; - import fr.insee.rmes.model.links.Link; import fr.insee.rmes.model.notes.DatableNote; import fr.insee.rmes.model.notes.VersionableNote; +import java.time.LocalDateTime; +import java.util.List; + public class Concept { private String id; diff --git a/src/main/java/fr/insee/rmes/model/concepts/ConceptForExport.java b/src/main/java/fr/insee/rmes/model/concepts/ConceptForExport.java index 9e37b81d2..6b8ec9af1 100644 --- a/src/main/java/fr/insee/rmes/model/concepts/ConceptForExport.java +++ b/src/main/java/fr/insee/rmes/model/concepts/ConceptForExport.java @@ -1,12 +1,11 @@ package fr.insee.rmes.model.concepts; -import java.util.ArrayList; -import java.util.List; - +import fr.insee.rmes.bauhaus_services.Constants; import org.json.JSONArray; import org.json.JSONObject; -import fr.insee.rmes.bauhaus_services.Constants; +import java.util.ArrayList; +import java.util.List; public class ConceptForExport { diff --git a/src/main/java/fr/insee/rmes/model/links/OperationsLink.java b/src/main/java/fr/insee/rmes/model/links/OperationsLink.java index 9918d2ba6..648a86472 100644 --- a/src/main/java/fr/insee/rmes/model/links/OperationsLink.java +++ b/src/main/java/fr/insee/rmes/model/links/OperationsLink.java @@ -1,10 +1,10 @@ package fr.insee.rmes.model.links; -import java.util.Objects; - import fr.opensagres.xdocreport.core.utils.StringUtils; import io.swagger.v3.oas.annotations.media.Schema; +import java.util.Objects; + public class OperationsLink { public static final String CLASS_NAME = "fr.insee.rmes.model.links.OperationsLink"; diff --git a/src/main/java/fr/insee/rmes/model/notes/DatableNote.java b/src/main/java/fr/insee/rmes/model/notes/DatableNote.java index fcc535acd..7c33acae5 100644 --- a/src/main/java/fr/insee/rmes/model/notes/DatableNote.java +++ b/src/main/java/fr/insee/rmes/model/notes/DatableNote.java @@ -1,9 +1,9 @@ package fr.insee.rmes.model.notes; -import java.time.LocalDateTime; - import org.eclipse.rdf4j.model.IRI; +import java.time.LocalDateTime; + public class DatableNote { private String noteType; diff --git a/src/main/java/fr/insee/rmes/model/notes/VersionableNote.java b/src/main/java/fr/insee/rmes/model/notes/VersionableNote.java index 29958aea0..b6fb7f395 100644 --- a/src/main/java/fr/insee/rmes/model/notes/VersionableNote.java +++ b/src/main/java/fr/insee/rmes/model/notes/VersionableNote.java @@ -1,9 +1,9 @@ package fr.insee.rmes.model.notes; -import java.time.LocalDateTime; - import org.eclipse.rdf4j.model.IRI; +import java.time.LocalDateTime; + public class VersionableNote { diff --git a/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsDatedNoteTypes.java b/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsDatedNoteTypes.java index 05bfa9f56..6ea982e76 100644 --- a/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsDatedNoteTypes.java +++ b/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsDatedNoteTypes.java @@ -1,15 +1,13 @@ package fr.insee.rmes.model.notes.concepts; -import java.util.EnumSet; - -import javax.annotation.PostConstruct; - +import fr.insee.rmes.config.Config; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fr.insee.rmes.config.Config; +import javax.annotation.PostConstruct; +import java.util.EnumSet; public enum ConceptsDatedNoteTypes { diff --git a/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsVersionnedNoteTypes.java b/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsVersionnedNoteTypes.java index 9d48d91c1..d9ad3487a 100644 --- a/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsVersionnedNoteTypes.java +++ b/src/main/java/fr/insee/rmes/model/notes/concepts/ConceptsVersionnedNoteTypes.java @@ -1,18 +1,16 @@ package fr.insee.rmes.model.notes.concepts; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - +import fr.insee.rmes.config.Config; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.vocabulary.SKOS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fr.insee.rmes.config.Config; +import javax.annotation.PostConstruct; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; /** * Énumération correspondant aux différents types de notes explicatives. diff --git a/src/main/java/fr/insee/rmes/model/operations/Family.java b/src/main/java/fr/insee/rmes/model/operations/Family.java index f743fd401..7e3e14d7d 100644 --- a/src/main/java/fr/insee/rmes/model/operations/Family.java +++ b/src/main/java/fr/insee/rmes/model/operations/Family.java @@ -1,10 +1,10 @@ package fr.insee.rmes.model.operations; -import java.util.List; - import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; + public class Family { @Schema(description = "Id", required = true) diff --git a/src/main/java/fr/insee/rmes/model/operations/Indicator.java b/src/main/java/fr/insee/rmes/model/operations/Indicator.java index 1defa053b..04ec7c72f 100644 --- a/src/main/java/fr/insee/rmes/model/operations/Indicator.java +++ b/src/main/java/fr/insee/rmes/model/operations/Indicator.java @@ -1,16 +1,15 @@ package fr.insee.rmes.model.operations; -import java.util.List; -import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat.Shape; - import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.links.OperationsLink; import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; +import java.util.Objects; + public class Indicator { diff --git a/src/main/java/fr/insee/rmes/model/operations/Operation.java b/src/main/java/fr/insee/rmes/model/operations/Operation.java index 6369a7b84..1dcea0750 100644 --- a/src/main/java/fr/insee/rmes/model/operations/Operation.java +++ b/src/main/java/fr/insee/rmes/model/operations/Operation.java @@ -1,8 +1,8 @@ package fr.insee.rmes.model.operations; import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; -import fr.opensagres.xdocreport.utils.StringUtils; import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.util.ObjectUtils; public class Operation { @@ -58,7 +58,7 @@ public String getId() { } public void setId(String id) { - if(StringUtils.isNotEmpty(id)) { + if(!ObjectUtils.isEmpty(id)) { this.id = id; } } diff --git a/src/main/java/fr/insee/rmes/model/operations/Series.java b/src/main/java/fr/insee/rmes/model/operations/Series.java index 62438cf2c..7509dd984 100644 --- a/src/main/java/fr/insee/rmes/model/operations/Series.java +++ b/src/main/java/fr/insee/rmes/model/operations/Series.java @@ -1,15 +1,14 @@ package fr.insee.rmes.model.operations; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat.Shape; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabelTwoLangs; import fr.insee.rmes.model.links.OperationsLink; import io.swagger.v3.oas.annotations.media.Schema; +import java.util.List; + public class Series { @Schema(description = "Id", required = true) diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/Document.java b/src/main/java/fr/insee/rmes/model/operations/documentations/Document.java index f2d493cdb..c24081cdf 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/Document.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/Document.java @@ -1,12 +1,10 @@ package fr.insee.rmes.model.operations.documentations; -import org.apache.commons.lang3.StringUtils; - import com.fasterxml.jackson.annotation.JsonProperty; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.utils.DateUtils; +import org.apache.commons.lang3.StringUtils; public class Document { diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/Documentation.java b/src/main/java/fr/insee/rmes/model/operations/documentations/Documentation.java index a976a09d6..52e532591 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/Documentation.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/Documentation.java @@ -1,11 +1,10 @@ package fr.insee.rmes.model.operations.documentations; -import java.util.List; - +import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; import org.apache.commons.lang3.StringUtils; -import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.List; public class Documentation { diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/DocumentationRubric.java b/src/main/java/fr/insee/rmes/model/operations/documentations/DocumentationRubric.java index 60c059cff..f419af2ae 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/DocumentationRubric.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/DocumentationRubric.java @@ -1,13 +1,11 @@ package fr.insee.rmes.model.operations.documentations; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - import com.fasterxml.jackson.annotation.JsonFormat; - import fr.insee.rmes.utils.XhtmlToMarkdownUtils; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; public class DocumentationRubric { diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/ExtensiveSims.java b/src/main/java/fr/insee/rmes/model/operations/documentations/ExtensiveSims.java index 30e16ec8d..442c60c42 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/ExtensiveSims.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/ExtensiveSims.java @@ -1,13 +1,12 @@ package fr.insee.rmes.model.operations.documentations; -import org.springframework.beans.factory.annotation.Autowired; - import fr.insee.rmes.bauhaus_services.operations.documentations.DocumentationsUtils; import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; import fr.insee.rmes.bauhaus_services.operations.series.SeriesUtils; import fr.insee.rmes.model.operations.Indicator; import fr.insee.rmes.model.operations.Operation; import fr.insee.rmes.model.operations.Series; +import org.springframework.beans.factory.annotation.Autowired; public class ExtensiveSims { @Autowired diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/MSD.java b/src/main/java/fr/insee/rmes/model/operations/documentations/MSD.java index 5caf50e82..f9b9d4537 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/MSD.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/MSD.java @@ -1,11 +1,11 @@ package fr.insee.rmes.model.operations.documentations; -import java.util.ArrayList; -import java.util.List; - import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import java.util.ArrayList; +import java.util.List; + public class MSD { @JacksonXmlProperty(localName = "mas") diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java b/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java index 7e7189148..817e0fafc 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java @@ -1,16 +1,15 @@ package fr.insee.rmes.model.operations.documentations; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.vocabulary.XSD; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.persistance.ontologies.DCMITYPE; import fr.insee.rmes.persistance.ontologies.GEO; import fr.insee.rmes.persistance.ontologies.ORG; import fr.insee.rmes.persistance.ontologies.SDMX_MM; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.vocabulary.XSD; + +import java.util.HashMap; +import java.util.Map; public enum RangeType { diff --git a/src/main/java/fr/insee/rmes/model/structures/Structure.java b/src/main/java/fr/insee/rmes/model/structures/Structure.java index d565c76fa..683f786d8 100644 --- a/src/main/java/fr/insee/rmes/model/structures/Structure.java +++ b/src/main/java/fr/insee/rmes/model/structures/Structure.java @@ -1,9 +1,9 @@ package fr.insee.rmes.model.structures; -import java.util.List; - import fr.insee.rmes.exceptions.RmesException; +import java.util.List; + public class Structure { private String id; diff --git a/src/main/java/fr/insee/rmes/persistance/ontologies/INSEE.java b/src/main/java/fr/insee/rmes/persistance/ontologies/INSEE.java index 6d0ad3f44..2014affe0 100644 --- a/src/main/java/fr/insee/rmes/persistance/ontologies/INSEE.java +++ b/src/main/java/fr/insee/rmes/persistance/ontologies/INSEE.java @@ -1,13 +1,12 @@ package fr.insee.rmes.persistance.ontologies; +import fr.insee.rmes.bauhaus_services.Constants; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Namespace; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleNamespace; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import fr.insee.rmes.bauhaus_services.Constants; - public class INSEE { private INSEE() { diff --git a/src/main/java/fr/insee/rmes/persistance/ontologies/QB.java b/src/main/java/fr/insee/rmes/persistance/ontologies/QB.java index 681403a1d..893b1c7c8 100644 --- a/src/main/java/fr/insee/rmes/persistance/ontologies/QB.java +++ b/src/main/java/fr/insee/rmes/persistance/ontologies/QB.java @@ -1,13 +1,12 @@ package fr.insee.rmes.persistance.ontologies; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Namespace; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleNamespace; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; - public class QB { private QB() { diff --git a/src/main/java/fr/insee/rmes/persistance/ontologies/SCHEMA.java b/src/main/java/fr/insee/rmes/persistance/ontologies/SCHEMA.java index a5c36ea6a..96a34ac9b 100644 --- a/src/main/java/fr/insee/rmes/persistance/ontologies/SCHEMA.java +++ b/src/main/java/fr/insee/rmes/persistance/ontologies/SCHEMA.java @@ -1,13 +1,12 @@ package fr.insee.rmes.persistance.ontologies; +import fr.insee.rmes.bauhaus_services.Constants; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Namespace; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.SimpleNamespace; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; -import fr.insee.rmes.bauhaus_services.Constants; - public class SCHEMA { private SCHEMA() { diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/code_list/CodeListQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/code_list/CodeListQueries.java index 99a5053f7..a527db74e 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/code_list/CodeListQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/code_list/CodeListQueries.java @@ -1,13 +1,13 @@ package fr.insee.rmes.persistance.sparql_queries.code_list; -import java.util.HashMap; -import java.util.Map; - import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import java.util.HashMap; +import java.util.Map; + public class CodeListQueries extends GenericQueries { private static final String CODES_LISTS_GRAPH = "CODES_LISTS_GRAPH"; diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/concepts/ConceptsQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/concepts/ConceptsQueries.java index 9f1c907da..748f8af46 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/concepts/ConceptsQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/concepts/ConceptsQueries.java @@ -1,12 +1,12 @@ package fr.insee.rmes.persistance.sparql_queries.concepts; -import java.util.HashMap; -import java.util.Map; - import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import java.util.HashMap; +import java.util.Map; + public class ConceptsQueries extends GenericQueries{ private static final String URI_CONCEPT = "uriConcept"; diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/geography/GeoQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/geography/GeoQueries.java index edb37ef85..2560162ed 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/geography/GeoQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/geography/GeoQueries.java @@ -1,13 +1,13 @@ package fr.insee.rmes.persistance.sparql_queries.geography; -import java.util.HashMap; -import java.util.Map; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import java.util.HashMap; +import java.util.Map; + public class GeoQueries extends GenericQueries{ diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/links/LinksQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/links/LinksQueries.java index 8268f2b4f..b0c7d2c53 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/links/LinksQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/links/LinksQueries.java @@ -1,9 +1,8 @@ package fr.insee.rmes.persistance.sparql_queries.links; -import org.eclipse.rdf4j.model.IRI; - import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.IRI; public class LinksQueries extends GenericQueries{ diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/notes/NotesQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/notes/NotesQueries.java index 491f1436a..f5f61ea1c 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/notes/NotesQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/notes/NotesQueries.java @@ -1,9 +1,8 @@ package fr.insee.rmes.persistance.sparql_queries.notes; -import org.eclipse.rdf4j.model.IRI; - import fr.insee.rmes.model.notes.DatableNote; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.IRI; public class NotesQueries extends GenericQueries{ diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/ParentQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/ParentQueries.java index 71e7a4d47..d0c3d52ed 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/ParentQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/ParentQueries.java @@ -1,13 +1,13 @@ package fr.insee.rmes.persistance.sparql_queries.operations; -import java.util.HashMap; -import java.util.Map; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import java.util.HashMap; +import java.util.Map; + public class ParentQueries extends GenericQueries{ static Map params ; diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/documentations/DocumentationsQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/documentations/DocumentationsQueries.java index 7126ac757..43c5ff649 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/documentations/DocumentationsQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/documentations/DocumentationsQueries.java @@ -1,15 +1,14 @@ package fr.insee.rmes.persistance.sparql_queries.operations.documentations; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.rdf4j.model.Resource; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.RangeType; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.Resource; + +import java.util.HashMap; +import java.util.Map; public class DocumentationsQueries extends GenericQueries{ diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/famOpeSerUtils/FamOpeSerQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/famOpeSerUtils/FamOpeSerQueries.java index 26fde0c53..d5e747b0c 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/famOpeSerUtils/FamOpeSerQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/operations/famOpeSerUtils/FamOpeSerQueries.java @@ -1,14 +1,13 @@ package fr.insee.rmes.persistance.sparql_queries.operations.famOpeSerUtils; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.rdf4j.model.IRI; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.IRI; + +import java.util.HashMap; +import java.util.Map; public class FamOpeSerQueries extends GenericQueries{ diff --git a/src/main/java/fr/insee/rmes/persistance/sparql_queries/structures/StructureQueries.java b/src/main/java/fr/insee/rmes/persistance/sparql_queries/structures/StructureQueries.java index 93b44ce1b..e28151381 100644 --- a/src/main/java/fr/insee/rmes/persistance/sparql_queries/structures/StructureQueries.java +++ b/src/main/java/fr/insee/rmes/persistance/sparql_queries/structures/StructureQueries.java @@ -1,14 +1,14 @@ package fr.insee.rmes.persistance.sparql_queries.structures; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - import fr.insee.rmes.bauhaus_services.rdf_utils.FreeMarkerUtils; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.persistance.ontologies.INSEE; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + public class StructureQueries extends GenericQueries{ public static String getStructures() throws RmesException { diff --git a/src/main/java/fr/insee/rmes/utils/DateUtils.java b/src/main/java/fr/insee/rmes/utils/DateUtils.java index 97e6e9e71..4499ef64f 100644 --- a/src/main/java/fr/insee/rmes/utils/DateUtils.java +++ b/src/main/java/fr/insee/rmes/utils/DateUtils.java @@ -1,7 +1,7 @@ package fr.insee.rmes.utils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.time.LocalDateTime; @@ -14,7 +14,7 @@ public class DateUtils { - private static final Logger logger = LogManager.getLogger(DateUtils.class); + private static final Logger logger = LoggerFactory.getLogger(DateUtils.class); private static List dateFormats; diff --git a/src/main/java/fr/insee/rmes/utils/DocumentBuilders.java b/src/main/java/fr/insee/rmes/utils/DocumentBuilders.java index 829059eab..5afd32c0c 100644 --- a/src/main/java/fr/insee/rmes/utils/DocumentBuilders.java +++ b/src/main/java/fr/insee/rmes/utils/DocumentBuilders.java @@ -1,6 +1,6 @@ package fr.insee.rmes.utils; + import javax.xml.parsers.DocumentBuilder; -// BASED ON SOURCE: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; diff --git a/src/main/java/fr/insee/rmes/utils/FilesUtils.java b/src/main/java/fr/insee/rmes/utils/FilesUtils.java index d37bf7dfc..c61117454 100644 --- a/src/main/java/fr/insee/rmes/utils/FilesUtils.java +++ b/src/main/java/fr/insee/rmes/utils/FilesUtils.java @@ -1,30 +1,26 @@ package fr.insee.rmes.utils; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.Normalizer; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.zeroturnaround.zip.FileSource; import org.zeroturnaround.zip.ZipEntrySource; import org.zeroturnaround.zip.ZipUtil; +import java.io.*; +import java.text.Normalizer; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + public class FilesUtils { - private static final Logger log = LogManager.getLogger(FilesUtils.class); + private static final Logger log = LoggerFactory.getLogger(FilesUtils.class); public static final String ODT_EXTENSION = ".odt"; public static final String ODS_EXTENSION = ".ods"; public static final String ZIP_EXTENSION = ".zip"; + public static File streamToFile(InputStream in, String fileName, String fileExtension) throws IOException { final File tempFile = File.createTempFile(fileName, fileExtension); tempFile.deleteOnExit(); @@ -65,7 +61,7 @@ public static void zipDirectory(File directoryToZip) throws IOException { try { zipOut.close(); fos.close(); - }catch(IOException e ) { + } catch(IOException e ) { log.warn("outputStream already closed"); } diff --git a/src/main/java/fr/insee/rmes/utils/JSONComparator.java b/src/main/java/fr/insee/rmes/utils/JSONComparator.java index ba9c023a2..a64a21037 100644 --- a/src/main/java/fr/insee/rmes/utils/JSONComparator.java +++ b/src/main/java/fr/insee/rmes/utils/JSONComparator.java @@ -1,15 +1,15 @@ package fr.insee.rmes.utils; -import java.util.Comparator; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Comparator; public class JSONComparator implements Comparator { - static final Logger logger = LogManager.getLogger(JSONComparator.class); + static final Logger logger = LoggerFactory.getLogger(JSONComparator.class); private String fieldToCompare; @@ -26,7 +26,7 @@ public int compare(JSONObject o1, JSONObject o2) { id1 = o1.getString(this.fieldToCompare); id2 = o2.getString(this.fieldToCompare); } catch (JSONException e) { - logger.error(e); + logger.error("Error comparing json", e); } return id1.toLowerCase().compareTo(id2.toLowerCase()); diff --git a/src/main/java/fr/insee/rmes/utils/JSONUtils.java b/src/main/java/fr/insee/rmes/utils/JSONUtils.java index c39bf3f9a..9af847590 100644 --- a/src/main/java/fr/insee/rmes/utils/JSONUtils.java +++ b/src/main/java/fr/insee/rmes/utils/JSONUtils.java @@ -1,13 +1,13 @@ package fr.insee.rmes.utils; +import org.json.JSONArray; +import org.json.JSONObject; + import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.json.JSONArray; -import org.json.JSONObject; - public class JSONUtils { public static JSONArray extractFieldToArray(JSONArray jsonA, String field) { diff --git a/src/main/java/fr/insee/rmes/utils/PropertiesUtils.java b/src/main/java/fr/insee/rmes/utils/PropertiesUtils.java index b7058938c..fbe286fb0 100644 --- a/src/main/java/fr/insee/rmes/utils/PropertiesUtils.java +++ b/src/main/java/fr/insee/rmes/utils/PropertiesUtils.java @@ -1,33 +1,21 @@ package fr.insee.rmes.utils; -import javax.validation.constraints.NotNull; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.nio.file.Path; -import java.util.Optional; -import java.util.Properties; - -public class PropertiesUtils { - - private PropertiesUtils() { - throw new IllegalStateException("Utility class"); - } +import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; +import fr.insee.rmes.bauhaus_services.rdf_utils.UriUtils; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; +import java.util.Optional; - private static final Properties propsForReadPropertyFromFile=new Properties(); +@Component +public record PropertiesUtils (Environment environment) implements UriUtils.PropertiesFinder { - public static Optional readPropertyFromPath(@NotNull String propertyName, @NotNull Path filePath){ - propsForReadPropertyFromFile.remove(propertyName); - // Use OS charset : for example windows-1252 for windows, UTF-8 for linux, ... - // switch to java 11 to specify charset - try(Reader readerFromFile=new FileReader(filePath.toFile())){ - propsForReadPropertyFromFile.load(readerFromFile); - }catch (IOException e){ - //propsForReadPropertyFromFile remain empty if file cannot be read + public Optional findByName(String name){ + if (name==null){ + return Optional.empty(); } - return Optional.ofNullable(propsForReadPropertyFromFile.getProperty(propertyName)); + return Optional.ofNullable(this.environment.getProperty(name)); } } diff --git a/src/main/java/fr/insee/rmes/utils/RestTemplateUtils.java b/src/main/java/fr/insee/rmes/utils/RestTemplateUtils.java index bb4a2d63b..b80894d6c 100644 --- a/src/main/java/fr/insee/rmes/utils/RestTemplateUtils.java +++ b/src/main/java/fr/insee/rmes/utils/RestTemplateUtils.java @@ -1,5 +1,15 @@ package fr.insee.rmes.utils; +import fr.insee.rmes.exceptions.RmesException; +import org.apache.commons.codec.binary.Base64; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -11,22 +21,6 @@ import java.util.List; import java.util.Map; -import org.apache.commons.codec.binary.Base64; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; - -import fr.insee.rmes.exceptions.RmesException; - @Service public class RestTemplateUtils { diff --git a/src/main/java/fr/insee/rmes/utils/StringUtils.java b/src/main/java/fr/insee/rmes/utils/StringUtils.java index 228bee19b..222355c87 100644 --- a/src/main/java/fr/insee/rmes/utils/StringUtils.java +++ b/src/main/java/fr/insee/rmes/utils/StringUtils.java @@ -1,5 +1,9 @@ package fr.insee.rmes.utils; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import org.eclipse.rdf4j.model.IRI; +import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -19,5 +23,16 @@ public static List stringToList(String value) { val.add(value); return val; } - + @NotNull + public static String urisAsString(List uris) { + return uris.stream().map(StringUtils::uriAsString).reduce(String::concat).orElse(""); + } + + @NotNull + private static String uriAsString(IRI uri) { + return "<" + RdfUtils.toString(uri) + ">"; + } + + + } diff --git a/src/main/java/fr/insee/rmes/utils/XMLUtils.java b/src/main/java/fr/insee/rmes/utils/XMLUtils.java index 779e1c84f..28719f069 100644 --- a/src/main/java/fr/insee/rmes/utils/XMLUtils.java +++ b/src/main/java/fr/insee/rmes/utils/XMLUtils.java @@ -1,13 +1,17 @@ package fr.insee.rmes.utils; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.operations.documentations.DocumentationJsonMixIn; +import fr.insee.rmes.model.operations.documentations.Documentation; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; @@ -19,26 +23,19 @@ import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.text.StringEscapeUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.http.MediaType; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; - -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.bauhaus_services.operations.documentations.DocumentationJsonMixIn; -import fr.insee.rmes.model.operations.documentations.Documentation; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class XMLUtils { private static final String AMP = "&"; - static final Logger logger = LogManager.getLogger(XMLUtils.class); + static final Logger logger = LoggerFactory.getLogger(XMLUtils.class); private XMLUtils() { throw new IllegalStateException("Utility class"); diff --git a/src/main/java/fr/insee/rmes/utils/XhtmlToMarkdownUtils.java b/src/main/java/fr/insee/rmes/utils/XhtmlToMarkdownUtils.java index 25dd725d4..762ab4d41 100644 --- a/src/main/java/fr/insee/rmes/utils/XhtmlToMarkdownUtils.java +++ b/src/main/java/fr/insee/rmes/utils/XhtmlToMarkdownUtils.java @@ -1,15 +1,14 @@ package fr.insee.rmes.utils; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONArray; -import org.json.JSONObject; - import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.parser.ParserEmulationProfile; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.MutableDataSet; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; public class XhtmlToMarkdownUtils { diff --git a/src/main/java/fr/insee/rmes/utils/XsltUtils.java b/src/main/java/fr/insee/rmes/utils/XsltUtils.java index 70ab27878..e8555c21c 100644 --- a/src/main/java/fr/insee/rmes/utils/XsltUtils.java +++ b/src/main/java/fr/insee/rmes/utils/XsltUtils.java @@ -1,16 +1,11 @@ package fr.insee.rmes.utils; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.CopyOption; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.Map; +import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.exceptions.RmesException; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.xml.XMLConstants; import javax.xml.transform.Transformer; @@ -18,14 +13,13 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import fr.insee.rmes.bauhaus_services.Constants; -import fr.insee.rmes.exceptions.RmesException; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.Map; public class XsltUtils { diff --git a/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java b/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java index 6923025b3..a8d3140b8 100644 --- a/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java @@ -1,30 +1,14 @@ package fr.insee.rmes.webservice; -import fr.insee.rmes.bauhaus_services.classifications.item.ClassificationItemService; -import fr.insee.rmes.model.classification.Classification; -import fr.insee.rmes.model.classification.ClassificationItem; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - import fr.insee.rmes.bauhaus_services.ClassificationsService; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.classifications.item.ClassificationItemService; import fr.insee.rmes.config.swagger.model.IdLabel; import fr.insee.rmes.config.swagger.model.classifications.FamilyClass; import fr.insee.rmes.config.swagger.model.classifications.Members; import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.model.classification.Classification; +import fr.insee.rmes.model.classification.ClassificationItem; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -36,6 +20,15 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; /** * WebService class for resources of Classifications @@ -60,7 +53,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class ClassificationsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(ClassificationsResources.class); + static final Logger logger = LoggerFactory.getLogger(ClassificationsResources.class); @Autowired ClassificationsService classificationsService; @@ -165,7 +158,7 @@ public ResponseEntity getClassification(@PathVariable(Constants.ID) Stri } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value="/classification/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "updateClassification", summary = "Update an existing classification" ) public ResponseEntity updateClassification( @@ -179,7 +172,7 @@ public ResponseEntity updateClassification( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value="/classification/{id}/validate") @io.swagger.v3.oas.annotations.Operation(operationId = "publishClassification", summary = "Publish a classification") public ResponseEntity publishClassification( @@ -321,7 +314,7 @@ public ResponseEntity getCorrespondenceItem(@PathVariable("correspondenc } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @Operation(operationId = "uploadClassification", summary = "Upload a new classification in database" ) @PostMapping(value = "/upload/classification", consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) @RequestBody(content = @Content(encoding = @Encoding(name = "database", contentType = "text/plain"))) diff --git a/src/main/java/fr/insee/rmes/webservice/CodeListsResources.java b/src/main/java/fr/insee/rmes/webservice/CodeListsResources.java index 568291564..1aa0f41ac 100644 --- a/src/main/java/fr/insee/rmes/webservice/CodeListsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/CodeListsResources.java @@ -14,8 +14,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -38,12 +38,12 @@ @ApiResponse(responseCode = "500", description = "Internal server error")}) public class CodeListsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(CodeListsResources.class); + static final Logger logger = LoggerFactory.getLogger(CodeListsResources.class); @Autowired CodeListService codeListService; - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCodesList", summary = "Create a codes list") public ResponseEntity setCodesList( @@ -57,7 +57,7 @@ public ResponseEntity setCodesList( return ResponseEntity.status(HttpStatus.OK).body(id); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCodesList", summary = "Create a codes list") public ResponseEntity updateCodesList( @@ -73,7 +73,7 @@ public ResponseEntity updateCodesList( } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/{id}") @Operation(operationId = "deleteCodeList", summary = "Delete a codes list") public ResponseEntity deleteCodeList(@PathVariable(Constants.ID) String notation) { @@ -85,7 +85,7 @@ public ResponseEntity deleteCodeList(@PathVariable(Constants.ID) String } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/partial", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "createPartialCodeList", summary = "Create a codes list") public ResponseEntity createPartialCodeList( @@ -99,7 +99,7 @@ public ResponseEntity createPartialCodeList( return ResponseEntity.status(HttpStatus.OK).body(id); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/partial/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCodesList", summary = "Create a codes list") public ResponseEntity updatePartialCodeList( @@ -114,7 +114,7 @@ public ResponseEntity updatePartialCodeList( return ResponseEntity.status(HttpStatus.OK).body(id); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/partial/{id}") @Operation(operationId = "deletePartialCodeList", summary = "Delete a partial codes list") public ResponseEntity deletePartialCodeList(@PathVariable(Constants.ID) String notation) { @@ -242,7 +242,7 @@ public ResponseEntity getCodeByNotation(@PathVariable("notation") String return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/validate/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "publishFullCodeList", summary = "Publish a codelist") public ResponseEntity publishFullCodeList( @@ -255,7 +255,7 @@ public ResponseEntity publishFullCodeList( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/partial/validate/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "publishPartialCodeList", summary = "Publish a partial codelist") public ResponseEntity publishPartialCodeList( diff --git a/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java b/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java index 96e317fd6..2098aeca4 100644 --- a/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java @@ -13,8 +13,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -38,7 +38,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class ConceptsCollectionsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(ConceptsCollectionsResources.class); + static final Logger logger = LoggerFactory.getLogger(ConceptsCollectionsResources.class); public enum Language { lg1, lg2; diff --git a/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java b/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java index af6ddc1cf..2438afbdf 100644 --- a/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java @@ -16,8 +16,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -49,7 +49,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class ConceptsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(ConceptsResources.class); + static final Logger logger = LoggerFactory.getLogger(ConceptsResources.class); @Autowired ConceptsService conceptsService; @@ -82,9 +82,9 @@ public ResponseEntity getRelatedConcepts(@PathVariable(Constants.ID) Str } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isCollectionCreator() " - + "|| @AuthorizeMethodDecider.isConceptCreator()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).COLLECTION_CREATOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CREATOR)") @DeleteMapping(value="/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteConcept", summary = "deletion") public ResponseEntity deleteConcept(@PathVariable(Constants.ID) String id) { @@ -205,8 +205,8 @@ public ResponseEntity getCollectionMembersByID(@PathVariable(Constants.I } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isConceptsContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CONTRIBUTOR)") @PostMapping(value = "/concept", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setConcept", summary = "Create concept" ) public ResponseEntity setConcept( @@ -219,8 +219,9 @@ public ResponseEntity setConcept( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isConceptsContributor() ") + //TODO Test with Roles.ADMIN, Roles.CONCEPT_CONTRIBUTOR (user stamp is contributor and user stamp is not contributor) : StampRestrictionsServiceImpl.isConceptManager + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CONTRIBUTOR)") @PutMapping(value="/concept/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setConceptById", summary = "Update concept") public ResponseEntity setConcept( @@ -235,8 +236,9 @@ public ResponseEntity setConcept( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isConceptCreator() ") + //TODO Test with admin and with concept_creator (user stamp is creator of all concepts, user stamp is not creator of one concept) + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CREATOR)") @PutMapping(value= "/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setConceptsValidation", summary = "Concepts validation") public ResponseEntity setConceptsValidation( @@ -262,8 +264,8 @@ public void exportZipConcept(@PathVariable(Constants.ID) String id, @RequestHead conceptsService.exportZipConcept(id, accept, response); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isConceptsContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CONTRIBUTOR)") @PostMapping(value = "/collection", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCollection", summary = "Create collection") public ResponseEntity setCollection( @@ -276,9 +278,9 @@ public ResponseEntity setCollection( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isConceptsContributor() " - + "|| @AuthorizeMethodDecider.isCollectionCreator()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).COLLECTION_CREATOR)") @PutMapping(value = "/collection/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCollectionById", summary = "Update collection") public ResponseEntity setCollection( @@ -294,8 +296,8 @@ public ResponseEntity setCollection( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isCollectionCreator()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).COLLECTION_CREATOR)") @PutMapping(value= "/collections/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCollectionsValidation", summary = "Collections validation") public ResponseEntity setCollectionsValidation( diff --git a/src/main/java/fr/insee/rmes/webservice/ConsultationGestion.java b/src/main/java/fr/insee/rmes/webservice/ConsultationGestion.java index f0aec11c5..e41bc5e94 100644 --- a/src/main/java/fr/insee/rmes/webservice/ConsultationGestion.java +++ b/src/main/java/fr/insee/rmes/webservice/ConsultationGestion.java @@ -1,14 +1,5 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.consutation_gestion.ConsultationGestionService; import fr.insee.rmes.exceptions.RmesException; @@ -17,6 +8,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; @RestController diff --git a/src/main/java/fr/insee/rmes/webservice/DocumentsResources.java b/src/main/java/fr/insee/rmes/webservice/DocumentsResources.java index f10d9a944..7ce16d894 100644 --- a/src/main/java/fr/insee/rmes/webservice/DocumentsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/DocumentsResources.java @@ -13,8 +13,8 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -45,7 +45,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class DocumentsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(DocumentsResources.class); + static final Logger logger = LoggerFactory.getLogger(DocumentsResources.class); @Autowired DocumentsService documentsService; @@ -113,9 +113,9 @@ public ResponseEntity downloadDocument(@PathVariable(Constants.ID) Strin /** * Create a new document */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @Operation(operationId = "setDocument", summary = "Create document" ) @PostMapping(value = "/document", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, @@ -143,9 +143,9 @@ public ResponseEntity setDocument( /** * Update informations about a document */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping("/document/{id}") @Operation(operationId = "setDocumentById", summary = "Update document ") public ResponseEntity setDocument( @@ -165,9 +165,9 @@ public ResponseEntity setDocument( /** * Change the file of a document */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") @Operation(operationId = "changeDocument", summary = "Change document file" ) + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @Operation(operationId = "changeDocument", summary = "Change document file" ) @PutMapping(value = "/document/{id}/file", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE, @@ -193,9 +193,9 @@ public ResponseEntity changeDocument( /** * Delete a document */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") @DeleteMapping("/document/{id}") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @DeleteMapping("/document/{id}") @Operation(operationId = "deleteDocument", summary = "Delete a document") public ResponseEntity deleteDocument(@PathVariable(Constants.ID) String id) { HttpStatus status = null; @@ -232,9 +232,9 @@ public ResponseEntity getLink(@PathVariable(Constants.ID) String id) { /** * Create a new link */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PostMapping(value = "/link", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE, @@ -257,9 +257,9 @@ public ResponseEntity setLink( /** * Update informations about a link */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping("/link/{id}") @Operation(operationId = "setLinkById", summary = "Update link") public ResponseEntity setLink( @@ -277,9 +277,9 @@ public ResponseEntity setLink( /** * Delete a link */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") @DeleteMapping("/link/{id}") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @DeleteMapping("/link/{id}") @Operation(operationId = "deleteLink", summary = "Delete a link") public ResponseEntity deleteLink(@PathVariable(Constants.ID) String id) { HttpStatus status = null; diff --git a/src/main/java/fr/insee/rmes/webservice/GenericResources.java b/src/main/java/fr/insee/rmes/webservice/GenericResources.java index bea520aa5..fcf1b5662 100644 --- a/src/main/java/fr/insee/rmes/webservice/GenericResources.java +++ b/src/main/java/fr/insee/rmes/webservice/GenericResources.java @@ -1,22 +1,16 @@ package fr.insee.rmes.webservice; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; +import fr.insee.rmes.exceptions.RmesException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RestController; -import fr.insee.rmes.config.Config; -import fr.insee.rmes.exceptions.RmesException; - @RestController public class GenericResources { - @Autowired - Config config; - - protected static final Logger logger = LogManager.getLogger(GenericResources.class); + protected static final Logger logger = LoggerFactory.getLogger(GenericResources.class); protected ResponseEntity returnRmesException(RmesException e) { logger.error(e.getMessage(), e); diff --git a/src/main/java/fr/insee/rmes/webservice/GeographyResources.java b/src/main/java/fr/insee/rmes/webservice/GeographyResources.java index e50388f82..4100f841c 100644 --- a/src/main/java/fr/insee/rmes/webservice/GeographyResources.java +++ b/src/main/java/fr/insee/rmes/webservice/GeographyResources.java @@ -1,20 +1,5 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.GeographyService; import fr.insee.rmes.exceptions.RmesException; @@ -28,6 +13,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @RestController @@ -45,7 +38,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class GeographyResources extends GenericResources { - static final Logger logger = LogManager.getLogger(GeographyResources.class); + static final Logger logger = LoggerFactory.getLogger(GeographyResources.class); @Autowired GeographyService geoService; @@ -71,7 +64,7 @@ public ResponseEntity getGeoFeature(@PathVariable(Constants.ID) String i } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/territory", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createGeograohy", summary = "Create feature") public ResponseEntity createGeography( @@ -85,7 +78,7 @@ public ResponseEntity createGeography( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/territory/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "updateGeography", summary = "Update geography ") public ResponseEntity updateGeography( diff --git a/src/main/java/fr/insee/rmes/webservice/HealthcheckApi.java b/src/main/java/fr/insee/rmes/webservice/HealthcheckApi.java index 501968138..c6c813e14 100644 --- a/src/main/java/fr/insee/rmes/webservice/HealthcheckApi.java +++ b/src/main/java/fr/insee/rmes/webservice/HealthcheckApi.java @@ -1,28 +1,26 @@ package fr.insee.rmes.webservice; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.StringJoiner; -import java.util.function.UnaryOperator; - +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; +import fr.insee.rmes.config.auth.roles.UserRolesManagerService; +import fr.insee.rmes.exceptions.RmesException; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.NotNull; +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.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; -import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; -import fr.insee.rmes.config.auth.roles.UserRolesManagerService; -import fr.insee.rmes.exceptions.RmesException; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.StringJoiner; @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Opération réussie"), @@ -49,14 +47,26 @@ public class HealthcheckApi extends GenericResources { private final RepositoryPublication repositoryPublication; private final UserRolesManagerService userService; + private final String documentsStoragePublicationInterne; + private final String documentsStoragePublicationExterne; + private final String documentsStorageGestion; + + private static final Logger logger = LoggerFactory.getLogger(HealthcheckApi.class); + - private static final Logger logger = LogManager.getLogger(HealthcheckApi.class); - @Autowired - public HealthcheckApi(RepositoryGestion repoGestion, RepositoryPublication repositoryPublication, UserRolesManagerService userService) { + public HealthcheckApi(@Autowired RepositoryGestion repoGestion, + @Autowired RepositoryPublication repositoryPublication, + @Autowired UserRolesManagerService userService, + @Value("${fr.insee.rmes.bauhaus.storage.document.publication.interne}") String documentsStoragePublicationInterne, + @Value("${fr.insee.rmes.bauhaus.storage.document.publication}") String documentsStoragePublicationExterne, + @Value("${fr.insee.rmes.bauhaus.storage.document.gestion}") String documentsStorageGestion) { this.repoGestion = repoGestion; this.repositoryPublication = repositoryPublication; this.userService = userService; + this.documentsStoragePublicationInterne = documentsStoragePublicationInterne; + this.documentsStoragePublicationExterne = documentsStoragePublicationExterne; + this.documentsStorageGestion = documentsStorageGestion; } @GetMapping(value = "", @@ -100,12 +110,11 @@ private void checkSugoi(StringJoiner errorMessage, StringJoiner stateResult) { } } - @NotNull private void checkStrorage(StringJoiner errorMessage, StringJoiner stateResult) { stateResult = stateResult.add("Document storage \n"); - checkDocumentStorage(config.getDocumentsStorageGestion(), "Gestion", stateResult, errorMessage); - checkDocumentStorage(config.getDocumentsStoragePublicationExterne(), "Publication Externe", stateResult, errorMessage); - checkDocumentStorage(config.getDocumentsStoragePublicationInterne(), "Publication Interne", stateResult, errorMessage); + checkDocumentStorage(this.documentsStorageGestion, "Gestion", stateResult, errorMessage); + checkDocumentStorage(this.documentsStoragePublicationExterne, "Publication Externe", stateResult, errorMessage); + checkDocumentStorage(this.documentsStoragePublicationInterne, "Publication Interne", stateResult, errorMessage); } protected void checkDatabase(StringJoiner errorMessage, StringJoiner stateResult) { diff --git a/src/main/java/fr/insee/rmes/webservice/LoaderResources.java b/src/main/java/fr/insee/rmes/webservice/LoaderResources.java index f000b3889..82bf43919 100644 --- a/src/main/java/fr/insee/rmes/webservice/LoaderResources.java +++ b/src/main/java/fr/insee/rmes/webservice/LoaderResources.java @@ -1,29 +1,5 @@ package fr.insee.rmes.webservice; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.rdf4j.rio.RDFFormat; -import org.eclipse.rdf4j.rio.Rio; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.http.ContentDisposition; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -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.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryPublication; @@ -38,6 +14,21 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.eclipse.rdf4j.rio.RDFFormat; +import org.eclipse.rdf4j.rio.Rio; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.*; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; /** * WebService class to download/upload resources in databases @@ -70,7 +61,7 @@ public class LoaderResources extends GenericResources { private static final String GESTION = "gestion"; - static final Logger logger = LogManager.getLogger(LoaderResources.class); + static final Logger logger = LoggerFactory.getLogger(LoaderResources.class); @Autowired @@ -80,7 +71,7 @@ public class LoaderResources extends GenericResources { protected RepositoryPublication repositoryPublication; - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @Operation(operationId = "uploadFile", summary = "Upload a ttl or trig file in database" ) @PostMapping(value = "/upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) @RequestBody(content = @Content(encoding = @Encoding(name = "database", contentType = "text/plain"))) @@ -114,7 +105,7 @@ public ResponseEntity downloadDocument( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/download/graphs", produces = "*/*") @Operation(operationId = "downloadGraphs", summary = "Download all graphs in a zip file") public ResponseEntity downloadDocument( diff --git a/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java b/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java index a3050380d..392896475 100644 --- a/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java +++ b/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java @@ -1,15 +1,14 @@ package fr.insee.rmes.webservice; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; import fr.insee.rmes.bauhaus_services.OperationsService; 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.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; @RestController diff --git a/src/main/java/fr/insee/rmes/webservice/OrganizationsResources.java b/src/main/java/fr/insee/rmes/webservice/OrganizationsResources.java index 2d9616138..6a32e4a8b 100644 --- a/src/main/java/fr/insee/rmes/webservice/OrganizationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/OrganizationsResources.java @@ -1,17 +1,5 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.OrganizationsService; import fr.insee.rmes.config.swagger.model.IdLabel; import fr.insee.rmes.config.swagger.model.organizations.Organization; @@ -26,6 +14,13 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/organizations") @@ -42,7 +37,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class OrganizationsResources extends GenericResources { - static final Logger logger = LogManager.getLogger(OrganizationsResources.class); + static final Logger logger = LoggerFactory.getLogger(OrganizationsResources.class); @Autowired OrganizationsService organizationsService; diff --git a/src/main/java/fr/insee/rmes/webservice/PublicResources.java b/src/main/java/fr/insee/rmes/webservice/PublicResources.java index e789f478d..01d1f5a26 100644 --- a/src/main/java/fr/insee/rmes/webservice/PublicResources.java +++ b/src/main/java/fr/insee/rmes/webservice/PublicResources.java @@ -17,122 +17,137 @@ 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.apache.commons.io.FileUtils; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.json.JSONObject; +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.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; import java.util.TreeSet; /** - * WebService class for resources - * schemes: - http - * - * consumes: - application/json - * - * produces: - application/json - * + * WebService class for resources + * schemes: - http + * + * consumes: - application/json + * + * produces: - application/json */ @RestController @RequestMapping("/") -@Tag(name="Application", description="Application API") -@ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "400", description = "Bad Request"), - @ApiResponse(responseCode = "401", description = "Unauthorized"), - @ApiResponse(responseCode = "403", description = "Forbidden"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "406", description = "Not Acceptable"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) -public class PublicResources extends GenericResources { +@Tag(name = "Application", description = "Application API") +@ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Success"), + @ApiResponse(responseCode = "204", description = "No Content"), + @ApiResponse(responseCode = "400", description = "Bad Request"), + @ApiResponse(responseCode = "401", description = "Unauthorized"), + @ApiResponse(responseCode = "403", description = "Forbidden"), + @ApiResponse(responseCode = "404", description = "Not found"), + @ApiResponse(responseCode = "406", description = "Not Acceptable"), + @ApiResponse(responseCode = "500", description = "Internal server error")}) +public class PublicResources extends GenericResources { - static final Logger logger = LogManager.getLogger(PublicResources.class); + static final Logger logger = LoggerFactory.getLogger(PublicResources.class); - @Autowired - UserRolesManagerService userRolesManagerService; - - @Autowired - StampsService stampsService; + private final UserRolesManagerService userRolesManagerService; - @GetMapping(value = "/init", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getInit", summary = "Initial properties", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Init.class)))}) - public ResponseEntity getProperties() throws RmesException { - JSONObject props = new JSONObject(); - try { - props.put("appHost", config.getAppHost()); - props.put("authorizationHost", config.getSugoiUi()); - props.put("defaultContributor", config.getDefaultContributor()); - props.put("defaultMailSender", config.getDefaultMailSender()); - props.put("maxLengthScopeNote", config.getMaxLengthScopeNote()); - props.put("lg1", config.getLg1()); - props.put("lg2", config.getLg2()); - props.put("authType", AuthType.getAuthType(config)); - props.put("modules", getActiveModules()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR,e.getMessage(),e.getClass().getSimpleName()); - } - return ResponseEntity.status(HttpStatus.SC_OK).body(props.toString()); - } + private final StampsService stampsService; + private final String env; + private final String lg2; + private final String lg1; + private final String maxLengthScopeNote; + private final String defaultMailSender; + private final String defaultContributor; + private final String sugoiUi; + private final String appHost; + private final List activeModules; - private List getActiveModules() { - String dirPath = config.getDocumentsStorageGestion() + "/BauhausActiveModules.txt"; - File file = new File(dirPath); + public PublicResources(@Autowired UserRolesManagerService userRolesManagerService, + @Autowired StampsService stampsService, + @Value("${fr.insee.rmes.bauhaus.env}") String env, + @Value("${fr.insee.rmes.bauhaus.lg1}") String lg2, + @Value("${fr.insee.rmes.bauhaus.lg2}") String lg1, + @Value("${fr.insee.rmes.bauhaus.concepts.maxLengthScopeNote}") String maxLengthScopeNote, + @Value("${fr.insee.rmes.bauhaus.concepts.defaultMailSender}") String defaultMailSender, + @Value("${fr.insee.rmes.bauhaus.concepts.defaultContributor}") String defaultContributor, + @Value("${fr.insee.rmes.bauhaus.sugoi.ui}") String sugoiUi, + @Value("${fr.insee.rmes.bauhaus.appHost}") String appHost, + @Value("${fr.insee.rmes.bauhaus.activeModules}") List activeModules) { + this.userRolesManagerService = userRolesManagerService; + this.stampsService = stampsService; + this.env = env; + this.lg2 = lg2; + this.lg1 = lg1; + this.maxLengthScopeNote = maxLengthScopeNote; + this.defaultMailSender = defaultMailSender; + this.defaultContributor = defaultContributor; + this.sugoiUi = sugoiUi; + this.appHost = appHost; + this.activeModules=activeModules; + } + + @GetMapping(value = "/init", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getInit", summary = "Initial properties", responses = {@ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Init.class)))}) + public ResponseEntity getProperties() throws RmesException { + JSONObject props = new JSONObject(); try { - return FileUtils.readLines(file, StandardCharsets.UTF_8);//Read lines in a list - } catch (IOException e) { - logger.error(e.getMessage(), e); - return new ArrayList<>(); - } - } + props.put("appHost", this.appHost); + props.put("authorizationHost", this.sugoiUi); + props.put("defaultContributor", this.defaultContributor); + props.put("defaultMailSender", this.defaultMailSender); + props.put("maxLengthScopeNote", this.maxLengthScopeNote); + props.put("lg1", this.lg1); + props.put("lg2", this.lg2); + props.put("authType", AuthType.getAuthType(this.env)); + props.put("modules", this.activeModules); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e.getClass().getSimpleName()); + } + return ResponseEntity.status(HttpStatus.SC_OK).body(props.toString()); + } - @GetMapping(value = "/stamps", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getStamps", summary = "List of stamps", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) - public ResponseEntity getStamps() { - try { - return ResponseEntity.status(HttpStatus.SC_OK).body(stampsService.getStamps()); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - } + @GetMapping(value = "/stamps", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getStamps", summary = "List of stamps", responses = {@ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) + public ResponseEntity getStamps() { + try { + return ResponseEntity.status(HttpStatus.SC_OK).body(stampsService.getStamps()); + } catch (RmesException e) { + return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + } + } - @GetMapping(value = "/disseminationStatus", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getDisseminationStatus", summary = "List of dissemination status", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=LabelUrl.class))))}) - public ResponseEntity getDisseminationStatus() { - TreeSet dsList = new TreeSet<>(); - for (DisseminationStatus ds : DisseminationStatus.values()) { - try { - dsList.add(new ObjectMapper().writeValueAsString(ds)); - } catch (JsonProcessingException e) { - return ResponseEntity.status(500).body(e.getMessage()); - } - } - return ResponseEntity.status(HttpStatus.SC_OK).body(dsList.toString()); - } + @GetMapping(value = "/disseminationStatus", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getDisseminationStatus", summary = "List of dissemination status", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LabelUrl.class))))}) + public ResponseEntity getDisseminationStatus() { + TreeSet dsList = new TreeSet<>(); + for (DisseminationStatus ds : DisseminationStatus.values()) { + try { + dsList.add(new ObjectMapper().writeValueAsString(ds)); + } catch (JsonProcessingException e) { + return ResponseEntity.status(500).body(e.getMessage()); + } + } + return ResponseEntity.status(HttpStatus.SC_OK).body(dsList.toString()); + } - @GetMapping(value = "/roles", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getRoles", summary = "List of roles", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=Roles.class))))}) - public ResponseEntity getRoles() { - String entity = null; - try { - entity = userRolesManagerService.getRoles(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.SC_OK).body(entity); - } + @GetMapping(value = "/roles", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getRoles", summary = "List of roles", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Roles.class))))}) + public ResponseEntity getRoles() { + String entity = null; + try { + entity = userRolesManagerService.getRoles(); + } catch (RmesException e) { + return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + } + return ResponseEntity.status(HttpStatus.SC_OK).body(entity); + } } \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/webservice/StructureResources.java b/src/main/java/fr/insee/rmes/webservice/StructureResources.java index bb0448ba9..f895208ca 100644 --- a/src/main/java/fr/insee/rmes/webservice/StructureResources.java +++ b/src/main/java/fr/insee/rmes/webservice/StructureResources.java @@ -1,21 +1,5 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -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.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.structures.StructureComponent; import fr.insee.rmes.bauhaus_services.structures.StructureService; @@ -31,6 +15,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/structures") @@ -47,7 +39,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error")}) public class StructureResources extends GenericResources { - static final Logger logger = LogManager.getLogger(StructureResources.class); + static final Logger logger = LoggerFactory.getLogger(StructureResources.class); @Autowired StructureService structureService; @@ -97,7 +89,7 @@ public ResponseEntity getStructureById(@PathVariable(Constants.ID) Strin } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/structure/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishStructureById", summary = "Publish a structure") public ResponseEntity publishStructureById(@PathVariable(Constants.ID) String id) { @@ -121,7 +113,7 @@ public ResponseEntity getStructureByIdDetails(@PathVariable(Constants.ID } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/structure", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setStructure", summary = "Create a structure") @@ -135,7 +127,7 @@ public ResponseEntity setStructure( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/structure/{structureId}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setStructure", summary = "Update a structure") @@ -150,7 +142,7 @@ public ResponseEntity setStructure( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping("/structure/{structureId}") @Operation(operationId = "deleteStructure", summary = "Delete a structure") public ResponseEntity deleteStructure(@PathVariable("structureId") String structureId) { @@ -206,7 +198,7 @@ public ResponseEntity getComponentById(@PathVariable(Constants.ID) Strin } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/components/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishComponentById", summary = "Publish a component") public ResponseEntity publishComponentById(@PathVariable(Constants.ID) String id) { @@ -218,7 +210,7 @@ public ResponseEntity publishComponentById(@PathVariable(Constants.ID) S } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/components/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteComponentById", summary = "delete a mutualized component") public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) String id) { @@ -230,7 +222,7 @@ public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) St } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/components/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "updateComponent", summary = "Update a component") @@ -244,7 +236,7 @@ public ResponseEntity updateComponentById(@PathVariable(Constants.ID) St } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/components", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "createComponent", summary = "create a component") diff --git a/src/main/java/fr/insee/rmes/webservice/TokenApi.java b/src/main/java/fr/insee/rmes/webservice/TokenApi.java index 606f8cc06..bbec0db94 100644 --- a/src/main/java/fr/insee/rmes/webservice/TokenApi.java +++ b/src/main/java/fr/insee/rmes/webservice/TokenApi.java @@ -2,8 +2,8 @@ import fr.insee.rmes.bauhaus_services.keycloak.KeycloakServices; import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +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; @@ -19,10 +19,10 @@ public class TokenApi extends GenericResources { protected KeycloakServices keycloakServices; - private static final Logger logger = LogManager.getLogger(TokenApi.class); + private static final Logger logger = LoggerFactory.getLogger(TokenApi.class); - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/{rdfServerUrl}") public String getToken(@PathVariable String rdfServerUrl) throws RmesException { logger.info("GET /token"); diff --git a/src/main/java/fr/insee/rmes/webservice/UserResources.java b/src/main/java/fr/insee/rmes/webservice/UserResources.java index 0e7bd7166..5e222c411 100644 --- a/src/main/java/fr/insee/rmes/webservice/UserResources.java +++ b/src/main/java/fr/insee/rmes/webservice/UserResources.java @@ -1,23 +1,7 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import fr.insee.rmes.config.auth.roles.UserRolesManagerService; -import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; +import fr.insee.rmes.config.auth.user.Stamp; import fr.insee.rmes.config.auth.user.User; -import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.external_services.authentication.stamps.StampsService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -27,6 +11,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; /** * WebService class for resources of Concepts @@ -56,38 +48,37 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class UserResources extends GenericResources { - static final Logger logger = LogManager.getLogger(UserResources.class); + static final Logger logger = LoggerFactory.getLogger(UserResources.class); + + private final StampsService stampsService; - @Autowired - UserRolesManagerService userRolesManagerService; - - @Autowired - StampsService stampsService; @Autowired - StampsRestrictionsService stampsRestrictionService; + public UserResources(StampsService stampsService) { + this.stampsService = stampsService; + } @GetMapping(value = "/stamp", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getStamp", summary = "User's stamp", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) - public ResponseEntity getStamp() { - String stamp = null; + public ResponseEntity getStamp(@AuthenticationPrincipal Object principal) { + Stamp stamp; try { - stamp = stampsService.getStamp(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + stamp = stampsService.findStampFrom(principal); + } catch (Exception e) { + logger.error("exception while retrieving stamp",e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).body("exception while retrieving stamp"); } return ResponseEntity.status(HttpStatus.SC_OK).body(stamp); } + @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "login", summary = "Fake Login", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class)))}) public ResponseEntity login( - @Parameter(description = "Component", required = true) @RequestBody String user) - throws JsonProcessingException { - stampsRestrictionService.setFakeUser(user); - return ResponseEntity.status(HttpStatus.SC_OK).build(); + @Parameter(description = "Component", required = true) @RequestBody String user) { + throw new RuntimeException("Deprecated to be removed: noop"); } diff --git a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java index a9b4b1656..1f5853644 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java @@ -1,18 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabel; import fr.insee.rmes.exceptions.RmesException; @@ -25,6 +12,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; /*************************************************************************************************** @@ -75,7 +68,7 @@ public ResponseEntity getFamilyByID(@PathVariable(Constants.ID) String i return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(jsonResultat); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/family/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyById", summary = "Update an existing family" ) public ResponseEntity setFamilyById( @@ -90,7 +83,7 @@ public ResponseEntity setFamilyById( } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping("/family") @io.swagger.v3.oas.annotations.Operation(operationId = "createFamily", summary = "Create a new family") public ResponseEntity createFamily( @@ -105,7 +98,7 @@ public ResponseEntity createFamily( return ResponseEntity.status(HttpStatus.OK).body(id); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/family/validate/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyValidation", summary = "Validate a family") public ResponseEntity setFamilyValidation( diff --git a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java index f2afe287c..5d3557759 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java @@ -1,19 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; @@ -26,6 +12,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @Qualifier("Indicator") @@ -91,7 +83,8 @@ public ResponseEntity getIndicatorByID(@PathVariable(Constants.ID) Strin * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + //TODO Test : admin then INDICATOR_CONTRIBUTOR with stamp fit then not + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PutMapping(value="/indicator/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicatorById", summary = "Update indicator") public ResponseEntity setIndicatorById( @@ -111,7 +104,7 @@ public ResponseEntity setIndicatorById( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PutMapping(value="/indicator/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicatorValidation", summary = "Indicator validation") public ResponseEntity setIndicatorValidation( @@ -129,7 +122,7 @@ public ResponseEntity setIndicatorValidation( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PostMapping(value="/indicator", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicator", summary = "Create indicator", responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) diff --git a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java index 875475e02..cd33f3148 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java @@ -173,7 +173,7 @@ public ResponseEntity getMetadataReportOwner(@PathVariable(Constants.ID) * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor() || @AuthorizeMethodDecider.isSeriesContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR || T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PostMapping(value = "/metadataReport", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReport", summary = "Create metadata report", responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) @@ -197,10 +197,10 @@ public ResponseEntity setMetadataReport( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/metadataReport/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReportById", summary = "Update metadata report") public ResponseEntity setMetadataReportById( @@ -220,7 +220,7 @@ public ResponseEntity setMetadataReportById( * @param id * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/metadataReport/delete/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "deleteMetadataReportById", summary = "Delete metadata report") public ResponseEntity deleteMetadataReportById( @@ -241,9 +241,9 @@ public ResponseEntity deleteMetadataReportById( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/metadataReport/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReportValidation", summary = "Sims validation") public ResponseEntity setSimsValidation( diff --git a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java index ad76223e7..2dd628f97 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java @@ -181,8 +181,8 @@ public ResponseEntity> getCodeBookCheck( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/operation/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setOperationById", summary = "Update operation") public ResponseEntity setOperationById(@PathVariable(Constants.ID) String id, @@ -201,7 +201,7 @@ public ResponseEntity setOperationById(@PathVariable(Constants.ID) Strin * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PostMapping(value = "/operation", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createOperation", summary = "Create operation") public ResponseEntity createOperation( @@ -221,7 +221,7 @@ public ResponseEntity createOperation( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/operation/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setOperationValidation", summary = "Operation validation") public ResponseEntity setOperationValidation(@PathVariable(Constants.ID) String id) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java index 321196ad2..51ab91ea2 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java @@ -1,19 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; @@ -27,6 +13,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @Qualifier("Series") @@ -105,9 +97,9 @@ public ResponseEntity getSeriesForSearchWithStamps(@Parameter( return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/series/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setSeriesById", summary = "Update series") @@ -153,7 +145,7 @@ public ResponseEntity getOperationsWithReport(@PathVariable(Constants.ID * @param body * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/series", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createSeries", summary = "Create series") @@ -174,8 +166,8 @@ public ResponseEntity createSeries( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/series/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setSeriesValidation", summary = "Series validation") diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 572bcb193..6fe0e2f41 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,7 +4,6 @@ spring.config.import=classpath:bauhaus-core.properties,optional:classpath:bauhau spring.servlet.multipart.max-file-size=40MB spring.servlet.multipart.max-request-size=40MB - # Config Swagger (only for display) fr.insee.rmes.bauhaus.version=@project.version@ #springdoc.api-docs.path= @@ -14,3 +13,9 @@ springdoc.swagger-ui.path=/index.html server.servlet.contextPath=/api/ spring.security.oauth2.resourceserver.jwt.issuer-uri=${fr.insee.rmes.bauhaus.auth-server-url} + +# to log exchanges with repo rdf, switch to debug +logging.level.org.apache.http.wire=info +# to log sparql queries and results, switch to trace +logging.level.fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryUtils=info + diff --git a/src/main/resources/bauhaus-core.properties b/src/main/resources/bauhaus-core.properties index 0490ffaa4..82bef0f05 100644 --- a/src/main/resources/bauhaus-core.properties +++ b/src/main/resources/bauhaus-core.properties @@ -10,6 +10,7 @@ fr.insee.rmes.bauhaus.cors.allowedOrigin=* jwt.id-claim = preferred_username jwt.role-claim = realm_access jwt.stamp-claim = timbre +jwt.role-claim.roles = roles fr.insee.rmes.bauhaus.sugoi.application = RMESGNCS fr.insee.rmes.bauhaus.sugoi.realm = SSP @@ -30,6 +31,8 @@ fr.insee.rmes.bauhaus.concepts.maxLengthScopeNote = 350 ############################### fr.insee.rmes.bauhaus.classifications.families.graph = codes/nomenclatures +fr.insee.rmes.bauhaus.activeModules = concepts,classifications,operations,habilitations + ############################### #OPERATIONS ############################### diff --git a/src/main/resources/bauhaus-dev.properties b/src/main/resources/bauhaus-dev.properties index b2196f15e..6ea106459 100644 --- a/src/main/resources/bauhaus-dev.properties +++ b/src/main/resources/bauhaus-dev.properties @@ -18,7 +18,7 @@ fr.insee.rmes.bauhaus.rdf.auth=ENABLED #HorsProd = /opt/tomcat9/logs/rmesgncs.log # Bdd Sesame de gestion -fr.insee.rmes.bauhaus.sesame.gestion.sesameServer = +fr.insee.rmes.bauhaus.sesame.gestion.sesameServer = XXX fr.insee.rmes.bauhaus.sesame.gestion.repository = XXX fr.insee.rmes.bauhaus.sesame.gestion.baseURI = http://bauhaus/ fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[interne.insee.fr].zone=interne @@ -29,7 +29,7 @@ fr.insee.rmes.bauhaus.sesame.publication.sesameServer = XXX fr.insee.rmes.bauhaus.sesame.publication.repository = XXX fr.insee.rmes.bauhaus.sesame.publication.baseURI = http://id.insee.fr/ fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[dmz.insee.fr].zone=dmz -fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[gestion.insee.fr].zone=interne" +fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[gestion.insee.fr].zone=interne # Bdd Sesame de publication interne fr.insee.rmes.bauhaus.sesame.publication.interne.repository = XXX @@ -75,6 +75,7 @@ fr.insee.rmes.bauhaus.dmz.auth-server-url = SECRET # Swagger fr.insee.rmes.bauhaus.api.host = SECRET fr.insee.rmes.bauhaus.api.basepath= XXX +fr.insee.rmes.bauhaus.api.ssl= false # Stockage fr.insee.rmes.bauhaus.storage.document.gestion = XXX diff --git a/src/main/resources/gestion/BauhausActiveModules.txt b/src/main/resources/gestion/BauhausActiveModules.txt deleted file mode 100644 index 28910b869..000000000 --- a/src/main/resources/gestion/BauhausActiveModules.txt +++ /dev/null @@ -1,5 +0,0 @@ -concepts -classifications -operations -structures -habilitations \ No newline at end of file diff --git a/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh b/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh index 941a23ff1..55d1a8a42 100644 --- a/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh +++ b/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh @@ -3,11 +3,11 @@ FROM <${OPERATIONS_GRAPH}> WHERE { { ?series dc:creator ?creators . - VALUES ?series { <${URI_SERIES}>} + VALUES ?series { ${URI_SERIES?no_esc}} } UNION { ?series dc:creator ?creators . - ?series dcterms:hasPart <${URI_SERIES}> + ?series dcterms:hasPart ${URI_SERIES?no_esc} } } \ No newline at end of file diff --git a/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml b/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml index 07fbe5cf2..91670c72a 100644 --- a/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml +++ b/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml @@ -1,35 +1,21 @@ + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" + office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" + office:version="1.2"> diff --git a/src/main/resources/xslTransformerFiles/dico-codes.xsl b/src/main/resources/xslTransformerFiles/dico-codes.xsl index 481520fda..281bbc511 100644 --- a/src/main/resources/xslTransformerFiles/dico-codes.xsl +++ b/src/main/resources/xslTransformerFiles/dico-codes.xsl @@ -1,8 +1,7 @@ - + diff --git a/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml b/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml index ac084d6d5..6e0c44862 100644 --- a/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml +++ b/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml @@ -1,33 +1,20 @@ - + - + - + - + - + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" + office:version="1.2"> + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + office:version="1.2"> diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java index de1df553d..69edeeabb 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java @@ -1,8 +1,10 @@ package fr.insee.rmes.bauhaus_services; -import java.util.ArrayList; -import java.util.List; - +import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; +import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.model.links.OperationsLink; +import fr.insee.rmes.model.operations.Indicator; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Assertions; @@ -12,11 +14,8 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; -import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.model.links.OperationsLink; -import fr.insee.rmes.model.operations.Indicator; +import java.util.ArrayList; +import java.util.List; class IndicatorsUtilsTest { @@ -49,8 +48,6 @@ public void init() { } - //getCodeListByNotation// - @Test void givenBuildIndicatorFromJson_whenCorrectRequest_thenResponseIsOk() throws RmesException { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java index 2a56e257e..01379eca2 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java @@ -27,7 +27,7 @@ @TestPropertySource(properties = { "fr.insee.rmes.bauhaus.keycloak.client.secret = XXX", "fr.insee.rmes.bauhaus.keycloak.client.id = XXX", - "fr.insee.rmes.bauhaus.auth-server-url= keycloak.interne", + "fr.insee.rmes.bauhaus.auth-server-url = keycloak.interne", "fr.insee.rmes.bauhaus.keycloak.client.dmz.secret = XXX", "fr.insee.rmes.bauhaus.keycloak.client.dmz.id = XXX", "fr.insee.rmes.bauhaus.dmz.auth-server-url = keycloak.dmz", @@ -42,7 +42,6 @@ class KeycloakServicesTest { @Autowired private KeycloakServicesStub keycloakServices; - private Token token; @Test void nowPlus1Second() { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java index 8f6fed947..1b746acd7 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java @@ -1,26 +1,21 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import org.apache.http.HttpStatus; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.operations.ParentUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.model.operations.documentations.DocumentationRubric; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; class DocumentationsUtilsTest { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java index 55833190b..b80bcfaa4 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java @@ -11,7 +11,6 @@ import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java new file mode 100644 index 000000000..886db7f3b --- /dev/null +++ b/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java @@ -0,0 +1,62 @@ +package fr.insee.rmes.bauhaus_services.stamps; + +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryUtils; +import fr.insee.rmes.config.ConfigStub; +import fr.insee.rmes.config.auth.UserProvider; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class StampsRestrictionServiceImplTest { + + String timbre = "FR01-XXX"; + @Mock + private RepositoryGestion repoGestion; + @Mock + private UserProvider userProvider; + private final IRI iriToCheck = SimpleValueFactory.getInstance().createIRI("http://bauhaus/operations/serie/s2132"); + + @BeforeAll + static void activateTraceLevel() throws URISyntaxException { + var logbackConfigFilePath = Path.of(StampsRestrictionServiceImplTest.class + .getClassLoader() + .getResource(".") + .toURI()) + .resolve("logback-test-trace.xml"); + + System.setProperty("logback.configurationFile", logbackConfigFilePath.toString()); + } + + @BeforeAll + static void configureOpSeriesQueries() { + OpSeriesQueries.setConfig(new ConfigStub()); + } + + @Test + void isSeriesManager_OK_whenStampIsManager() throws RmesException { + var owners=new JSONArray("[{\"creators\":\""+timbre+"\"}]"); + when(repoGestion.getResponseAsArray(anyString())).thenReturn(owners); + when(userProvider.findUserDefaultToEmpty()).thenReturn(new User("", List.of(), timbre)); + var stampsRestrictionServiceImpl = new StampsRestrictionServiceImpl(repoGestion, null, userProvider); + assertTrue(stampsRestrictionServiceImpl.isSeriesManager(this.iriToCheck)); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/rmes/config/ConfigStub.java b/src/test/java/fr/insee/rmes/config/ConfigStub.java new file mode 100644 index 000000000..62128a720 --- /dev/null +++ b/src/test/java/fr/insee/rmes/config/ConfigStub.java @@ -0,0 +1,29 @@ +package fr.insee.rmes.config; + +public class ConfigStub extends Config { + + @Override + public String getLg2() { + return "en"; + } + + @Override + public String getLg1() { + return "fr"; + } + + @Override + public String getOperationsGraph() { + return "http://rdf.insee.fr/graphes/operations"; + } + + @Override + public String getOrganizationsGraph() { + return "http://rdf.insee.fr/graphes/organisations"; + } + + @Override + public String getOrgInseeGraph() { + return "http://rdf.insee.fr/graphes/organisations/insee"; + } +} diff --git a/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java b/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java new file mode 100644 index 000000000..c30118ebe --- /dev/null +++ b/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java @@ -0,0 +1,142 @@ +package fr.insee.rmes.config.auth.security; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.OutputStreamAppender; +import com.nimbusds.jose.shaded.json.JSONArray; +import com.nimbusds.jose.shaded.json.JSONObject; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.LOG_INFO_DEFAULT_STAMP; +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.TIMBRE_ANONYME; +import static org.assertj.core.api.Assertions.assertThat; + +class OpenIDConnectSecurityContextTest { + + private static final ByteArrayOutputStream logOutputStream=new ByteArrayOutputStream(); + private static final String idep = "zzzzzz"; + private static final String timbre="DR59-SNDI"; + private static final List roles = List.of("role1", "role2", "role3", "role4", "role5"); + + private static final JSONArray rolesOfAccount=initJsonArray("manage-account", + "manage-account-links", + "view-profile"); + + private static final JSONArray allowedOrigins = initJsonArray("https://gestion-metadonnees.insee.fr", + "https://preprod.gestion-metadonnees.insee.fr", + "https://test-gestion-metadonnees.insee.fr"); + + private static final JSONArray rolesOfJwt = initJsonArray(roles); + + private static final JSONArray rolesOfRealmAccess = rolesOfJwt; + + private static final Map jwtDecoded=initJwtDecoded(); + + + private static JSONArray initJsonArray(List elements) { + var retour=new JSONArray(); + retour.addAll(elements); + return retour; + } + + private static JSONArray initJsonArray(String... elements) { + return initJsonArray(List.of(elements)); + } + + private static Map initJwtDecoded() { + Map retour =new HashMap<>(); + retour.put("sub", "f:fblabbalbalba:ZZZZZZ"); + retour.put("resource_access", new JSONObject(Map.of( + "account", new JSONObject(Map.of( + "roles", rolesOfAccount) + ) + ))); + retour.put("matricule", "0000000000054"); + retour.put("allowed-origins", allowedOrigins); + retour.put("roles", rolesOfJwt); + retour.put("iss", "https://blabla.fr/a/r/a"); + retour.put("typ", "Bearer"); + retour.put("preferred_username", idep); + retour.put("given_name", "Fabrice"); + retour.put("sid", "c3000000-0000-0000-0000-000000000"); + retour.put("aud", List.of("account")); + retour.put("timbre", timbre); + retour.put("realm_access", new JSONObject(Map.of("roles", rolesOfRealmAccess))); + retour.put("idminefi", "1010101010101"); + retour.put("azp", "blblblblbl-frontend"); + retour.put("auth_time", 1693372846); + retour.put("scope", "insee-timbre-matricule"); + retour.put("name", "Fabrice Vivonne"); + retour.put("exp", "Wed Aug 30 15,15,33 CEST 2023"); + retour.put("session_state", "c000000-0000-0000-0000-00000000000"); + retour.put("iat", "Wed Aug 30 15,10,33 CEST 2023"); + retour.put("family_name", "Vivonne"); + retour.put("jti", "000000-0000-0000-0000-000000000"); + retour.put("email", "fabrice.vivonne@insee.fr"); + return retour; + } + + @BeforeAll + static void configureLog4j(){ + LoggerContext context = ((LoggerContext) LoggerFactory.getILoggerFactory()); + addAppenderToOidcSecurityContextLogger(createOutputStreamAppender(context), context); + } + + private static void addAppenderToOidcSecurityContextLogger(Appender appender, LoggerContext context) { + var oidcSecurityContextLogger = context.getLogger(OpenIDConnectSecurityContext.class); + oidcSecurityContextLogger.setLevel(Level.INFO); + oidcSecurityContextLogger.addAppender(appender); + } + + @NotNull + private static Appender createOutputStreamAppender(LoggerContext context) { + PatternLayoutEncoder ple=new PatternLayoutEncoder(); + ple.setPattern("%msg"); + ple.setContext(context); + ple.start(); + var appender = new OutputStreamAppender(); + appender.setContext(context); + appender.setEncoder(ple); + appender.setOutputStream(logOutputStream); + appender.start(); + + return appender; + } + + @Test + void testJwt() throws RmesException { + var oidcContext = new OpenIDConnectSecurityContext("timbre", "realm_access", "preferred_username", false, "roles"); + + User user = oidcContext.buildUserFromToken(jwtDecoded); + assertThat(user.id()).isEqualTo(idep); + assertThat(user.getStamp()).isEqualTo(timbre); + assertThat(user.roles()).isEqualTo(roles); + } + + @Test + void testJwt_sansTimbre() throws RmesException { + logOutputStream.reset(); + + var oidcContext = new OpenIDConnectSecurityContext( "timbr", "realm_access", "preferred_username", false, "roles"); + + User user = oidcContext.buildUserFromToken(jwtDecoded); + assertThat(user.id()).isEqualTo(idep); + assertThat(user.getStamp()).isEqualTo(TIMBRE_ANONYME); + assertThat(user.roles()).isEqualTo(roles); + assertThat(logOutputStream.toString().trim()).hasToString(String.format(LOG_INFO_DEFAULT_STAMP.replace("{}", "%s"), idep)); + logOutputStream.reset(); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java new file mode 100644 index 000000000..25c7cc958 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java @@ -0,0 +1,65 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.roles.UserRolesManagerService; +import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.external_services.authentication.stamps.StampsService; +import fr.insee.rmes.webservice.PublicResources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.stream.Stream; + +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.PUBLIC_RESOURCES_ANT_PATTERNS; +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@WebMvcTest(controllers= PublicResources.class, + properties = {"fr.insee.rmes.bauhaus.env=PROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM, + "logging.level.org.springframework.security=DEBUG", + "logging.level.org.springframework.security.web.access=TRACE", + "logging.level.fr.insee.rmes.config.auth=TRACE"}) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + CommonSecurityConfiguration.class, + UserProviderFromSecurityContext.class}) +class PublicResourcesAuthorizationsTest { + + @Autowired + private MockMvc mvc; + + @MockBean + private StampsService stampsService; + + @MockBean + private UserRolesManagerService userRolesManagerService; + + public static Stream endpointsProvider() { + return Stream.of(PUBLIC_RESOURCES_ANT_PATTERNS).map(Arguments::of); + } + + @ParameterizedTest + @MethodSource("endpointsProvider") + void ok_withoutAuth(String endpoint) throws Exception { + this.mvc.perform(get(endpoint).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java new file mode 100644 index 000000000..51c23b6d9 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java @@ -0,0 +1,116 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.bauhaus_services.GeographyService; +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.webservice.GeographyResources; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = GeographyResources.class, + properties = {"fr.insee.rmes.bauhaus.env=HORSPROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM + } +) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + UserProviderFromSecurityContext.class}) +class TestGeographyResourcesAuthorizationsEnvHorsProd { + + @Autowired + private MockMvc mvc; + + @MockBean + private GeographyService geographyService; + + @MockBean + private JwtDecoder jwtDecoder; + + private final String idep = "xxxxux"; + private final String timbre = "XX59-YYY"; + + @Test + void getTerritoriesAuthentified_ok() throws Exception { + String idep = "xxxxux"; + String timbre = "XX59-YYY"; + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(get("/geo/territories").header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void getTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(get("/geo/territories") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(post("/geo/territory") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(options("/geo/territory") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java new file mode 100644 index 000000000..7fdc0e2a6 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java @@ -0,0 +1,129 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.bauhaus_services.GeographyService; +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.webservice.GeographyResources; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = GeographyResources.class, + properties = {"fr.insee.rmes.bauhaus.env=PROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM, + "logging.level.org.springframework.security=DEBUG", + "logging.level.org.springframework.security.web.access=TRACE", + "logging.level.fr.insee.rmes.config.auth=TRACE"} +) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + CommonSecurityConfiguration.class, + UserProviderFromSecurityContext.class}) +class TestGeographyResourcesAuthorizationsEnvProd { + + @Autowired + private MockMvc mvc; + + @MockBean + private GeographyService geographyService; + + @MockBean + private JwtDecoder jwtDecoder; + + private final String idep = "xxxxux"; + private final String timbre = "XX59-YYY"; + + + @Test + void getTerritoriesAuthentified_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(get("/geo/territories").header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void getTerritoriesUnauthentified_401() throws Exception { + mvc.perform(get("/geo/territories") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @Test + void postTerritoriesUnauthentified_401() throws Exception { + mvc.perform(post("/geo/territory") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isUnauthorized()); + } + + @Test + void postTerritoriesNoAdmin_403() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isForbidden()); + + } + + @Test + void postTerritoriesAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + + mvc.perform(post("/geo/territory").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(options("/geo/territory") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesAsAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java b/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java new file mode 100644 index 000000000..b3aeeac4a --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java @@ -0,0 +1,38 @@ +package fr.insee.rmes.integration.authorizations; + +import com.nimbusds.jose.shaded.json.JSONArray; +import com.nimbusds.jose.shaded.json.JSONObject; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +public class TokenForTestsConfiguration { + + public static final String ROLE_CLAIM = "realm_access"; + public static final String KEY_FOR_ROLES_IN_ROLE_CLAIM = "roles"; + public static final String STAMP_CLAIM = "timbre"; + public static final String ID_CLAIM = "preferred_username"; + + public static void configureJwtDecoderMock(JwtDecoder jwtDecoderMock, String idep, String timbre, List roles) { + when(jwtDecoderMock.decode(anyString())).then(invocation -> Jwt.withTokenValue(invocation.getArgument(0)) + .header("typ", "JWT") + .header("alg", "none") + .claim(ID_CLAIM, idep) + .claim(STAMP_CLAIM, timbre) + .claim(ROLE_CLAIM, jsonRoles(roles)) + .build()); + } + + private static JSONObject jsonRoles(List roles) { + var jsonObject = new JSONObject(); + var jsonArray=new JSONArray(); + jsonArray.addAll(roles); + jsonObject.put(KEY_FOR_ROLES_IN_ROLE_CLAIM, jsonArray); + return jsonObject; + } + +} diff --git a/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java b/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java new file mode 100644 index 000000000..d6bd45e12 --- /dev/null +++ b/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java @@ -0,0 +1,58 @@ +package fr.insee.rmes.persistance.sparql_queries.operations.series; + +import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.UriUtils; +import fr.insee.rmes.config.ConfigStub; +import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.IRI; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static fr.insee.rmes.utils.StringUtils.urisAsString; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +class OpSeriesQueriesTest { + + public static final String SERIES_BASE_URI="operations/serie"; + + private String actualRequest; + + + @Test + void getCreatorsBySeriesUri_requestIsWellGenerated() { + var id="s2132"; + prepareRdfUtils(); + prepareGenericQueries(); + List uris=List.of(RdfUtils.objectIRI(ObjectType.SERIES,id)); + String expectedGeneratedQuery= """ + SELECT ?creators\s + FROM + WHERE { + { + ?series dc:creator ?creators . + VALUES ?series {
+ * consumes: - application/json + *
+ * produces: - application/json */ @RestController @RequestMapping("/") -@Tag(name="Application", description="Application API") -@ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "400", description = "Bad Request"), - @ApiResponse(responseCode = "401", description = "Unauthorized"), - @ApiResponse(responseCode = "403", description = "Forbidden"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "406", description = "Not Acceptable"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) -public class PublicResources extends GenericResources { +@Tag(name = "Application", description = "Application API") +@ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Success"), + @ApiResponse(responseCode = "204", description = "No Content"), + @ApiResponse(responseCode = "400", description = "Bad Request"), + @ApiResponse(responseCode = "401", description = "Unauthorized"), + @ApiResponse(responseCode = "403", description = "Forbidden"), + @ApiResponse(responseCode = "404", description = "Not found"), + @ApiResponse(responseCode = "406", description = "Not Acceptable"), + @ApiResponse(responseCode = "500", description = "Internal server error")}) +public class PublicResources extends GenericResources { - static final Logger logger = LogManager.getLogger(PublicResources.class); + static final Logger logger = LoggerFactory.getLogger(PublicResources.class); - @Autowired - UserRolesManagerService userRolesManagerService; - - @Autowired - StampsService stampsService; + private final UserRolesManagerService userRolesManagerService; - @GetMapping(value = "/init", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getInit", summary = "Initial properties", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Init.class)))}) - public ResponseEntity getProperties() throws RmesException { - JSONObject props = new JSONObject(); - try { - props.put("appHost", config.getAppHost()); - props.put("authorizationHost", config.getSugoiUi()); - props.put("defaultContributor", config.getDefaultContributor()); - props.put("defaultMailSender", config.getDefaultMailSender()); - props.put("maxLengthScopeNote", config.getMaxLengthScopeNote()); - props.put("lg1", config.getLg1()); - props.put("lg2", config.getLg2()); - props.put("authType", AuthType.getAuthType(config)); - props.put("modules", getActiveModules()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR,e.getMessage(),e.getClass().getSimpleName()); - } - return ResponseEntity.status(HttpStatus.SC_OK).body(props.toString()); - } + private final StampsService stampsService; + private final String env; + private final String lg2; + private final String lg1; + private final String maxLengthScopeNote; + private final String defaultMailSender; + private final String defaultContributor; + private final String sugoiUi; + private final String appHost; + private final List activeModules; - private List getActiveModules() { - String dirPath = config.getDocumentsStorageGestion() + "/BauhausActiveModules.txt"; - File file = new File(dirPath); + public PublicResources(@Autowired UserRolesManagerService userRolesManagerService, + @Autowired StampsService stampsService, + @Value("${fr.insee.rmes.bauhaus.env}") String env, + @Value("${fr.insee.rmes.bauhaus.lg1}") String lg2, + @Value("${fr.insee.rmes.bauhaus.lg2}") String lg1, + @Value("${fr.insee.rmes.bauhaus.concepts.maxLengthScopeNote}") String maxLengthScopeNote, + @Value("${fr.insee.rmes.bauhaus.concepts.defaultMailSender}") String defaultMailSender, + @Value("${fr.insee.rmes.bauhaus.concepts.defaultContributor}") String defaultContributor, + @Value("${fr.insee.rmes.bauhaus.sugoi.ui}") String sugoiUi, + @Value("${fr.insee.rmes.bauhaus.appHost}") String appHost, + @Value("${fr.insee.rmes.bauhaus.activeModules}") List activeModules) { + this.userRolesManagerService = userRolesManagerService; + this.stampsService = stampsService; + this.env = env; + this.lg2 = lg2; + this.lg1 = lg1; + this.maxLengthScopeNote = maxLengthScopeNote; + this.defaultMailSender = defaultMailSender; + this.defaultContributor = defaultContributor; + this.sugoiUi = sugoiUi; + this.appHost = appHost; + this.activeModules=activeModules; + } + + @GetMapping(value = "/init", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getInit", summary = "Initial properties", responses = {@ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Init.class)))}) + public ResponseEntity getProperties() throws RmesException { + JSONObject props = new JSONObject(); try { - return FileUtils.readLines(file, StandardCharsets.UTF_8);//Read lines in a list - } catch (IOException e) { - logger.error(e.getMessage(), e); - return new ArrayList<>(); - } - } + props.put("appHost", this.appHost); + props.put("authorizationHost", this.sugoiUi); + props.put("defaultContributor", this.defaultContributor); + props.put("defaultMailSender", this.defaultMailSender); + props.put("maxLengthScopeNote", this.maxLengthScopeNote); + props.put("lg1", this.lg1); + props.put("lg2", this.lg2); + props.put("authType", AuthType.getAuthType(this.env)); + props.put("modules", this.activeModules); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e.getClass().getSimpleName()); + } + return ResponseEntity.status(HttpStatus.SC_OK).body(props.toString()); + } - @GetMapping(value = "/stamps", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getStamps", summary = "List of stamps", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) - public ResponseEntity getStamps() { - try { - return ResponseEntity.status(HttpStatus.SC_OK).body(stampsService.getStamps()); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - } + @GetMapping(value = "/stamps", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getStamps", summary = "List of stamps", responses = {@ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) + public ResponseEntity getStamps() { + try { + return ResponseEntity.status(HttpStatus.SC_OK).body(stampsService.getStamps()); + } catch (RmesException e) { + return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + } + } - @GetMapping(value = "/disseminationStatus", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getDisseminationStatus", summary = "List of dissemination status", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=LabelUrl.class))))}) - public ResponseEntity getDisseminationStatus() { - TreeSet dsList = new TreeSet<>(); - for (DisseminationStatus ds : DisseminationStatus.values()) { - try { - dsList.add(new ObjectMapper().writeValueAsString(ds)); - } catch (JsonProcessingException e) { - return ResponseEntity.status(500).body(e.getMessage()); - } - } - return ResponseEntity.status(HttpStatus.SC_OK).body(dsList.toString()); - } + @GetMapping(value = "/disseminationStatus", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getDisseminationStatus", summary = "List of dissemination status", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LabelUrl.class))))}) + public ResponseEntity getDisseminationStatus() { + TreeSet dsList = new TreeSet<>(); + for (DisseminationStatus ds : DisseminationStatus.values()) { + try { + dsList.add(new ObjectMapper().writeValueAsString(ds)); + } catch (JsonProcessingException e) { + return ResponseEntity.status(500).body(e.getMessage()); + } + } + return ResponseEntity.status(HttpStatus.SC_OK).body(dsList.toString()); + } - @GetMapping(value = "/roles", produces = MediaType.APPLICATION_JSON_VALUE) - @Operation(operationId = "getRoles", summary = "List of roles", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=Roles.class))))}) - public ResponseEntity getRoles() { - String entity = null; - try { - entity = userRolesManagerService.getRoles(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.SC_OK).body(entity); - } + @GetMapping(value = "/roles", produces = MediaType.APPLICATION_JSON_VALUE) + @Operation(operationId = "getRoles", summary = "List of roles", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Roles.class))))}) + public ResponseEntity getRoles() { + String entity = null; + try { + entity = userRolesManagerService.getRoles(); + } catch (RmesException e) { + return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + } + return ResponseEntity.status(HttpStatus.SC_OK).body(entity); + } } \ No newline at end of file diff --git a/src/main/java/fr/insee/rmes/webservice/StructureResources.java b/src/main/java/fr/insee/rmes/webservice/StructureResources.java index bb0448ba9..f895208ca 100644 --- a/src/main/java/fr/insee/rmes/webservice/StructureResources.java +++ b/src/main/java/fr/insee/rmes/webservice/StructureResources.java @@ -1,21 +1,5 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -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.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.structures.StructureComponent; import fr.insee.rmes.bauhaus_services.structures.StructureService; @@ -31,6 +15,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/structures") @@ -47,7 +39,7 @@ @ApiResponse(responseCode = "500", description = "Internal server error")}) public class StructureResources extends GenericResources { - static final Logger logger = LogManager.getLogger(StructureResources.class); + static final Logger logger = LoggerFactory.getLogger(StructureResources.class); @Autowired StructureService structureService; @@ -97,7 +89,7 @@ public ResponseEntity getStructureById(@PathVariable(Constants.ID) Strin } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/structure/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishStructureById", summary = "Publish a structure") public ResponseEntity publishStructureById(@PathVariable(Constants.ID) String id) { @@ -121,7 +113,7 @@ public ResponseEntity getStructureByIdDetails(@PathVariable(Constants.ID } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/structure", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setStructure", summary = "Create a structure") @@ -135,7 +127,7 @@ public ResponseEntity setStructure( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/structure/{structureId}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setStructure", summary = "Update a structure") @@ -150,7 +142,7 @@ public ResponseEntity setStructure( } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping("/structure/{structureId}") @Operation(operationId = "deleteStructure", summary = "Delete a structure") public ResponseEntity deleteStructure(@PathVariable("structureId") String structureId) { @@ -206,7 +198,7 @@ public ResponseEntity getComponentById(@PathVariable(Constants.ID) Strin } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/components/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishComponentById", summary = "Publish a component") public ResponseEntity publishComponentById(@PathVariable(Constants.ID) String id) { @@ -218,7 +210,7 @@ public ResponseEntity publishComponentById(@PathVariable(Constants.ID) S } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/components/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteComponentById", summary = "delete a mutualized component") public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) String id) { @@ -230,7 +222,7 @@ public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) St } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping(value = "/components/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "updateComponent", summary = "Update a component") @@ -244,7 +236,7 @@ public ResponseEntity updateComponentById(@PathVariable(Constants.ID) St } } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/components", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "createComponent", summary = "create a component") diff --git a/src/main/java/fr/insee/rmes/webservice/TokenApi.java b/src/main/java/fr/insee/rmes/webservice/TokenApi.java index 606f8cc06..bbec0db94 100644 --- a/src/main/java/fr/insee/rmes/webservice/TokenApi.java +++ b/src/main/java/fr/insee/rmes/webservice/TokenApi.java @@ -2,8 +2,8 @@ import fr.insee.rmes.bauhaus_services.keycloak.KeycloakServices; import fr.insee.rmes.exceptions.RmesException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +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; @@ -19,10 +19,10 @@ public class TokenApi extends GenericResources { protected KeycloakServices keycloakServices; - private static final Logger logger = LogManager.getLogger(TokenApi.class); + private static final Logger logger = LoggerFactory.getLogger(TokenApi.class); - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @GetMapping(value = "/{rdfServerUrl}") public String getToken(@PathVariable String rdfServerUrl) throws RmesException { logger.info("GET /token"); diff --git a/src/main/java/fr/insee/rmes/webservice/UserResources.java b/src/main/java/fr/insee/rmes/webservice/UserResources.java index 0e7bd7166..5e222c411 100644 --- a/src/main/java/fr/insee/rmes/webservice/UserResources.java +++ b/src/main/java/fr/insee/rmes/webservice/UserResources.java @@ -1,23 +1,7 @@ package fr.insee.rmes.webservice; -import org.apache.http.HttpStatus; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import fr.insee.rmes.config.auth.roles.UserRolesManagerService; -import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService; +import fr.insee.rmes.config.auth.user.Stamp; import fr.insee.rmes.config.auth.user.User; -import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.external_services.authentication.stamps.StampsService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -27,6 +11,14 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; +import org.apache.http.HttpStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.*; /** * WebService class for resources of Concepts @@ -56,38 +48,37 @@ @ApiResponse(responseCode = "500", description = "Internal server error") }) public class UserResources extends GenericResources { - static final Logger logger = LogManager.getLogger(UserResources.class); + static final Logger logger = LoggerFactory.getLogger(UserResources.class); + + private final StampsService stampsService; - @Autowired - UserRolesManagerService userRolesManagerService; - - @Autowired - StampsService stampsService; @Autowired - StampsRestrictionsService stampsRestrictionService; + public UserResources(StampsService stampsService) { + this.stampsService = stampsService; + } @GetMapping(value = "/stamp", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getStamp", summary = "User's stamp", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class)))}) - public ResponseEntity getStamp() { - String stamp = null; + public ResponseEntity getStamp(@AuthenticationPrincipal Object principal) { + Stamp stamp; try { - stamp = stampsService.getStamp(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); + stamp = stampsService.findStampFrom(principal); + } catch (Exception e) { + logger.error("exception while retrieving stamp",e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).body("exception while retrieving stamp"); } return ResponseEntity.status(HttpStatus.SC_OK).body(stamp); } + @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "login", summary = "Fake Login", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class)))}) public ResponseEntity login( - @Parameter(description = "Component", required = true) @RequestBody String user) - throws JsonProcessingException { - stampsRestrictionService.setFakeUser(user); - return ResponseEntity.status(HttpStatus.SC_OK).build(); + @Parameter(description = "Component", required = true) @RequestBody String user) { + throw new RuntimeException("Deprecated to be removed: noop"); } diff --git a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java index a9b4b1656..1f5853644 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java @@ -1,18 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabel; import fr.insee.rmes.exceptions.RmesException; @@ -25,6 +12,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; /*************************************************************************************************** @@ -75,7 +68,7 @@ public ResponseEntity getFamilyByID(@PathVariable(Constants.ID) String i return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(jsonResultat); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/family/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyById", summary = "Update an existing family" ) public ResponseEntity setFamilyById( @@ -90,7 +83,7 @@ public ResponseEntity setFamilyById( } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping("/family") @io.swagger.v3.oas.annotations.Operation(operationId = "createFamily", summary = "Create a new family") public ResponseEntity createFamily( @@ -105,7 +98,7 @@ public ResponseEntity createFamily( return ResponseEntity.status(HttpStatus.OK).body(id); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PutMapping("/family/validate/{id}") @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyValidation", summary = "Validate a family") public ResponseEntity setFamilyValidation( diff --git a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java index f2afe287c..5d3557759 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java @@ -1,19 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; @@ -26,6 +12,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @Qualifier("Indicator") @@ -91,7 +83,8 @@ public ResponseEntity getIndicatorByID(@PathVariable(Constants.ID) Strin * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + //TODO Test : admin then INDICATOR_CONTRIBUTOR with stamp fit then not + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PutMapping(value="/indicator/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicatorById", summary = "Update indicator") public ResponseEntity setIndicatorById( @@ -111,7 +104,7 @@ public ResponseEntity setIndicatorById( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PutMapping(value="/indicator/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicatorValidation", summary = "Indicator validation") public ResponseEntity setIndicatorValidation( @@ -129,7 +122,7 @@ public ResponseEntity setIndicatorValidation( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") @PostMapping(value="/indicator", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicator", summary = "Create indicator", responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) diff --git a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java index 875475e02..cd33f3148 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java @@ -173,7 +173,7 @@ public ResponseEntity getMetadataReportOwner(@PathVariable(Constants.ID) * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() || @AuthorizeMethodDecider.isIndicatorContributor() || @AuthorizeMethodDecider.isSeriesContributor()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN || T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR || T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PostMapping(value = "/metadataReport", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReport", summary = "Create metadata report", responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) @@ -197,10 +197,10 @@ public ResponseEntity setMetadataReport( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/metadataReport/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReportById", summary = "Update metadata report") public ResponseEntity setMetadataReportById( @@ -220,7 +220,7 @@ public ResponseEntity setMetadataReportById( * @param id * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @DeleteMapping(value = "/metadataReport/delete/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "deleteMetadataReportById", summary = "Delete metadata report") public ResponseEntity deleteMetadataReportById( @@ -241,9 +241,9 @@ public ResponseEntity deleteMetadataReportById( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isIndicatorContributor() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/metadataReport/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setMetadataReportValidation", summary = "Sims validation") public ResponseEntity setSimsValidation( diff --git a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java index ad76223e7..2dd628f97 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java @@ -181,8 +181,8 @@ public ResponseEntity> getCodeBookCheck( * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/operation/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setOperationById", summary = "Update operation") public ResponseEntity setOperationById(@PathVariable(Constants.ID) String id, @@ -201,7 +201,7 @@ public ResponseEntity setOperationById(@PathVariable(Constants.ID) Strin * @param body * @return */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PostMapping(value = "/operation", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createOperation", summary = "Create operation") public ResponseEntity createOperation( @@ -221,7 +221,7 @@ public ResponseEntity createOperation( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/operation/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setOperationValidation", summary = "Operation validation") public ResponseEntity setOperationValidation(@PathVariable(Constants.ID) String id) throws RmesException { diff --git a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java index 321196ad2..51ab91ea2 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java @@ -1,19 +1,5 @@ package fr.insee.rmes.webservice.operations; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; @@ -27,6 +13,12 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; @Qualifier("Series") @@ -105,9 +97,9 @@ public ResponseEntity getSeriesForSearchWithStamps(@Parameter( return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); } - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() " - + "|| @AuthorizeMethodDecider.isCnis()") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR " + + ", T(fr.insee.rmes.config.auth.roles.Roles).CNIS)") @PutMapping(value = "/series/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setSeriesById", summary = "Update series") @@ -153,7 +145,7 @@ public ResponseEntity getOperationsWithReport(@PathVariable(Constants.ID * @param body * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/series", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createSeries", summary = "Create series") @@ -174,8 +166,8 @@ public ResponseEntity createSeries( * @param id * @return response */ - @PreAuthorize("@AuthorizeMethodDecider.isAdmin() " - + "|| @AuthorizeMethodDecider.isSeriesContributor() ") + @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") @PutMapping(value = "/series/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setSeriesValidation", summary = "Series validation") diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 572bcb193..6fe0e2f41 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,7 +4,6 @@ spring.config.import=classpath:bauhaus-core.properties,optional:classpath:bauhau spring.servlet.multipart.max-file-size=40MB spring.servlet.multipart.max-request-size=40MB - # Config Swagger (only for display) fr.insee.rmes.bauhaus.version=@project.version@ #springdoc.api-docs.path= @@ -14,3 +13,9 @@ springdoc.swagger-ui.path=/index.html server.servlet.contextPath=/api/ spring.security.oauth2.resourceserver.jwt.issuer-uri=${fr.insee.rmes.bauhaus.auth-server-url} + +# to log exchanges with repo rdf, switch to debug +logging.level.org.apache.http.wire=info +# to log sparql queries and results, switch to trace +logging.level.fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryUtils=info + diff --git a/src/main/resources/bauhaus-core.properties b/src/main/resources/bauhaus-core.properties index 0490ffaa4..82bef0f05 100644 --- a/src/main/resources/bauhaus-core.properties +++ b/src/main/resources/bauhaus-core.properties @@ -10,6 +10,7 @@ fr.insee.rmes.bauhaus.cors.allowedOrigin=* jwt.id-claim = preferred_username jwt.role-claim = realm_access jwt.stamp-claim = timbre +jwt.role-claim.roles = roles fr.insee.rmes.bauhaus.sugoi.application = RMESGNCS fr.insee.rmes.bauhaus.sugoi.realm = SSP @@ -30,6 +31,8 @@ fr.insee.rmes.bauhaus.concepts.maxLengthScopeNote = 350 ############################### fr.insee.rmes.bauhaus.classifications.families.graph = codes/nomenclatures +fr.insee.rmes.bauhaus.activeModules = concepts,classifications,operations,habilitations + ############################### #OPERATIONS ############################### diff --git a/src/main/resources/bauhaus-dev.properties b/src/main/resources/bauhaus-dev.properties index b2196f15e..6ea106459 100644 --- a/src/main/resources/bauhaus-dev.properties +++ b/src/main/resources/bauhaus-dev.properties @@ -18,7 +18,7 @@ fr.insee.rmes.bauhaus.rdf.auth=ENABLED #HorsProd = /opt/tomcat9/logs/rmesgncs.log # Bdd Sesame de gestion -fr.insee.rmes.bauhaus.sesame.gestion.sesameServer = +fr.insee.rmes.bauhaus.sesame.gestion.sesameServer = XXX fr.insee.rmes.bauhaus.sesame.gestion.repository = XXX fr.insee.rmes.bauhaus.sesame.gestion.baseURI = http://bauhaus/ fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[interne.insee.fr].zone=interne @@ -29,7 +29,7 @@ fr.insee.rmes.bauhaus.sesame.publication.sesameServer = XXX fr.insee.rmes.bauhaus.sesame.publication.repository = XXX fr.insee.rmes.bauhaus.sesame.publication.baseURI = http://id.insee.fr/ fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[dmz.insee.fr].zone=dmz -fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[gestion.insee.fr].zone=interne" +fr.insee.rmes.bauhaus.keycloak-configuration.zoneByServers.[gestion.insee.fr].zone=interne # Bdd Sesame de publication interne fr.insee.rmes.bauhaus.sesame.publication.interne.repository = XXX @@ -75,6 +75,7 @@ fr.insee.rmes.bauhaus.dmz.auth-server-url = SECRET # Swagger fr.insee.rmes.bauhaus.api.host = SECRET fr.insee.rmes.bauhaus.api.basepath= XXX +fr.insee.rmes.bauhaus.api.ssl= false # Stockage fr.insee.rmes.bauhaus.storage.document.gestion = XXX diff --git a/src/main/resources/gestion/BauhausActiveModules.txt b/src/main/resources/gestion/BauhausActiveModules.txt deleted file mode 100644 index 28910b869..000000000 --- a/src/main/resources/gestion/BauhausActiveModules.txt +++ /dev/null @@ -1,5 +0,0 @@ -concepts -classifications -operations -structures -habilitations \ No newline at end of file diff --git a/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh b/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh index 941a23ff1..55d1a8a42 100644 --- a/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh +++ b/src/main/resources/request/operations/series/getSeriesCreatorsByUriQuery.ftlh @@ -3,11 +3,11 @@ FROM <${OPERATIONS_GRAPH}> WHERE { { ?series dc:creator ?creators . - VALUES ?series { <${URI_SERIES}>} + VALUES ?series { ${URI_SERIES?no_esc}} } UNION { ?series dc:creator ?creators . - ?series dcterms:hasPart <${URI_SERIES}> + ?series dcterms:hasPart ${URI_SERIES?no_esc} } } \ No newline at end of file diff --git a/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml b/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml index 07fbe5cf2..91670c72a 100644 --- a/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml +++ b/src/main/resources/xslTransformerFiles/collection/collectionEnPatternContent.xml @@ -1,35 +1,21 @@ + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" + office:version="1.3"> + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" + office:version="1.2"> diff --git a/src/main/resources/xslTransformerFiles/dico-codes.xsl b/src/main/resources/xslTransformerFiles/dico-codes.xsl index 481520fda..281bbc511 100644 --- a/src/main/resources/xslTransformerFiles/dico-codes.xsl +++ b/src/main/resources/xslTransformerFiles/dico-codes.xsl @@ -1,8 +1,7 @@ - + diff --git a/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml b/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml index ac084d6d5..6e0c44862 100644 --- a/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml +++ b/src/main/resources/xslTransformerFiles/dicoCodes/dicoConcisDescrPatternContent.xml @@ -1,33 +1,20 @@ - + - + - + - + - + xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" + xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" + xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" + xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" + xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" + xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" + xmlns:officeooo="http://openoffice.org/2009/office" + office:version="1.2"> + xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" + xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" + xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" + xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" + xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" + office:version="1.2"> diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java index de1df553d..69edeeabb 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/IndicatorsUtilsTest.java @@ -1,8 +1,10 @@ package fr.insee.rmes.bauhaus_services; -import java.util.ArrayList; -import java.util.List; - +import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; +import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.model.links.OperationsLink; +import fr.insee.rmes.model.operations.Indicator; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Assertions; @@ -12,11 +14,8 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import fr.insee.rmes.bauhaus_services.operations.famopeserind_utils.FamOpeSerIndUtils; -import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; -import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.model.links.OperationsLink; -import fr.insee.rmes.model.operations.Indicator; +import java.util.ArrayList; +import java.util.List; class IndicatorsUtilsTest { @@ -49,8 +48,6 @@ public void init() { } - //getCodeListByNotation// - @Test void givenBuildIndicatorFromJson_whenCorrectRequest_thenResponseIsOk() throws RmesException { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java index 2a56e257e..01379eca2 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/keycloak/KeycloakServicesTest.java @@ -27,7 +27,7 @@ @TestPropertySource(properties = { "fr.insee.rmes.bauhaus.keycloak.client.secret = XXX", "fr.insee.rmes.bauhaus.keycloak.client.id = XXX", - "fr.insee.rmes.bauhaus.auth-server-url= keycloak.interne", + "fr.insee.rmes.bauhaus.auth-server-url = keycloak.interne", "fr.insee.rmes.bauhaus.keycloak.client.dmz.secret = XXX", "fr.insee.rmes.bauhaus.keycloak.client.dmz.id = XXX", "fr.insee.rmes.bauhaus.dmz.auth-server-url = keycloak.dmz", @@ -42,7 +42,6 @@ class KeycloakServicesTest { @Autowired private KeycloakServicesStub keycloakServices; - private Token token; @Test void nowPlus1Second() { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java index 8f6fed947..1b746acd7 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtilsTest.java @@ -1,26 +1,21 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; -import static org.junit.jupiter.api.Assertions.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import org.apache.http.HttpStatus; -import org.json.JSONException; -import org.json.JSONObject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; - import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.operations.ParentUtils; import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.model.operations.documentations.DocumentationRubric; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; class DocumentationsUtilsTest { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java index 55833190b..b80bcfaa4 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryInitiatorWithAuthentTest.java @@ -11,7 +11,6 @@ import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java new file mode 100644 index 000000000..886db7f3b --- /dev/null +++ b/src/test/java/fr/insee/rmes/bauhaus_services/stamps/StampsRestrictionServiceImplTest.java @@ -0,0 +1,62 @@ +package fr.insee.rmes.bauhaus_services.stamps; + +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryGestion; +import fr.insee.rmes.bauhaus_services.rdf_utils.RepositoryUtils; +import fr.insee.rmes.config.ConfigStub; +import fr.insee.rmes.config.auth.UserProvider; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import fr.insee.rmes.persistance.sparql_queries.operations.series.OpSeriesQueries; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class StampsRestrictionServiceImplTest { + + String timbre = "FR01-XXX"; + @Mock + private RepositoryGestion repoGestion; + @Mock + private UserProvider userProvider; + private final IRI iriToCheck = SimpleValueFactory.getInstance().createIRI("http://bauhaus/operations/serie/s2132"); + + @BeforeAll + static void activateTraceLevel() throws URISyntaxException { + var logbackConfigFilePath = Path.of(StampsRestrictionServiceImplTest.class + .getClassLoader() + .getResource(".") + .toURI()) + .resolve("logback-test-trace.xml"); + + System.setProperty("logback.configurationFile", logbackConfigFilePath.toString()); + } + + @BeforeAll + static void configureOpSeriesQueries() { + OpSeriesQueries.setConfig(new ConfigStub()); + } + + @Test + void isSeriesManager_OK_whenStampIsManager() throws RmesException { + var owners=new JSONArray("[{\"creators\":\""+timbre+"\"}]"); + when(repoGestion.getResponseAsArray(anyString())).thenReturn(owners); + when(userProvider.findUserDefaultToEmpty()).thenReturn(new User("", List.of(), timbre)); + var stampsRestrictionServiceImpl = new StampsRestrictionServiceImpl(repoGestion, null, userProvider); + assertTrue(stampsRestrictionServiceImpl.isSeriesManager(this.iriToCheck)); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/rmes/config/ConfigStub.java b/src/test/java/fr/insee/rmes/config/ConfigStub.java new file mode 100644 index 000000000..62128a720 --- /dev/null +++ b/src/test/java/fr/insee/rmes/config/ConfigStub.java @@ -0,0 +1,29 @@ +package fr.insee.rmes.config; + +public class ConfigStub extends Config { + + @Override + public String getLg2() { + return "en"; + } + + @Override + public String getLg1() { + return "fr"; + } + + @Override + public String getOperationsGraph() { + return "http://rdf.insee.fr/graphes/operations"; + } + + @Override + public String getOrganizationsGraph() { + return "http://rdf.insee.fr/graphes/organisations"; + } + + @Override + public String getOrgInseeGraph() { + return "http://rdf.insee.fr/graphes/organisations/insee"; + } +} diff --git a/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java b/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java new file mode 100644 index 000000000..c30118ebe --- /dev/null +++ b/src/test/java/fr/insee/rmes/config/auth/security/OpenIDConnectSecurityContextTest.java @@ -0,0 +1,142 @@ +package fr.insee.rmes.config.auth.security; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.OutputStreamAppender; +import com.nimbusds.jose.shaded.json.JSONArray; +import com.nimbusds.jose.shaded.json.JSONObject; +import fr.insee.rmes.config.auth.user.User; +import fr.insee.rmes.exceptions.RmesException; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.LOG_INFO_DEFAULT_STAMP; +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.TIMBRE_ANONYME; +import static org.assertj.core.api.Assertions.assertThat; + +class OpenIDConnectSecurityContextTest { + + private static final ByteArrayOutputStream logOutputStream=new ByteArrayOutputStream(); + private static final String idep = "zzzzzz"; + private static final String timbre="DR59-SNDI"; + private static final List roles = List.of("role1", "role2", "role3", "role4", "role5"); + + private static final JSONArray rolesOfAccount=initJsonArray("manage-account", + "manage-account-links", + "view-profile"); + + private static final JSONArray allowedOrigins = initJsonArray("https://gestion-metadonnees.insee.fr", + "https://preprod.gestion-metadonnees.insee.fr", + "https://test-gestion-metadonnees.insee.fr"); + + private static final JSONArray rolesOfJwt = initJsonArray(roles); + + private static final JSONArray rolesOfRealmAccess = rolesOfJwt; + + private static final Map jwtDecoded=initJwtDecoded(); + + + private static JSONArray initJsonArray(List elements) { + var retour=new JSONArray(); + retour.addAll(elements); + return retour; + } + + private static JSONArray initJsonArray(String... elements) { + return initJsonArray(List.of(elements)); + } + + private static Map initJwtDecoded() { + Map retour =new HashMap<>(); + retour.put("sub", "f:fblabbalbalba:ZZZZZZ"); + retour.put("resource_access", new JSONObject(Map.of( + "account", new JSONObject(Map.of( + "roles", rolesOfAccount) + ) + ))); + retour.put("matricule", "0000000000054"); + retour.put("allowed-origins", allowedOrigins); + retour.put("roles", rolesOfJwt); + retour.put("iss", "https://blabla.fr/a/r/a"); + retour.put("typ", "Bearer"); + retour.put("preferred_username", idep); + retour.put("given_name", "Fabrice"); + retour.put("sid", "c3000000-0000-0000-0000-000000000"); + retour.put("aud", List.of("account")); + retour.put("timbre", timbre); + retour.put("realm_access", new JSONObject(Map.of("roles", rolesOfRealmAccess))); + retour.put("idminefi", "1010101010101"); + retour.put("azp", "blblblblbl-frontend"); + retour.put("auth_time", 1693372846); + retour.put("scope", "insee-timbre-matricule"); + retour.put("name", "Fabrice Vivonne"); + retour.put("exp", "Wed Aug 30 15,15,33 CEST 2023"); + retour.put("session_state", "c000000-0000-0000-0000-00000000000"); + retour.put("iat", "Wed Aug 30 15,10,33 CEST 2023"); + retour.put("family_name", "Vivonne"); + retour.put("jti", "000000-0000-0000-0000-000000000"); + retour.put("email", "fabrice.vivonne@insee.fr"); + return retour; + } + + @BeforeAll + static void configureLog4j(){ + LoggerContext context = ((LoggerContext) LoggerFactory.getILoggerFactory()); + addAppenderToOidcSecurityContextLogger(createOutputStreamAppender(context), context); + } + + private static void addAppenderToOidcSecurityContextLogger(Appender appender, LoggerContext context) { + var oidcSecurityContextLogger = context.getLogger(OpenIDConnectSecurityContext.class); + oidcSecurityContextLogger.setLevel(Level.INFO); + oidcSecurityContextLogger.addAppender(appender); + } + + @NotNull + private static Appender createOutputStreamAppender(LoggerContext context) { + PatternLayoutEncoder ple=new PatternLayoutEncoder(); + ple.setPattern("%msg"); + ple.setContext(context); + ple.start(); + var appender = new OutputStreamAppender(); + appender.setContext(context); + appender.setEncoder(ple); + appender.setOutputStream(logOutputStream); + appender.start(); + + return appender; + } + + @Test + void testJwt() throws RmesException { + var oidcContext = new OpenIDConnectSecurityContext("timbre", "realm_access", "preferred_username", false, "roles"); + + User user = oidcContext.buildUserFromToken(jwtDecoded); + assertThat(user.id()).isEqualTo(idep); + assertThat(user.getStamp()).isEqualTo(timbre); + assertThat(user.roles()).isEqualTo(roles); + } + + @Test + void testJwt_sansTimbre() throws RmesException { + logOutputStream.reset(); + + var oidcContext = new OpenIDConnectSecurityContext( "timbr", "realm_access", "preferred_username", false, "roles"); + + User user = oidcContext.buildUserFromToken(jwtDecoded); + assertThat(user.id()).isEqualTo(idep); + assertThat(user.getStamp()).isEqualTo(TIMBRE_ANONYME); + assertThat(user.roles()).isEqualTo(roles); + assertThat(logOutputStream.toString().trim()).hasToString(String.format(LOG_INFO_DEFAULT_STAMP.replace("{}", "%s"), idep)); + logOutputStream.reset(); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java new file mode 100644 index 000000000..25c7cc958 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java @@ -0,0 +1,65 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.roles.UserRolesManagerService; +import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.external_services.authentication.stamps.StampsService; +import fr.insee.rmes.webservice.PublicResources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.stream.Stream; + +import static fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext.PUBLIC_RESOURCES_ANT_PATTERNS; +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@WebMvcTest(controllers= PublicResources.class, + properties = {"fr.insee.rmes.bauhaus.env=PROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM, + "logging.level.org.springframework.security=DEBUG", + "logging.level.org.springframework.security.web.access=TRACE", + "logging.level.fr.insee.rmes.config.auth=TRACE"}) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + CommonSecurityConfiguration.class, + UserProviderFromSecurityContext.class}) +class PublicResourcesAuthorizationsTest { + + @Autowired + private MockMvc mvc; + + @MockBean + private StampsService stampsService; + + @MockBean + private UserRolesManagerService userRolesManagerService; + + public static Stream endpointsProvider() { + return Stream.of(PUBLIC_RESOURCES_ANT_PATTERNS).map(Arguments::of); + } + + @ParameterizedTest + @MethodSource("endpointsProvider") + void ok_withoutAuth(String endpoint) throws Exception { + this.mvc.perform(get(endpoint).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java new file mode 100644 index 000000000..51c23b6d9 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java @@ -0,0 +1,116 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.bauhaus_services.GeographyService; +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.webservice.GeographyResources; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = GeographyResources.class, + properties = {"fr.insee.rmes.bauhaus.env=HORSPROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM + } +) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + UserProviderFromSecurityContext.class}) +class TestGeographyResourcesAuthorizationsEnvHorsProd { + + @Autowired + private MockMvc mvc; + + @MockBean + private GeographyService geographyService; + + @MockBean + private JwtDecoder jwtDecoder; + + private final String idep = "xxxxux"; + private final String timbre = "XX59-YYY"; + + @Test + void getTerritoriesAuthentified_ok() throws Exception { + String idep = "xxxxux"; + String timbre = "XX59-YYY"; + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(get("/geo/territories").header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void getTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(get("/geo/territories") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(post("/geo/territory") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void postTerritoriesAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(options("/geo/territory") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java new file mode 100644 index 000000000..7fdc0e2a6 --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java @@ -0,0 +1,129 @@ +package fr.insee.rmes.integration.authorizations; + +import fr.insee.rmes.bauhaus_services.GeographyService; +import fr.insee.rmes.config.Config; +import fr.insee.rmes.config.auth.UserProviderFromSecurityContext; +import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration; +import fr.insee.rmes.config.auth.security.DefaultSecurityContext; +import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; +import fr.insee.rmes.webservice.GeographyResources; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.List; + +import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(controllers = GeographyResources.class, + properties = {"fr.insee.rmes.bauhaus.env=PROD", + "jwt.stamp-claim=" + STAMP_CLAIM, + "jwt.role-claim=" + ROLE_CLAIM, + "jwt.id-claim=" + ID_CLAIM, + "jwt.role-claim.roles=" + KEY_FOR_ROLES_IN_ROLE_CLAIM, + "logging.level.org.springframework.security=DEBUG", + "logging.level.org.springframework.security.web.access=TRACE", + "logging.level.fr.insee.rmes.config.auth=TRACE"} +) +@Import({Config.class, + OpenIDConnectSecurityContext.class, + DefaultSecurityContext.class, + CommonSecurityConfiguration.class, + UserProviderFromSecurityContext.class}) +class TestGeographyResourcesAuthorizationsEnvProd { + + @Autowired + private MockMvc mvc; + + @MockBean + private GeographyService geographyService; + + @MockBean + private JwtDecoder jwtDecoder; + + private final String idep = "xxxxux"; + private final String timbre = "XX59-YYY"; + + + @Test + void getTerritoriesAuthentified_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(get("/geo/territories").header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void getTerritoriesUnauthentified_401() throws Exception { + mvc.perform(get("/geo/territories") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isUnauthorized()); + } + + @Test + void postTerritoriesUnauthentified_401() throws Exception { + mvc.perform(post("/geo/territory") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isUnauthorized()); + } + + @Test + void postTerritoriesNoAdmin_403() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + mvc.perform(post("/geo/territory") + .header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isForbidden()); + + } + + @Test + void postTerritoriesAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + + mvc.perform(post("/geo/territory").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"}")) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesNoAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("bidon")); + + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesUnauthentified_ok() throws Exception { + mvc.perform(options("/geo/territory") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void optionCreateTerritoriesAsAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("Administrateur_RMESGNCS")); + mvc.perform(options("/geo/territory") + .header("Authorization", "Bearer toto") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + +} diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java b/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java new file mode 100644 index 000000000..b3aeeac4a --- /dev/null +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TokenForTestsConfiguration.java @@ -0,0 +1,38 @@ +package fr.insee.rmes.integration.authorizations; + +import com.nimbusds.jose.shaded.json.JSONArray; +import com.nimbusds.jose.shaded.json.JSONObject; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtDecoder; + +import java.util.List; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +public class TokenForTestsConfiguration { + + public static final String ROLE_CLAIM = "realm_access"; + public static final String KEY_FOR_ROLES_IN_ROLE_CLAIM = "roles"; + public static final String STAMP_CLAIM = "timbre"; + public static final String ID_CLAIM = "preferred_username"; + + public static void configureJwtDecoderMock(JwtDecoder jwtDecoderMock, String idep, String timbre, List roles) { + when(jwtDecoderMock.decode(anyString())).then(invocation -> Jwt.withTokenValue(invocation.getArgument(0)) + .header("typ", "JWT") + .header("alg", "none") + .claim(ID_CLAIM, idep) + .claim(STAMP_CLAIM, timbre) + .claim(ROLE_CLAIM, jsonRoles(roles)) + .build()); + } + + private static JSONObject jsonRoles(List roles) { + var jsonObject = new JSONObject(); + var jsonArray=new JSONArray(); + jsonArray.addAll(roles); + jsonObject.put(KEY_FOR_ROLES_IN_ROLE_CLAIM, jsonArray); + return jsonObject; + } + +} diff --git a/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java b/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java new file mode 100644 index 000000000..d6bd45e12 --- /dev/null +++ b/src/test/java/fr/insee/rmes/persistance/sparql_queries/operations/series/OpSeriesQueriesTest.java @@ -0,0 +1,58 @@ +package fr.insee.rmes.persistance.sparql_queries.operations.series; + +import fr.insee.rmes.bauhaus_services.rdf_utils.ObjectType; +import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils; +import fr.insee.rmes.bauhaus_services.rdf_utils.UriUtils; +import fr.insee.rmes.config.ConfigStub; +import fr.insee.rmes.persistance.sparql_queries.GenericQueries; +import org.eclipse.rdf4j.model.IRI; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static fr.insee.rmes.utils.StringUtils.urisAsString; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +class OpSeriesQueriesTest { + + public static final String SERIES_BASE_URI="operations/serie"; + + private String actualRequest; + + + @Test + void getCreatorsBySeriesUri_requestIsWellGenerated() { + var id="s2132"; + prepareRdfUtils(); + prepareGenericQueries(); + List uris=List.of(RdfUtils.objectIRI(ObjectType.SERIES,id)); + String expectedGeneratedQuery= """ + SELECT ?creators\s + FROM + WHERE { + { + ?series dc:creator ?creators . + VALUES ?series {