diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/Constants.java b/src/main/java/fr/insee/rmes/bauhaus_services/Constants.java index 9a0b691fe..1583717c7 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/Constants.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/Constants.java @@ -31,8 +31,7 @@ public class Constants { public static final String DOCUMENT = "document"; public static final String DOCUMENTS_LG1 = "documentsLg1"; public static final String DOCUMENTS_LG2 = "documentsLg2"; - public static final String DOT_XML = ".xml"; - public static final String DOT_ZIP = ".zip"; + /*E*/ public static final String EDITORIAL_NOTE_LG1 = "editorialNoteLg1"; @@ -103,9 +102,7 @@ public class Constants { public static final String SEEALSO = "seeAlso"; public static final String SERIES_UP = "SERIES"; public static final String STAMP = "stamp"; - public static final String STATUT_VALIDATION = "statutValidation"; - /*T*/ public static final String TEXT = "text"; public static final String TEXT_LG1 = "texte"; 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 af0979bbf..8e83936d1 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 @@ -5,6 +5,7 @@ import fr.insee.rmes.bauhaus_services.OrganizationsService; import fr.insee.rmes.bauhaus_services.code_list.CodeList; import fr.insee.rmes.bauhaus_services.operations.ParentUtils; +import fr.insee.rmes.bauhaus_services.operations.documentations.documents.DocumentsUtils; import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; import fr.insee.rmes.bauhaus_services.operations.operations.OperationsUtils; import fr.insee.rmes.bauhaus_services.operations.series.SeriesUtils; @@ -13,19 +14,26 @@ import fr.insee.rmes.model.operations.Operation; import fr.insee.rmes.model.operations.Series; import fr.insee.rmes.model.operations.documentations.MSD; -import fr.insee.rmes.utils.EncodingType; -import fr.insee.rmes.utils.ExportUtils; -import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.utils.XsltUtils; +import fr.insee.rmes.utils.*; +import org.json.JSONArray; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.io.IOException; +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; import static fr.insee.rmes.bauhaus_services.Constants.GOAL_COMITE_LABEL; @@ -33,6 +41,7 @@ @Component public class DocumentationExport { + static final Logger logger = LoggerFactory.getLogger(DocumentationExport.class); public static final String DOCUMENTATION = "documentation"; final ExportUtils exportUtils; @@ -50,15 +59,16 @@ public class DocumentationExport { 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 String xslFile = "/xslTransformerFiles/sims2fodt.xsl"; - static String xmlPatternRmes = "/xslTransformerFiles/simsRmes/rmesPatternContent.xml"; - static String zipRmes = "/xslTransformerFiles/simsRmes/toZipForRmes.zip"; - - static String xmlPatternLabel = "/xslTransformerFiles/simsLabel/labelPatternContent.xml"; - static String zipLabel = "/xslTransformerFiles/simsLabel/toZipForLabel.zip"; + static final String xmlPatternLabel = "/xslTransformerFiles/simsLabel/labelPatternContent.xml"; + static final String zipLabel = "/xslTransformerFiles/simsLabel/toZipForLabel.zip"; + private final int maxLength; - public DocumentationExport(ExportUtils exportUtils, SeriesUtils seriesUtils, OperationsUtils operationsUtils, IndicatorsUtils indicatorsUtils, ParentUtils parentUtils, CodeListService codeListServiceImpl, OrganizationsService organizationsServiceImpl, DocumentationsUtils documentationsUtils) { + 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; @@ -67,6 +77,8 @@ public DocumentationExport(ExportUtils exportUtils, SeriesUtils seriesUtils, Ope this.codeListServiceImpl = codeListServiceImpl; this.organizationsServiceImpl = organizationsServiceImpl; this.documentationsUtils = documentationsUtils; + this.documentsUtils = documentsUtils; + this.maxLength = maxLength; } /** @@ -86,13 +98,98 @@ public ResponseEntity exportAsResponse(String id, Map Exporter exporter; if (documents) { JSONObject sims = this.documentationsUtils.getDocumentationByIdSims(id); - exporter = (xml, xsl, xmlPattern, zip, documentation) -> exportUtils.exportAsZip(sims, xml, xsl, xmlPattern, zip, documentation ); + exporter = (xml, xsl, xmlPattern, zip, documentation) -> exportAsZip(sims, xml, xsl, xmlPattern, zip, documentation ); } else{ exporter = (xml, xsl, xmlPattern, zip, documentation) -> exportUtils.exportAsODT(id, 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) throws RmesException { + String simsId = sims.getString("id"); + logger.debug("Begin to download the SIMS {} with its documents", simsId); + String fileName = sims.getString("labelLg1"); + + 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(sims.getString("labelLg1"), FilesUtils.ZIP_EXTENSION, this.maxLength); + responseHeaders.setAccessControlExposeHeaders(List.of("X-Missing-Documents", HttpUtils.CONTENT_DISPOSITION)); + 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.reduceFileNameSize(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); } @@ -104,7 +201,6 @@ public ResponseEntity exportXmlFiles(Map xmlContent, Str xmlContent.put(Constants.PARAMETERS_FILE, parametersXML); return exportUtils.exportFilesAsResponse(xmlContent); - } diff --git a/src/main/java/fr/insee/rmes/utils/ExportUtils.java b/src/main/java/fr/insee/rmes/utils/ExportUtils.java index ae5d6dca1..8a373c6b8 100644 --- a/src/main/java/fr/insee/rmes/utils/ExportUtils.java +++ b/src/main/java/fr/insee/rmes/utils/ExportUtils.java @@ -3,19 +3,18 @@ import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.operations.documentations.documents.DocumentsUtils; import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.model.dissemination_status.DisseminationStatus; -import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; 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.Value; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; -import org.springframework.http.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import javax.xml.transform.TransformerException; @@ -25,19 +24,13 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; -import java.util.*; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; +import java.util.Map; @Component public class ExportUtils { - - private static final String CONTENT_TYPE = "Content-Type"; - private static final String ATTACHMENT = "attachment"; private static final Logger logger = LoggerFactory.getLogger(ExportUtils.class); private static final String CAN_T_GENERATE_CODEBOOK = "Can't generate codebook"; private static final String NULL_STREAM = "Stream is null"; - private static final String CONTENT_DISPOSITION = "Content-Disposition"; final int maxLength; @@ -48,106 +41,15 @@ public ExportUtils(@Value("${fr.insee.rmes.bauhaus.filenames.maxlength}") int ma this.documentsUtils = documentsUtils; } - public ResponseEntity exportAsZip(JSONObject sims, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType) throws RmesException { - String simsId = sims.getString("id"); - logger.debug("Begin to download the SIMS {} with its documents", simsId); - String fileName = sims.getString("labelLg1"); - - ContentDisposition content = ContentDisposition.builder(ATTACHMENT).filename(fileName + Constants.DOT_ZIP).build(); - - 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.toString()); - - logger.debug("Generating the InputStream for the SIMS {}", simsId); - - InputStream input = 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 = new HttpHeaders(); - responseHeaders.setContentDisposition(content); - responseHeaders.set(HttpHeaders.CONTENT_TYPE, "application/zip"); - responseHeaders.setAccessControlExposeHeaders(List.of("X-Missing-Documents")); - responseHeaders.set("X-Missing-Documents", String.join(",", missingDocuments)); - Resource resource = new UrlResource(Paths.get(simsDirectory.toString(), simsDirectory.getFileName() + Constants.DOT_ZIP).toUri()); - return ResponseEntity.ok() - .headers(responseHeaders) - .body(resource); - } - catch (Exception exception) { - logger.error("Error when downloading the SIMS {} with its documents", simsId, 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.reduceFileNameSize(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; - } - - public ResponseEntity exportAsODT(String fileName, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType) throws RmesException { - return exportAsFileByExtension(fileName, xmlContent, xslFile, xmlPattern, zip, objectType, FilesUtils.ODT_EXTENSION, "application/vnd.oasis.opendocument.text"); + return exportAsFileByExtension(fileName, xmlContent, xslFile, xmlPattern, zip, objectType, FilesUtils.ODT_EXTENSION); } public ResponseEntity exportAsODS(String fileName, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType) throws RmesException { - return exportAsFileByExtension(fileName, xmlContent, xslFile, xmlPattern, zip, objectType, FilesUtils.ODS_EXTENSION, "application/vnd.oasis.opendocument.spreadsheet"); + return exportAsFileByExtension(fileName, xmlContent, xslFile, xmlPattern, zip, objectType, FilesUtils.ODS_EXTENSION); } - private ResponseEntity exportAsFileByExtension(String fileName, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType, String extension, String contentType) throws RmesException { + private ResponseEntity exportAsFileByExtension(String fileName, Map xmlContent, String xslFile, String xmlPattern, String zip, String objectType, String extension) throws RmesException { logger.debug("Begin To export {} as Response", objectType); fileName = fileName.replace(extension, ""); @@ -165,17 +67,7 @@ private ResponseEntity exportAsFileByExtension(String fileName, Map allowHeaders = new ArrayList<>(); - allowHeaders.add(CONTENT_DISPOSITION); - allowHeaders.add("Access-Control-Allow-Origin"); - allowHeaders.add("Access-Control-Allow-Credentials"); - responseHeaders.setAccessControlExposeHeaders(allowHeaders); - responseHeaders.add(CONTENT_TYPE, contentType); + HttpHeaders responseHeaders = HttpUtils.generateHttpHeaders(fileName, extension, this.maxLength); return ResponseEntity.ok() .headers(responseHeaders) @@ -239,7 +131,6 @@ public InputStream exportAsInputStream(String fileName, Map xmlC public ResponseEntity exportFilesAsResponse(Map xmlContent) throws RmesException { logger.debug("Begin To export temp files as Response"); - ContentDisposition content = ContentDisposition.builder(ATTACHMENT).filename("xmlFiles.zip").build(); Path tempDir; try { @@ -248,7 +139,7 @@ public ResponseEntity exportFilesAsResponse(Map xmlConte // Add all files in a tempDirectory xmlContent.forEach((paramName, xmlData) -> { try { - Path tempFile = Files.createTempFile(tempDir, paramName, Constants.DOT_XML); + Path tempFile = Files.createTempFile(tempDir, paramName, FilesUtils.XML_EXTENSION); Files.write(tempFile, xmlData.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); } catch (IOException e) { logger.error(e.getMessage()); @@ -260,9 +151,7 @@ public ResponseEntity exportFilesAsResponse(Map xmlConte logger.debug("End To export temp files as Response"); - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.setContentDisposition(content); - responseHeaders.set(HttpHeaders.CONTENT_TYPE, "application/zip"); + HttpHeaders responseHeaders = HttpUtils.generateHttpHeaders("xmlFiles", FilesUtils.ZIP_EXTENSION, this.maxLength); Resource resource = new UrlResource(Paths.get(tempDir.toString(), tempDir.getFileName() + FilesUtils.ZIP_EXTENSION).toUri()); return ResponseEntity.ok() .headers(responseHeaders) diff --git a/src/main/java/fr/insee/rmes/utils/FilesUtils.java b/src/main/java/fr/insee/rmes/utils/FilesUtils.java index fd1a92319..b2ab8d598 100644 --- a/src/main/java/fr/insee/rmes/utils/FilesUtils.java +++ b/src/main/java/fr/insee/rmes/utils/FilesUtils.java @@ -4,6 +4,7 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; import org.zeroturnaround.zip.FileSource; import org.zeroturnaround.zip.ZipEntrySource; import org.zeroturnaround.zip.ZipUtil; @@ -23,6 +24,15 @@ public class FilesUtils { public static final String XML_EXTENSION = ".xml"; public static final String FODT_EXTENSION = ".fodt"; + public static MediaType getMediaTypeFromExtension(String extension) { + MediaType contentType = switch (extension){ + case FilesUtils.ODT_EXTENSION -> new MediaType("application", "vnd.oasis.opendocument.text"); + case FilesUtils.ODS_EXTENSION -> new MediaType("application", "vnd.oasis.opendocument.spreadsheet"); + case FilesUtils.ZIP_EXTENSION -> new MediaType("application", "zip"); + default -> throw new IllegalStateException("Unexpected value: " + extension); + }; + return contentType; + } public static String getExtension(String acceptHeader) { if (acceptHeader == null) { diff --git a/src/main/java/fr/insee/rmes/utils/HttpUtils.java b/src/main/java/fr/insee/rmes/utils/HttpUtils.java new file mode 100644 index 000000000..b4ee8dcdb --- /dev/null +++ b/src/main/java/fr/insee/rmes/utils/HttpUtils.java @@ -0,0 +1,34 @@ +package fr.insee.rmes.utils; + +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +import java.util.List; + +public final class HttpUtils { + public static final String ATTACHMENT = "attachment"; + public static final String CONTENT_DISPOSITION = "Content-Disposition"; + + private HttpUtils() { + } + + public static HttpHeaders generateHttpHeaders(String fileName, String extension, int maxLength) { + MediaType contentType = FilesUtils.getMediaTypeFromExtension(extension); + + ContentDisposition content = ContentDisposition.builder(HttpUtils.ATTACHMENT).filename(FilesUtils.reduceFileNameSize(fileName, maxLength) + extension).build(); + + List allowHeaders = List.of(CONTENT_DISPOSITION, + "Access-Control-Allow-Origin", + "Access-Control-Allow-Credentials"); + + + HttpHeaders responseHeaders = new HttpHeaders(); + responseHeaders.setAccept(List.of(MediaType.ALL)); + responseHeaders.setContentDisposition(content); + responseHeaders.setContentType(contentType); + responseHeaders.setAccessControlExposeHeaders(allowHeaders); + return responseHeaders; + } + +} diff --git a/src/main/java/fr/insee/rmes/utils/XsltUtils.java b/src/main/java/fr/insee/rmes/utils/XsltUtils.java index e8faa9f59..7c5606588 100644 --- a/src/main/java/fr/insee/rmes/utils/XsltUtils.java +++ b/src/main/java/fr/insee/rmes/utils/XsltUtils.java @@ -53,7 +53,7 @@ private static void addParameter(Transformer xsltTransformer, String paramName, // Pass parameters in a file CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING }; try { - Path tempFile = Files.createTempFile(tempDir, paramName, Constants.DOT_XML); + Path tempFile = Files.createTempFile(tempDir, paramName, FilesUtils.XML_EXTENSION); String absolutePath = tempFile.toFile().getAbsolutePath(); InputStream is = IOUtils.toInputStream(paramData, StandardCharsets.UTF_8); Files.copy(is, tempFile, options); diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExportTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExportTest.java index 462d1cb78..1cf3a705a 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExportTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationExportTest.java @@ -1,36 +1,57 @@ package fr.insee.rmes.bauhaus_services.operations.documentations; +import fr.insee.rmes.bauhaus_services.CodeListService; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.OrganizationsService; import fr.insee.rmes.bauhaus_services.operations.ParentUtils; +import fr.insee.rmes.bauhaus_services.operations.documentations.documents.DocumentsUtils; +import fr.insee.rmes.bauhaus_services.operations.indicators.IndicatorsUtils; +import fr.insee.rmes.bauhaus_services.operations.operations.OperationsUtils; +import fr.insee.rmes.bauhaus_services.operations.series.SeriesUtils; import fr.insee.rmes.exceptions.RmesBadRequestException; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.utils.ExportUtils; +import fr.insee.rmes.utils.FilesUtils; +import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import java.io.InputStream; import java.util.HashMap; import java.util.Map; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class DocumentationExportTest { + @Mock + private SeriesUtils seriesUtils; + + @Mock + private OperationsUtils operationsUtils; + + @Mock + private IndicatorsUtils indicatorsUtils; + @Mock private ExportUtils exportUtils; + @Mock + private CodeListService codeListService; + @Mock private ParentUtils parentUtils; @@ -40,32 +61,46 @@ class DocumentationExportTest { @Mock private OrganizationsService organizationsService; - @InjectMocks - private DocumentationExport documentationExport; + @Mock + private DocumentsUtils documentsUtils; @Test - public void testExportMetadataReport_Success_WithDocuments_RMES() throws RmesException { - String id = "1234"; - boolean includeEmptyMas = true; - boolean lg1 = true; - boolean lg2 = false; - boolean document = true; - String goal = Constants.GOAL_RMES; - String targetType = "someTargetType"; + public void testExportAsZip_success() throws Exception { + JSONObject document = new JSONObject(); + document.put("url", "file://doc.doc"); + document.put("id", "1"); - Resource resource = new ByteArrayResource("Mocked Document Content".getBytes()); + when(documentsUtils.getDocumentsUriAndUrlForSims("sims123")).thenReturn(new JSONArray().put(document)); + var sims = new JSONObject(); + sims.put("id", "sims123"); + sims.put("labelLg1", "simsLabel"); - when(parentUtils.getDocumentationTargetTypeAndId(id)).thenReturn(new String[]{targetType, "someId"}); - when(documentationsUtils.getDocumentationByIdSims(id)).thenReturn(new JSONObject()); - when(documentationsUtils.getFullSimsForXml(id)).thenReturn(new Documentation()); - when(exportUtils.exportAsZip(any(), any(), any(), any(), any(), any())).thenReturn(ResponseEntity.ok().body(resource)); + var xmlContent = new HashMap(); + var xslFile = "xslFile"; + var xmlPattern = "xmlPattern"; + var zip = "zip"; + var objectType = "objectType"; - ResponseEntity response = documentationExport.exportMetadataReport(id, includeEmptyMas, lg1, lg2, document, goal); - assertEquals(ResponseEntity.ok().body(resource), response); + DocumentationExport documentationExport = new DocumentationExport(50, documentsUtils, exportUtils, seriesUtils, operationsUtils, indicatorsUtils, parentUtils, codeListService, organizationsService, documentationsUtils ); + + + InputStream inputStreamMock = mock(InputStream.class); + when(exportUtils.exportAsInputStream(eq("simsLabel"), eq(xmlContent), eq(xslFile), eq(xmlPattern), eq(zip), eq(objectType), eq(FilesUtils.ODT_EXTENSION))) + .thenReturn(inputStreamMock); + when(inputStreamMock.readAllBytes()).thenReturn(new byte[0]); + + ResponseEntity response = documentationExport.exportAsZip(sims, xmlContent, xslFile, xmlPattern, zip, objectType); + + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getBody()); + assertEquals(response.getStatusCode(), HttpStatus.OK); + assertEquals(response.getHeaders().get("X-Missing-Documents").get(0), "1"); } @Test - public void testExportMetadataReport_Success_WithoutDocuments_Label() throws RmesException { + public void testExportMetadataReport_Success_WithoutDocuments_Label() throws RmesException { + DocumentationExport documentationExport = new DocumentationExport(50, documentsUtils, exportUtils, seriesUtils, operationsUtils, indicatorsUtils, parentUtils, codeListService, organizationsService, documentationsUtils ); + String id = "1234"; boolean includeEmptyMas = true; boolean lg1 = true; @@ -86,6 +121,8 @@ public void testExportMetadataReport_Success_WithoutDocuments_Label() throws Rme @Test public void testExportMetadataReport_Failure_UnknownGoal() throws RmesException { + DocumentationExport documentationExport = new DocumentationExport(50, documentsUtils, exportUtils, seriesUtils, operationsUtils, indicatorsUtils, parentUtils, codeListService, organizationsService, documentationsUtils ); + String id = "1234"; boolean includeEmptyMas = true; boolean lg1 = true; @@ -105,6 +142,8 @@ public void testExportMetadataReport_Failure_UnknownGoal() throws RmesException @Test public void testExportXmlFiles_Success() throws RmesException { + DocumentationExport documentationExport = new DocumentationExport(50, documentsUtils, exportUtils, seriesUtils, operationsUtils, indicatorsUtils, parentUtils, codeListService, organizationsService, documentationsUtils ); + Map xmlContent = new HashMap<>(); boolean includeEmptyMas = true; boolean lg1 = true;