diff --git a/pom.xml b/pom.xml
index 02054a40b..162879797 100644
--- a/pom.xml
+++ b/pom.xml
@@ -13,7 +13,7 @@
fr.insee.rmes
Bauhaus-BO
jar
- 4.1.6
+ 4.1.7-beta
Bauhaus-Back-Office
Back-office services for Bauhaus
https://github.com/InseeFr/Bauhaus-Back-Office
diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/FileSystemOperation.java b/src/main/java/fr/insee/rmes/bauhaus_services/FileSystemOperation.java
index 1be00cb9a..7afdd0b6a 100644
--- a/src/main/java/fr/insee/rmes/bauhaus_services/FileSystemOperation.java
+++ b/src/main/java/fr/insee/rmes/bauhaus_services/FileSystemOperation.java
@@ -22,16 +22,16 @@ public void delete(String path) {
try {
Files.delete(Paths.get(path));
} catch (IOException e) {
- throw new RmesFileException("Failed to delete file: " + path, e);
+ throw new RmesFileException(path, "Failed to delete file: " + path, e);
}
}
@Override
- public InputStream read(String fileName) {
+ public byte[] read(String fileName) {
try {
- return Files.newInputStream(Paths.get(config.getDocumentsStorageGestion()).resolve(fileName));
+ return Files.readAllBytes(Paths.get(config.getDocumentsStorageGestion()).resolve(fileName));
} catch (IOException e) {
- throw new RmesFileException("Failed to read file: " + fileName, e);
+ throw new RmesFileException(fileName, "Failed to read file: " + fileName, e);
}
}
@@ -40,7 +40,7 @@ public void write(InputStream content, Path destPath) {
try {
Files.copy(content, destPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
- throw new RmesFileException("Failed to write file: " + destPath, e);
+ throw new RmesFileException(destPath.toString(),"Failed to write file: " + destPath, e);
}
}
@@ -51,7 +51,7 @@ public void copy(String srcPath, String destPath) {
try {
Files.copy(file, targetPath.resolve(file.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
- throw new RmesFileException("Failed to copy file : " + srcPath + " to " + destPath, e);
+ throw new RmesFileException(srcPath, "Failed to copy file : " + srcPath + " to " + destPath, e);
}
}
@@ -59,4 +59,9 @@ public void copy(String srcPath, String destPath) {
public boolean dirExists(Path gestionStorageFolder) {
return Files.isDirectory(requireNonNull(gestionStorageFolder));
}
+
+ @Override
+ public boolean exists(Path path) {
+ return false;
+ }
}
diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/FilesOperations.java b/src/main/java/fr/insee/rmes/bauhaus_services/FilesOperations.java
index 7f7f6453f..7b7ca79f7 100644
--- a/src/main/java/fr/insee/rmes/bauhaus_services/FilesOperations.java
+++ b/src/main/java/fr/insee/rmes/bauhaus_services/FilesOperations.java
@@ -5,9 +5,11 @@
public interface FilesOperations {
void delete(String path);
- InputStream read(String path);
+ byte[] read(String path);
void write(InputStream content, Path destPath);
void copy(String srcPath, String destPath);
boolean dirExists(Path gestionStorageFolder);
+
+ boolean exists(Path path);
}
diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/MinioFilesOperation.java b/src/main/java/fr/insee/rmes/bauhaus_services/MinioFilesOperation.java
index 0b794034e..fdb6d7d31 100644
--- a/src/main/java/fr/insee/rmes/bauhaus_services/MinioFilesOperation.java
+++ b/src/main/java/fr/insee/rmes/bauhaus_services/MinioFilesOperation.java
@@ -3,8 +3,6 @@
import fr.insee.rmes.exceptions.RmesFileException;
import io.minio.*;
import io.minio.errors.*;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
@@ -12,62 +10,65 @@
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
-public record MinioFilesOperation(MinioClient minioClient, String bucketName, String directoryGestion, String directoryPublication) implements FilesOperations {
+import static java.util.Objects.requireNonNull;
- private static final Logger logger = LoggerFactory.getLogger(MinioFilesOperation.class);
+public record MinioFilesOperation(MinioClient minioClient, String bucketName, String directoryGestion, String directoryPublication) implements FilesOperations {
@Override
- public InputStream read(String pathFile){
- String objectName= extractFileName(pathFile);
-
- try {
- return minioClient.getObject(GetObjectArgs.builder()
- .bucket(bucketName)
- .object(directoryGestion +"/"+ objectName)
- .build());
+ public byte[] read(String pathFile){
+ String objectName = getObjectName(requireNonNull(pathFile));
+ try(InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
+ .bucket(bucketName)
+ .object(objectName)
+ .build())) {
+ return inputStream.readAllBytes();
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
- throw new RmesFileException("Error reading file: " + objectName, e);
+ throw new RmesFileException(pathFile, "Error reading file: " + pathFile+" as object `"+objectName+"` in bucket "+bucketName, e);
}
}
- private static String extractFileName(String filePath) {
- if (filePath == null || filePath.isEmpty()) {
- return "";
- }
- return Path.of(filePath).getFileName().toString();
+
+ private String getObjectName(String pathFile) {
+ return getObjectName(Path.of(pathFile));
+ }
+
+ private String getObjectName(Path pathFile) {
+ return directoryGestion + "/" + pathFile.getFileName().toString();
}
@Override
- public void write(InputStream content, Path objectName) {
+ public void write(InputStream content, Path filePath) {
+ String objectName = getObjectName(requireNonNull(filePath));
try {
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
- .object(directoryGestion +"/"+ objectName.getFileName().toString())
+ .object(objectName)
.stream(content, content.available(), -1)
.build());
} catch (IOException | ErrorResponseException | InsufficientDataException | InternalException |
InvalidKeyException | InvalidResponseException | NoSuchAlgorithmException | ServerException |
XmlParserException e) {
- throw new RmesFileException("Error writing file: " + objectName, e);
+ throw new RmesFileException(filePath.toString(), "Error writing file: " + filePath+ "as object `"+objectName+"` in bucket "+bucketName, e);
}
}
@Override
public void copy(String srcObjectName, String destObjectName) {
+ String srcObject = getObjectName(requireNonNull(srcObjectName));
+ String destObject = getObjectName(requireNonNull(srcObjectName));
try {
CopySource source = CopySource.builder()
.bucket(bucketName)
- .object(directoryGestion +"/"+ extractFileName(srcObjectName))
+ .object(srcObject)
.build();
-
minioClient.copyObject(CopyObjectArgs.builder()
.bucket(bucketName)
- .object(directoryPublication +"/"+ extractFileName(srcObjectName))
+ .object(destObject)
.source(source)
.build());
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
- throw new RmesFileException("Error copying file from " + srcObjectName + " to " + destObjectName, e);
+ throw new RmesFileException(srcObjectName,"Error copying file from `" + srcObject + "` to `" + destObject+"` in bucket "+bucketName, e);
}
}
@@ -77,7 +78,20 @@ public boolean dirExists(Path gestionStorageFolder) {
return true;
}
- @Override
+ @Override
+ public boolean exists(Path path) {
+ var objectName = getObjectName(requireNonNull(path));
+ try {
+ return minioClient.statObject(StatObjectArgs.builder()
+ .bucket(bucketName)
+ .object(objectName)
+ .build()).size() > 0;
+ } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
+ return false;
+ }
+ }
+
+ @Override
public void delete(String objectName) {
try {
minioClient.removeObject(RemoveObjectArgs.builder()
@@ -85,7 +99,7 @@ public void delete(String objectName) {
.object(objectName)
.build());
} catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
- throw new RmesFileException("Error deleting file: " + objectName, e);
+ throw new RmesFileException(objectName,"Error deleting file: " + objectName+" in bucket "+bucketName, e);
}
}
diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/StampAuthorizationChecker.java b/src/main/java/fr/insee/rmes/bauhaus_services/StampAuthorizationChecker.java
index 8bda2da36..57790af12 100644
--- a/src/main/java/fr/insee/rmes/bauhaus_services/StampAuthorizationChecker.java
+++ b/src/main/java/fr/insee/rmes/bauhaus_services/StampAuthorizationChecker.java
@@ -136,9 +136,9 @@ private IRI findDistributionIRI(String distributionId) {
private IRI findComponentIRI(String componentId) throws RmesException {
JSONObject type = repoGestion.getResponseAsObject(StructureQueries.getComponentType(componentId));
String componentType = type.getString("type");
- if (componentType.equals(RdfUtils.toString(QB.ATTRIBUTE_PROPERTY))) {
+ if (componentType.equals(QB.ATTRIBUTE_PROPERTY.toString())) {
return RdfUtils.structureComponentAttributeIRI(componentId);
- } else if (componentType.equals(RdfUtils.toString(QB.DIMENSION_PROPERTY))) {
+ } else if (componentType.equals(QB.DIMENSION_PROPERTY.toString())) {
return RdfUtils.structureComponentDimensionIRI(componentId);
} else {
return RdfUtils.structureComponentMeasureIRI(componentId);
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 2821cc320..797409f93 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
@@ -3,7 +3,6 @@
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;
@@ -53,7 +52,7 @@ public void transformStatementToPublish(Model model, RepositoryResult
while (classifStatements.hasNext()) {
Statement st = classifStatements.next();
// Triplets that don't get published
- String predicate = RdfUtils.toString(st.getPredicate());
+ String predicate = st.getPredicate().toString();
if (!isTripletForPublication(predicate)) {
// nothing, wouldn't copy this attr
} else {
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 185909de3..901c7047f 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
@@ -30,7 +30,7 @@ private void checkIfResourceExists(RepositoryResult statements, Resou
}
private boolean shouldExcludeTriplet(Statement statement){
- String pred = RdfUtils.toString(statement.getPredicate());
+ String pred = statement.getPredicate().toString();
return pred.endsWith("validationState")
|| pred.endsWith(Constants.CREATOR)
|| pred.endsWith(Constants.CONTRIBUTOR)
@@ -54,7 +54,7 @@ private void publishCodeListAndCodesWithConnection(Resource codeListOrCode, Repo
}
- String predicate = RdfUtils.toString(st.getPredicate());
+ String predicate = st.getPredicate().toString();
String object = st.getObject().stringValue();
if (RDFS.SEEALSO.toString().equalsIgnoreCase(predicate)) {
publishSeeAlsoTriplets(object, connection);
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 3fdd80d01..4ef9a406d 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
@@ -267,7 +267,7 @@ private boolean checkCodeListUnicity(boolean partial, JSONObject codeList, Strin
String id = codeList.getString(Constants.ID);
if(!partial) {
IRI seeAlso = RdfUtils.codeListIRI(CONCEPT + codeList.getString(LAST_CLASS_URI_SEGMENT));
- return repoGestion.getResponseAsBoolean(CodeListQueries.checkCodeListUnicity(id, iri, RdfUtils.toString(seeAlso), false));
+ return repoGestion.getResponseAsBoolean(CodeListQueries.checkCodeListUnicity(id, iri, seeAlso.toString(), false));
}
return repoGestion.getResponseAsBoolean(CodeListQueries.checkCodeListUnicity(id, iri, "", true));
}
@@ -280,7 +280,7 @@ public String setCodesList(String body, boolean partial) throws RmesException {
IRI codeListIri = this.generateIri(codesList, partial);
- if(this.checkCodeListUnicity(partial, codesList, RdfUtils.toString(codeListIri))){
+ if(this.checkCodeListUnicity(partial, codesList, codeListIri.toString())){
throw new RmesBadRequestException(CodesListErrorCodes.CODE_LIST_UNICITY,
"The identifier, IRI and OWL class should be unique", "");
}
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 12c6b8873..e87e807bb 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
@@ -89,7 +89,7 @@ public String getConceptByID(String id) throws RmesException{
@Override
public String getRelatedConcepts(String id) throws RmesException{
- String uriConcept = RdfUtils.toString(RdfUtils.objectIRI(ObjectType.CONCEPT,id));
+ String uriConcept = RdfUtils.objectIRI(ObjectType.CONCEPT, id).toString();
JSONArray resQuery = conceptsUtils.getRelatedConcepts(uriConcept);
return QueryUtils.correctEmptyGroupConcat(resQuery.toString());
}
@@ -102,7 +102,7 @@ public String getRelatedConcepts(String id) throws RmesException{
*/
@Override
public String deleteConcept(String id) throws RmesException {
- String uriConcept = RdfUtils.toString(RdfUtils.objectIRI(ObjectType.CONCEPT,id));
+ String uriConcept = RdfUtils.objectIRI(ObjectType.CONCEPT, id).toString();
JSONArray graphArray = conceptsUtils.getGraphsWithConcept(uriConcept);
/* check concept isn't used in several graphs */
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 3558adf23..1c07f61a2 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
@@ -216,9 +216,9 @@ public JSONArray getRelatedConcepts(String id) throws RmesException{
}
public HttpStatus deleteConcept(String id) throws RmesException{
- HttpStatus result = repoGestion.executeUpdate(ConceptsQueries.deleteConcept(RdfUtils.toString(RdfUtils.objectIRI(ObjectType.CONCEPT,id)),RdfUtils.conceptGraph().toString()));
+ HttpStatus result = repoGestion.executeUpdate(ConceptsQueries.deleteConcept(RdfUtils.objectIRI(ObjectType.CONCEPT, id).toString(),RdfUtils.conceptGraph().toString()));
if (result.equals(HttpStatus.OK)) {
- result = repositoryPublication.executeUpdate(ConceptsQueries.deleteConcept(RdfUtils.toString(RdfUtils.objectIRIPublication(ObjectType.CONCEPT,id)),RdfUtils.conceptGraph().toString()));
+ result = repositoryPublication.executeUpdate(ConceptsQueries.deleteConcept(RdfUtils.objectIRIPublication(ObjectType.CONCEPT, id).toString(),RdfUtils.conceptGraph().toString()));
}
return result;
}
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 da25a90bc..16764dbbc 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
@@ -8,10 +8,7 @@
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;
-import org.eclipse.rdf4j.model.Resource;
-import org.eclipse.rdf4j.model.Statement;
+import org.eclipse.rdf4j.model.*;
import org.eclipse.rdf4j.model.impl.LinkedHashModel;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.SKOS;
@@ -80,7 +77,7 @@ private Boolean prepareOneTripleToPublicationAndCheckIfHasBroader(Model model, L
Resource subject = publicationUtils.tranformBaseURIToPublish(st.getSubject());
Resource graph = st.getContext();
- String predicat = RdfUtils.toString(st.getPredicate());
+ String predicat = st.getPredicate().toString();
if (PublicationUtils.stringEndsWithItemFromList(predicat,notes)) {
model.add(subject, st.getPredicate(), publicationUtils.tranformBaseURIToPublish((Resource) st.getObject()),
@@ -147,7 +144,7 @@ private void publishExplanatoryNotes(RepositoryConnection con, Resource note, Mo
Resource graph = null;
while (statements.hasNext()) {
Statement st = statements.next();
- String predicat = RdfUtils.toString(st.getPredicate());
+ String predicat = st.getPredicate().toString();
subject = publicationUtils.tranformBaseURIToPublish(st.getSubject());
graph = st.getContext();
if (predicat.endsWith("conceptVersion")) {
@@ -214,12 +211,12 @@ public void publishCollection(JSONArray collectionsToValidate) throws RmesExcept
while (statements.hasNext()) {
Statement st = statements.next();
// Other URI to transform
- if (RdfUtils.toString(st.getPredicate()).endsWith("member")) {
+ if (st.getPredicate().toString().endsWith("member")) {
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))) {
+ } else if (st.getPredicate().toString().endsWith("isValidated")
+ || (st.getPredicate().toString().endsWith(Constants.CREATOR))
+ || (st.getPredicate().toString().endsWith(Constants.CONTRIBUTOR))) {
// nothing, wouldn't copy this attr
}
// Literals
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 d908746f6..debfd7184 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
@@ -195,7 +195,7 @@ public String createRdfGeoFeature(GeoFeature geoFeature) throws RmesException {
});
repoGestion.loadSimpleObject(geoIRI, model);
- return RdfUtils.toString(geoIRI);
- }
+ return geoIRI.toString();
+ }
}
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 4b106b410..5808d2d87 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
@@ -67,7 +67,7 @@ public boolean checkIfSeriesHasSims(String uriSeries) throws RmesException {
}
public void checkIfParentIsASeriesWithOperations(String idParent) throws RmesException {
- String uriParent = RdfUtils.toString(RdfUtils.objectIRI(ObjectType.SERIES, idParent));
+ String uriParent = RdfUtils.objectIRI(ObjectType.SERIES, idParent).toString();
if (checkIfParentExists(uriParent) && checkIfSeriesHasOperation(uriParent)) throw new RmesNotAcceptableException(ErrorCodes.SERIES_OPERATION_OR_SIMS,
"Cannot create Sims for a series which already has operations", idParent);
}
@@ -117,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("<" + iri.toString() + ">"));
}
public String[] getDocumentationTargetTypeAndId(String idSims) throws RmesException {
diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExport.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExport.java
index 46eef73dd..e2f3ec1ee 100644
--- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExport.java
+++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExport.java
@@ -13,6 +13,7 @@
import fr.insee.rmes.exceptions.RmesException;
import fr.insee.rmes.model.operations.Operation;
import fr.insee.rmes.model.operations.Series;
+import fr.insee.rmes.model.operations.documentations.Document;
import fr.insee.rmes.model.operations.documentations.MSD;
import fr.insee.rmes.utils.*;
import org.json.JSONArray;
@@ -31,7 +32,6 @@
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.stream.Collectors;
@@ -41,281 +41,284 @@
@Component
public class DocumentationExport {
- static final Logger logger = LoggerFactory.getLogger(DocumentationExport.class);
-
- public static final String DOCUMENTATION = "documentation";
- final ExportUtils exportUtils;
-
- final SeriesUtils seriesUtils;
-
- final OperationsUtils operationsUtils;
-
- final IndicatorsUtils indicatorsUtils;
-
- final ParentUtils parentUtils;
-
- final CodeListService codeListServiceImpl;
-
- final OrganizationsService organizationsServiceImpl;
-
- final DocumentationsUtils documentationsUtils;
- final DocumentsUtils documentsUtils;
- static final String xslFile = "/xslTransformerFiles/sims2fodt.xsl";
- static final String xmlPatternRmes = "/xslTransformerFiles/simsRmes/rmesPatternContent.xml";
- static final String zipRmes = "/xslTransformerFiles/simsRmes/toZipForRmes.zip";
-
- static final String xmlPatternLabel = "/xslTransformerFiles/simsLabel/labelPatternContent.xml";
- static final String zipLabel = "/xslTransformerFiles/simsLabel/toZipForLabel.zip";
- private final int maxLength;
-
- public DocumentationExport(@Value("${fr.insee.rmes.bauhaus.filenames.maxlength}") int maxLength, DocumentsUtils documentsUtils, ExportUtils exportUtils, SeriesUtils seriesUtils, OperationsUtils operationsUtils, IndicatorsUtils indicatorsUtils, ParentUtils parentUtils, CodeListService codeListServiceImpl, OrganizationsService organizationsServiceImpl, DocumentationsUtils documentationsUtils) {
- this.exportUtils = exportUtils;
- this.seriesUtils = seriesUtils;
- this.operationsUtils = operationsUtils;
- this.indicatorsUtils = indicatorsUtils;
- this.parentUtils = parentUtils;
- this.codeListServiceImpl = codeListServiceImpl;
- this.organizationsServiceImpl = organizationsServiceImpl;
- this.documentationsUtils = documentationsUtils;
- this.documentsUtils = documentsUtils;
- this.maxLength = maxLength;
- }
-
- /**
- *
- * @param id The identifier of the report we want to export
- * @param documents a boolean value indicating if we want to include the related documents to the export.
- * If this value is equal to true, the export will be a .ZIP archive. If equal to false,
- * the export will be a .ODT file.
- */
- public ResponseEntity exportAsResponse(String id, Map xmlContent, String targetType, boolean includeEmptyFields, boolean lg1,
- boolean lg2, boolean documents, String goal, int maxLength) throws RmesException {
-
- PatternAndZip patternAndZip = PatternAndZip.of(goal);
- String parametersXML = XsltUtils.buildParams(lg1, lg2, includeEmptyFields, targetType);
- xmlContent.put(Constants.PARAMETERS_FILE, parametersXML);
-
- Exporter exporter;
- JSONObject sims = this.documentationsUtils.getDocumentationByIdSims(id);
-
- if (documents) {
- exporter = (xml, xsl, xmlPattern, zip, documentation) -> exportAsZip(sims, xml, xsl, xmlPattern, zip, documentation, maxLength);
- } else{
- String fileName = FilesUtils.generateFinalFileNameWithoutExtension(sims.getString(Constants.LABEL_LG1), maxLength);
- exporter = (xml, xsl, xmlPattern, zip, documentation) -> exportUtils.exportAsODT(fileName, xml, xsl, xmlPattern, zip, documentation );
- }
- return export(exporter, xmlContent, patternAndZip);
- }
-
- public ResponseEntity exportAsZip(JSONObject sims, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType, int maxLength) throws RmesException {
- String simsId = sims.getString("id");
- logger.debug("Begin to download the SIMS {} with its documents", simsId);
- String fileName = FilesUtils.generateFinalFileNameWithoutExtension(sims.getString(Constants.LABEL_LG1), maxLength);
-
- try {
-
- Path directory = Files.createTempDirectory("sims");
- logger.debug("Creating tempory directory {}", directory.toString());
- Path simsDirectory = Files.createDirectory(Path.of(directory.toString(), fileName));
- logger.debug("Creating tempory directory {}", simsDirectory);
-
- logger.debug("Generating the InputStream for the SIMS {}", simsId);
-
- InputStream input = exportUtils.exportAsInputStream(fileName, xmlContent, xslFile, xmlPattern, zip, objectType, FilesUtils.ODT_EXTENSION);
- if (input == null){
- logger.debug("Error when creating the export of the SIMS {}", simsId);
- throw new RmesException(HttpStatus.INTERNAL_SERVER_ERROR, "Can't export this object", "");
- }
-
- logger.debug("Creating the .odt file for the SIMS {}", simsId);
- Path tempFile = Files.createFile(Path.of(simsDirectory.toString(), fileName + FilesUtils.ODT_EXTENSION));
- Files.write(tempFile, input.readAllBytes(), StandardOpenOption.APPEND);
- logger.debug("Finishing the creation of the .odt file for the SIMS {}", simsId);
-
-
- logger.debug("Starting downloading documents for the SIMS {}", simsId);
- Set missingDocuments = this.exportRubricsDocuments(sims, simsDirectory);
- logger.debug("Ending downloading documents for the SIMS {}", simsId);
-
- logger.debug("Zipping the folder for the SIMS {}", simsId);
- FilesUtils.zipDirectory(simsDirectory.toFile());
-
- logger.debug("Zip created for the SIMS {}", simsId);
- HttpHeaders responseHeaders = HttpUtils.generateHttpHeaders(fileName, FilesUtils.ZIP_EXTENSION);
- responseHeaders.set("X-Missing-Documents", String.join(",", missingDocuments));
- Resource resource = new UrlResource(Paths.get(simsDirectory.toString(), simsDirectory.getFileName() + FilesUtils.ZIP_EXTENSION).toUri());
- return ResponseEntity.ok()
- .headers(responseHeaders)
- .body(resource);
- }
- catch (Exception exception) {
- throw new RmesException(HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage(), exception.getClass().getSimpleName());
- }
- }
-
- private Set exportRubricsDocuments(JSONObject sims, Path directory) throws IOException, RmesException {
- Set history = new HashSet<>();
- JSONArray documents = documentsUtils.getDocumentsUriAndUrlForSims(sims.getString("id"));
- Set missingDocuments = new HashSet<>();
-
- for (int i = 0; i < documents.length(); i++) {
- JSONObject document = documents.getJSONObject(i);
- String url = document.getString("url").replace("file://", "");
- if(!history.contains(url)){
- history.add(url);
- logger.debug("Extracting document {}", url);
-
-
- Path documentPath = Path.of(url);
-
- if(!Files.exists(documentPath)){
- missingDocuments.add(document.getString("id"));
- } else {
- String documentFileName = FilesUtils.generateFinalFileNameWithExtension(UriUtils.getLastPartFromUri(url), maxLength);
- try (InputStream inputStream = Files.newInputStream(documentPath)){
- Path documentDirectory = Path.of(directory.toString(), "documents");
- if (!Files.exists(documentDirectory)) {
- logger.debug("Creating the documents folder");
- Files.createDirectory(documentDirectory);
- }
-
- logger.debug("Writing the document {} with the name {} into the folder {}", url, documentFileName, directory.toString());
- Path documentTempFile = Files.createFile(Path.of(documentDirectory.toString(), documentFileName));
- Files.write(documentTempFile, inputStream.readAllBytes(), StandardOpenOption.APPEND);
- }
- }
-
- }
- }
-
- return missingDocuments;
- }
-
- private ResponseEntity export(Exporter exporter, Map xmlContent, PatternAndZip patternAndZip) throws RmesException {
- return exporter.export(xmlContent, xslFile, patternAndZip.xmlPattern(), patternAndZip.zip(), DOCUMENTATION);
- }
-
- public ResponseEntity