diff --git a/core/pom.xml b/core/pom.xml index 37f5803..9939cb0 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,7 +18,6 @@ 21 21 1.0.0-SNAPSHOT - 0.0.4 diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/FilePathProperties.java b/core/src/main/java/eu/eudat/file/transformer/configuration/FilePathProperties.java deleted file mode 100644 index b17de61..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/FilePathProperties.java +++ /dev/null @@ -1,30 +0,0 @@ -package eu.eudat.file.transformer.configuration; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.bind.ConstructorBinding; - -@ConfigurationProperties(prefix = "file.template") -public class FilePathProperties { - private final String wordTemplate; - private final String pidTemplate; - private final String wordDescriptionTemplate; - - @ConstructorBinding - public FilePathProperties(String wordTemplate, String pidTemplate, String wordDescriptionTemplate) { - this.wordTemplate = wordTemplate; - this.pidTemplate = pidTemplate; - this.wordDescriptionTemplate = wordDescriptionTemplate; - } - - public String getWordTemplate() { - return wordTemplate; - } - - public String getPidTemplate() { - return pidTemplate; - } - - public String getWordDescriptionTemplate() { - return wordDescriptionTemplate; - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageConfiguration.java b/core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageConfiguration.java deleted file mode 100644 index 4f6122b..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package eu.eudat.file.transformer.configuration; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties({FileStorageProperties.class}) -public class FileStorageConfiguration { -} diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/PdfConfiguration.java b/core/src/main/java/eu/eudat/file/transformer/configuration/PdfConfiguration.java deleted file mode 100644 index a24db19..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/PdfConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package eu.eudat.file.transformer.configuration; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableConfigurationProperties({PdfProperties.class}) -public class PdfConfiguration { -} diff --git a/core/src/main/java/eu/eudat/file/transformer/executor/WordFileTransformer.java b/core/src/main/java/eu/eudat/file/transformer/executor/WordFileTransformer.java deleted file mode 100644 index 0c84b3c..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/executor/WordFileTransformer.java +++ /dev/null @@ -1,634 +0,0 @@ -package eu.eudat.file.transformer.executor; - -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.file.transformer.configuration.FilePathProperties; -import eu.eudat.file.transformer.configuration.FileStorageProperties; -import eu.eudat.file.transformer.configuration.PdfProperties; -import eu.eudat.file.transformer.enums.DescriptionStatus; -import eu.eudat.file.transformer.enums.DmpBlueprintFieldCategory; -import eu.eudat.file.transformer.enums.DmpStatus; -import eu.eudat.file.transformer.enums.ReferenceType; -import eu.eudat.file.transformer.interfaces.FileTransformerClient; -import eu.eudat.file.transformer.interfaces.FileTransformerConfiguration; -import eu.eudat.file.transformer.models.description.DescriptionFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.DescriptionTemplateFileTransformerModel; -import eu.eudat.file.transformer.models.dmp.DmpFileTransformerModel; -import eu.eudat.file.transformer.models.dmp.DmpReferenceFileTransformerModel; -import eu.eudat.file.transformer.models.dmpblueprint.DmpBlueprintFileTransformerModel; -import eu.eudat.file.transformer.models.dmpblueprint.definition.ExtraFieldFileTransformerModelFileTransformerModel; -import eu.eudat.file.transformer.models.dmpblueprint.definition.FieldFileTransformerModel; -import eu.eudat.file.transformer.models.dmpblueprint.definition.SectionFileTransformerModel; -import eu.eudat.file.transformer.models.dmpblueprint.definition.SystemFieldFileTransformerModel; -import eu.eudat.file.transformer.model.enums.FileFormats; -import eu.eudat.file.transformer.models.misc.FileEnvelope; -import eu.eudat.file.transformer.model.file.FileEnvelopeInternal; -import eu.eudat.file.transformer.models.misc.FileFormat; -import eu.eudat.file.transformer.models.reference.ReferenceFileTransformerModel; -import eu.eudat.file.transformer.utils.pdf.PDFUtils; -import eu.eudat.file.transformer.utils.storage.FileStorageService; -import eu.eudat.file.transformer.utils.types.ParagraphStyle; -import eu.eudat.file.transformer.utils.word.WordBuilder; -import org.apache.poi.xwpf.usermodel.XWPFDocument; -import org.apache.poi.xwpf.usermodel.XWPFParagraph; -import org.apache.poi.xwpf.usermodel.XWPFRun; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; -import org.springframework.util.ResourceUtils; - -import javax.management.InvalidApplicationException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.time.Instant; -import java.util.*; -@Component -public class WordFileTransformer implements FileTransformerClient { - private final static Logger logger = LoggerFactory.getLogger(WordFileTransformer.class); - - private final static List FILE_FORMATS = List.of( - new FileFormat(FileFormats.PDF.getValue(), true, "fa-file-pdf-o"), - new FileFormat(FileFormats.DOCX.getValue(), true, "fa-file-word-o")); - - private final FilePathProperties fileTemplateProperties; - private final FileStorageProperties fileStorageProperties; - private final PdfProperties pdfProperties; - private final ApplicationContext applicationContext; - private final ObjectMapper objectMapper; - private final FileStorageService fileStorageService; - - @Autowired - public WordFileTransformer(FilePathProperties fileTemplateProperties, FileStorageProperties fileStorageProperties, PdfProperties pdfProperties, ApplicationContext applicationContext, FileStorageService fileStorageService) { - this.fileTemplateProperties = fileTemplateProperties; - this.fileStorageProperties = fileStorageProperties; - this.pdfProperties = pdfProperties; - this.applicationContext = applicationContext; - this.fileStorageService = fileStorageService; - this.objectMapper = new ObjectMapper(); - } - - @Override - public FileEnvelope exportDmp(DmpFileTransformerModel dmp) throws IOException { - FileFormats fileFormat = FileFormats.of(dmp.getVariant()); - return switch (fileFormat) { - case DOCX -> getWordDocument(dmp); - case PDF -> { - FileEnvelopeInternal wordFile = getWordDocument(dmp, true); - yield getPdfDocument(wordFile); - } - }; - } - - @Override - public FileEnvelope exportDescription(DescriptionFileTransformerModel descriptionFileTransformerModel, String format) throws InvalidApplicationException, IOException { - FileFormats fileFormat = FileFormats.of(format); - return switch (fileFormat) { - case DOCX -> getDescriptionWordDocument(descriptionFileTransformerModel); - case PDF -> { - FileEnvelopeInternal wordFile = getDescriptionWordDocumentInternal(descriptionFileTransformerModel); - yield getPdfDocument(wordFile); - } - }; - } - - - @Override - public DmpFileTransformerModel importDmp(FileEnvelope envelope) { - //Nothing to do here - return null; - } - - @Override - public DescriptionFileTransformerModel importDescription(FileEnvelope envelope) { - return null; - } - - @Override - public FileTransformerConfiguration getConfiguration() { - FileTransformerConfiguration configuration = new FileTransformerConfiguration(); - configuration.setFileTransformerId("docx/pdf"); - configuration.setExportVariants(FILE_FORMATS); - return configuration; - } - - private FileEnvelope getPdfDocument(FileEnvelopeInternal wordFile) throws IOException { - File pdfFile = PDFUtils.convertToPDF(wordFile, fileStorageProperties.getTemp(), pdfProperties.getUrl()); - FileEnvelope result = new FileEnvelope(); - result.setFilename(wordFile.getFilename().replaceAll(".docx", ".pdf")); - try (FileInputStream fis = new FileInputStream(pdfFile)) { - result.setFile(fileStorageService.storeFile(fis.readAllBytes())); - } - return result; - } - - private FileEnvelope getWordDocument(DmpFileTransformerModel dmp) throws IOException { - FileEnvelopeInternal wordFile = getWordDocument(dmp, true); - FileEnvelope result = new FileEnvelope(); - result.setFilename(wordFile.getFilename()); - try (FileInputStream fis = new FileInputStream(wordFile.getFile())) { - result.setFile(fileStorageService.storeFile(fis.readAllBytes())); - } - return result; - } - - private FileEnvelopeInternal getWordDocument(DmpFileTransformerModel dmpEntity, Boolean versioned) throws IOException { - WordBuilder wordBuilder = new WordBuilder(fileTemplateProperties, fileStorageProperties); - XWPFDocument document = new XWPFDocument(new FileInputStream(ResourceUtils.getFile(fileTemplateProperties.getWordTemplate()))); - - wordBuilder.fillFirstPage(dmpEntity, null, document, false); - - List grants = new ArrayList<>(); - List researchers = new ArrayList<>(); - List organizations = new ArrayList<>(); - List funders = new ArrayList<>(); - List projects = new ArrayList<>(); - if (dmpEntity.getDmpReferences() != null) { - grants = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Grants)).toList(); - researchers = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(reference -> reference.getType().equals(ReferenceType.Researcher)).toList(); - organizations = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Organizations)).toList(); - funders = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Funder)).toList(); - projects = dmpEntity.getDmpReferences().stream().filter(referenceFileModel -> referenceFileModel.getReference().getType().equals(ReferenceType.Project)).map(DmpReferenceFileTransformerModel::getReference).toList(); - } - -// int powered_pos = document.getParagraphs().size() - 3; - int powered_pos = wordBuilder.findPosOfPoweredBy(document); - XWPFParagraph powered_par = null; - XWPFParagraph argos_img_par = null; - if(powered_pos != -1) { - powered_par = document.getParagraphArray(powered_pos); - argos_img_par = document.getParagraphArray(powered_pos + 1); - } - - -// // DMP info on top of the document. -// wordBuilder.addParagraphContent("Data Management Plan Information", document, ParagraphStyle.HEADER1, BigInteger.ZERO); -// // DMP title custom style. -// wordBuilder.addParagraphContent(dmpEntity.getLabel(), document, ParagraphStyle.HEADER2, BigInteger.ZERO); -// wordBuilder.addParagraphContent(dmpEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Funder", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getGrant().getFunder() != null) -// wordBuilder.addParagraphContent(dmpEntity.getGrant().getFunder().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Grant", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// wordBuilder.addParagraphContent(dmpEntity.getGrant().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// -// wordBuilder.addParagraphContent("Organisations", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getOrganisations().size() > 0) { -// wordBuilder.addParagraphContent(dmpEntity.getOrganisations().stream().map(Organisation::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// -// wordBuilder.addParagraphContent("Researchers", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (dmpEntity.getResearchers().size() > 0) { -// wordBuilder.addParagraphContent(dmpEntity.getResearchers().stream().map(Researcher::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// -// /*wordBuilder.addParagraphContent("DMP Profile", document, ParagraphStyle.HEADER2, BigInteger.ZERO); -// if (dmpEntity.getProfile() != null){ -// wordBuilder.addParagraphContent(dmpEntity.getProfile().getLabel(), document, ParagraphStyle.TEXT, BigInteger.ZERO); -// }*/ -// -// // Page break at the end of the DMP title. -// XWPFParagraph parBreakDMP = document.createParagraph(); -// parBreakDMP.setPageBreak(true); -// -// wordBuilder.addParagraphContent("Datasets", document, ParagraphStyle.HEADER1, BigInteger.ZERO); -// // Space below Datasets. -// XWPFParagraph parBreakDatasets = document.createParagraph(); - - DmpBlueprintFileTransformerModel dmpBlueprintFileTransformerModel = dmpEntity.getBlueprint(); - for(SectionFileTransformerModel sectionFileTransformerModel : dmpBlueprintFileTransformerModel.getDefinitionFileTransformerModel().getSections()){ - wordBuilder.addParagraphContent("Section " + sectionFileTransformerModel.getOrdinal(), document, ParagraphStyle.HEADER1, BigInteger.ZERO, 0); - XWPFParagraph sectionInfoParagraph = document.createParagraph(); - sectionInfoParagraph.setSpacingBetween(1.0); - XWPFRun runSectionTitle = sectionInfoParagraph.createRun(); - runSectionTitle.setText("Title: "); - runSectionTitle.setColor("000000"); - XWPFRun runSectionTitleText = sectionInfoParagraph.createRun(); - runSectionTitleText.setText(sectionFileTransformerModel.getLabel()); - runSectionTitleText.setColor("116a78"); - XWPFParagraph sectionDescriptionParagraph = document.createParagraph(); - XWPFRun runSectionDescription = sectionDescriptionParagraph.createRun(); - runSectionDescription.setText("Description: "); - runSectionDescription.setColor("000000"); - XWPFRun runSectionDescriptionText = sectionDescriptionParagraph.createRun(); - runSectionDescriptionText.setText(sectionFileTransformerModel.getDescription()); - runSectionDescriptionText.setColor("116a78"); - - wordBuilder.addParagraphContent("Section Fields", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); - if (sectionFileTransformerModel.getFields() != null) { - sectionFileTransformerModel.getFields().sort(Comparator.comparingInt(FieldFileTransformerModel::getOrdinal)); - for (FieldFileTransformerModel fieldFileTransformerModel : sectionFileTransformerModel.getFields()) { - if (fieldFileTransformerModel.getCategory() == DmpBlueprintFieldCategory.System) { - SystemFieldFileTransformerModel systemField = (SystemFieldFileTransformerModel) fieldFileTransformerModel; - XWPFParagraph systemFieldParagraph = document.createParagraph(); - systemFieldParagraph.setSpacingBetween(1.0); - XWPFRun runSyStemFieldTitle = systemFieldParagraph.createRun(); - runSyStemFieldTitle.setText("Title: "); - runSyStemFieldTitle.setColor("000000"); - XWPFRun runSystemFieldTitleText = systemFieldParagraph.createRun(); - runSystemFieldTitleText.setText(systemField.getLabel()); - runSystemFieldTitleText.setColor("116a78"); - if (systemField.getDescription() != null && !systemField.getDescription().isEmpty()) { - XWPFParagraph systemFieldDescription = document.createParagraph(); - systemFieldDescription.setSpacingBetween(1.0); - XWPFRun runSyStemFieldDescription = systemFieldDescription.createRun(); - runSyStemFieldDescription.setText("Description: "); - runSyStemFieldDescription.setColor("000000"); - XWPFRun runSystemFieldDescriptionText = systemFieldDescription.createRun(); - runSystemFieldDescriptionText.setText(systemField.getDescription()); - runSystemFieldDescriptionText.setColor("116a78"); - } - XWPFParagraph systemFieldInput = document.createParagraph(); - systemFieldInput.setSpacingBetween(1.0); - XWPFRun runInput = systemFieldInput.createRun(); - runInput.setText("Input: "); - runInput.setColor("000000"); - Map dmpProperties = objectMapper.readValue(dmpEntity.getProperties(), HashMap.class); - switch (systemField.getSystemFieldType()) { - case Text: - XWPFRun runTitle = systemFieldInput.createRun(); - runTitle.setText(dmpEntity.getLabel()); - runTitle.setColor("116a78"); - break; - case HtmlText: - XWPFRun runDescription = systemFieldInput.createRun(); - runDescription.setText(dmpEntity.getDescription()); - runDescription.setColor("116a78"); - break; - case Researchers: - for (ReferenceFileTransformerModel researcher : researchers) { - XWPFRun runResearcher = systemFieldInput.createRun(); - runResearcher.setText("• " + researcher.getLabel()); - runResearcher.setColor("116a78"); - } - break; - case Organizations: - for (ReferenceFileTransformerModel organisation : organizations) { - XWPFRun runOrganisation = systemFieldInput.createRun(); - runOrganisation.setText("• " + organisation.getLabel()); - runOrganisation.setColor("116a78"); - } - break; - /* case Language: - XWPFRun runLanguage = systemFieldInput.createRun(); - runLanguage.setText(dmpProperties.get("language").toString()); - runLanguage.setColor("116a78"); - break;*/ - case Contact: - XWPFRun runContact = systemFieldInput.createRun(); - runContact.setText(dmpEntity.getCreator().getName()); - runContact.setColor("116a78"); - break; - case Funder: - if (!funders.isEmpty()) { - XWPFRun runFunder = systemFieldInput.createRun(); - runFunder.setText(funders.get(0).getLabel()); - runFunder.setColor("116a78"); - } - break; - case Grant: - if (!grants.isEmpty()) { - XWPFRun runGrant = systemFieldInput.createRun(); - runGrant.setText(grants.get(0).getLabel()); - runGrant.setColor("116a78"); - } - break; - case Project: - if (!projects.isEmpty()) { - XWPFRun runProject = systemFieldInput.createRun(); - runProject.setText(projects.get(0).getLabel()); - runProject.setColor("116a78"); - } - break; - case License: - if (dmpProperties.containsKey("license")) { - XWPFRun runLicense = systemFieldInput.createRun(); - runLicense.setText(dmpProperties.get("license").toString()); - runLicense.setColor("116a78"); - } - break; - case AccessRights: - if (dmpProperties.containsKey("visible")) { - XWPFRun runAccessRights = systemFieldInput.createRun(); - runAccessRights.setText(dmpProperties.get("visible").toString()); - runAccessRights.setColor("116a78"); - } - break; - } - document.createParagraph(); - } else if (fieldFileTransformerModel.getCategory() == DmpBlueprintFieldCategory.Extra) { - ExtraFieldFileTransformerModelFileTransformerModel extraFieldFileTransformerModel = (ExtraFieldFileTransformerModelFileTransformerModel) fieldFileTransformerModel; - XWPFParagraph extraFieldParagraph = document.createParagraph(); - extraFieldParagraph.setSpacingBetween(1.0); - XWPFRun runExtraFieldLabel = extraFieldParagraph.createRun(); - runExtraFieldLabel.setText(extraFieldFileTransformerModel.getLabel()); - runExtraFieldLabel.setColor("116a78"); - if (extraFieldFileTransformerModel.getDescription() != null && !extraFieldFileTransformerModel.getDescription().isEmpty()) { - XWPFRun runExtraFieldDescription = extraFieldParagraph.createRun(); - runExtraFieldDescription.setText(extraFieldFileTransformerModel.getDescription()); - runExtraFieldDescription.setColor("116a78"); - } - XWPFRun runExtraFieldInput = extraFieldParagraph.createRun(); - Map dmpProperties = objectMapper.readValue(dmpEntity.getProperties(), HashMap.class); - if (dmpProperties.containsKey(fieldFileTransformerModel.getId()) && dmpProperties.get(fieldFileTransformerModel.getId()) != null) { - runExtraFieldInput.setText((String) dmpProperties.get(fieldFileTransformerModel.getId())); - } - runExtraFieldInput.setColor("116a78"); - } - } - } - final Boolean isFinalized = dmpEntity.getStatus() == DmpStatus.Finalized; - final Boolean isPublic = dmpEntity.getPublicAfter() != null && dmpEntity.getPublicAfter().isAfter(Instant.now()); - List descriptions = dmpEntity.getDescriptions().stream() - .filter(item -> item.getStatus() != DescriptionStatus.Canceled) - .filter(item -> !isPublic && !isFinalized || item.getStatus() == DescriptionStatus.Finalized) - .filter(item -> item.getSectionId().equals(sectionFileTransformerModel.getId())) //TODO - .sorted(Comparator.comparing(DescriptionFileTransformerModel::getCreatedAt)).toList(); - List descriptionTemplateFileTransformerModels = descriptions.stream().map(DescriptionFileTransformerModel::getDescriptionTemplate).toList(); - - if(!descriptionTemplateFileTransformerModels.isEmpty()){ - wordBuilder.addParagraphContent("Section descriptions", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); - wordBuilder.addParagraphContent("Description Templates", document, ParagraphStyle.HEADER4, BigInteger.ZERO, 0); - for(DescriptionTemplateFileTransformerModel descriptionTemplateFileTransformerModelEntity : descriptionTemplateFileTransformerModels){ - XWPFParagraph templateParagraph = document.createParagraph(); - XWPFRun runTemplateLabel = templateParagraph.createRun(); - runTemplateLabel.setText("• " + descriptionTemplateFileTransformerModelEntity.getLabel()); - runTemplateLabel.setColor("116a78"); - } - - - descriptions - .forEach(datasetEntity -> { - DescriptionTemplateFileTransformerModel descriptionTemplateFileTransformerModelFileModel = datasetEntity.getDescriptionTemplate(); - - // Dataset Description custom style. - XWPFParagraph datasetDescriptionParagraph = document.createParagraph(); - datasetDescriptionParagraph.setStyle("Heading4"); - datasetDescriptionParagraph.setSpacingBetween(1.5); - XWPFRun datasetDescriptionRun = datasetDescriptionParagraph.createRun(); - datasetDescriptionRun.setText("Dataset Description"); - //datasetDescriptionRun.setColor("2E75B6"); - //datasetDescriptionRun.setBold(true); - datasetDescriptionRun.setFontSize(15); - - - // Custom style for the Dataset title. - //wordBuilder.addParagraphContent("Title: " + datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); - XWPFParagraph datasetLabelParagraph = document.createParagraph(); -// datasetLabelParagraph.setStyle("Heading2"); - datasetLabelParagraph.setSpacingBetween(1.0); - XWPFRun runDatasetTitle1 = datasetLabelParagraph.createRun(); - runDatasetTitle1.setText("Title: "); - runDatasetTitle1.setColor("000000"); - //runDatasetTitle1.setBold(true); - //runDatasetTitle1.setFontSize(12); - XWPFRun runDatasetTitle = datasetLabelParagraph.createRun(); - runDatasetTitle.setText(datasetEntity.getLabel()); - runDatasetTitle.setColor("116a78"); - //runDatasetTitle.setBold(true); - //runDatasetTitle.setFontSize(12); - - XWPFParagraph datasetTemplateParagraph = document.createParagraph(); -// datasetTemplateParagraph.setStyle("Heading3"); - XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); - runDatasetTemplate1.setText("Template: "); - runDatasetTemplate1.setColor("000000"); - //runDatasetTemplate1.setBold(true); - //runDatasetTemplate1.setFontSize(12); - XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); - runDatasetTemplate.setText(descriptionTemplateFileTransformerModelFileModel.getLabel()); - runDatasetTemplate.setColor("116a78"); - //runDatasetTemplate.setBold(true); - //runDatasetTemplate.setFontSize(12); - -// /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); -// externalReferencesParagraph.setStyle("Heading3"); -// XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); -// externalReferencesRun.setText("External References"); -// externalReferencesRun.setColor("2E75B6"); -// externalReferencesRun.setBold(true); -// externalReferencesRun.setFontSize(12); -// -// wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getDatasetDataRepositories().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getDatasetDataRepositories().stream().map(DatasetDataRepository::getDataRepository).map(DataRepository::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("External Datasets", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getDatasetExternalDatasets().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getDatasetExternalDatasets().stream().map(DatasetExternalDataset::getExternalDataset).map(ExternalDataset::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("Registries", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getRegistries().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getRegistries().stream().map(Registry::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// wordBuilder.addParagraphContent("Services", document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// if (datasetEntity.getServices().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.TEXT, BigInteger.ZERO); -// } -// *//*wordBuilder.addParagraphContent("Tags", document, ParagraphStyle.HEADER3, BigInteger.ZERO); -// if (datasetEntity.().size() > 0) { -// wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) -// , document, ParagraphStyle.HEADER4, BigInteger.ZERO); -// }*/ -// -// - - XWPFParagraph datasetDescParagraph = document.createParagraph(); - XWPFRun runDatasetDescription1 = datasetDescParagraph.createRun(); - runDatasetDescription1.setText("Description: "); - runDatasetDescription1.setColor("000000"); - XWPFRun runDatasetDescription = datasetDescParagraph.createRun(); - runDatasetDescription.setText(descriptionTemplateFileTransformerModelFileModel.getLabel()); - runDatasetDescription.setColor("116a78"); - //wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO, 0); - - document.createParagraph(); - - - try { - wordBuilder.build(document, datasetEntity.getDescriptionTemplate()); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - // Page break at the end of the Dataset. - XWPFParagraph parBreakDataset = document.createParagraph(); - parBreakDataset.setPageBreak(true); - }); - } - } - -// // Removes the top empty headings. -// for (int i = 0; i < 6; i++) { -// document.removeBodyElement(0); -// } - - - if(powered_pos != -1) { - document.getLastParagraph().setPageBreak(false); - document.createParagraph(); - document.setParagraph(powered_par, document.getParagraphs().size() - 1); - - document.createParagraph(); - document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); - - document.removeBodyElement(powered_pos + 1); - document.removeBodyElement(powered_pos + 1); - } - - wordBuilder.fillFooter(dmpEntity, null, document, false); - - String fileName; - if (!grants.isEmpty() && grants.get(0).getLabel() != null) { - fileName = "DMP_" + grants.get(0).getLabel(); - } - else { - fileName = "DMP_" + dmpEntity.getLabel(); - } - if (versioned) { - fileName += "_" + dmpEntity.getVersion(); - } - // fileName = fileName.replaceAll("[^a-zA-Z0-9+ ]", ""); - FileEnvelopeInternal exportEnvelope = new FileEnvelopeInternal(); - exportEnvelope.setFilename(fileName + ".docx"); - String uuid = UUID.randomUUID().toString(); - File exportFile = new File(fileStorageProperties.getTemp() + "\\" + uuid + ".docx"); - FileOutputStream out = new FileOutputStream(exportFile); - document.write(out); - out.close(); - exportEnvelope.setFile(exportFile); - - return exportEnvelope; - } - - private FileEnvelope getDescriptionWordDocument(DescriptionFileTransformerModel descriptionFileTransformerModel) throws IOException { - FileEnvelopeInternal wordFile = getDescriptionWordDocumentInternal(descriptionFileTransformerModel); - FileEnvelope fileEnvelope = new FileEnvelope(); - fileEnvelope.setFilename(wordFile.getFilename()); - try (FileInputStream fis = new FileInputStream(wordFile.getFile())) { - fileEnvelope.setFile(fileStorageService.storeFile(fis.readAllBytes())); - } - return fileEnvelope; - } - - private FileEnvelopeInternal getDescriptionWordDocumentInternal(DescriptionFileTransformerModel descriptionFileTransformerModelEntityEntity) throws IOException { - WordBuilder wordBuilder = new WordBuilder(fileTemplateProperties, fileStorageProperties); - DmpFileTransformerModel dmpEntity = descriptionFileTransformerModelEntityEntity.getDmp(); - if (dmpEntity == null) { - throw new IllegalArgumentException("Dmp is invalid"); - } - XWPFDocument document = new XWPFDocument(new FileInputStream(ResourceUtils.getFile(fileTemplateProperties.getWordDescriptionTemplate()))); - - wordBuilder.fillFirstPage(dmpEntity, descriptionFileTransformerModelEntityEntity, document, true); - wordBuilder.fillFooter(dmpEntity, descriptionFileTransformerModelEntityEntity, document, true); - - int powered_pos = wordBuilder.findPosOfPoweredBy(document); - XWPFParagraph powered_par = null; - XWPFParagraph argos_img_par = null; - if(powered_pos != -1) { - powered_par = document.getParagraphArray(powered_pos); - argos_img_par = document.getParagraphArray(powered_pos + 1); - } - -// wordBuilder.addParagraphContent(datasetEntity.getLabel(), document, ParagraphStyle.HEADER1, BigInteger.ZERO); - - // Space below Dataset title. -// XWPFParagraph parBreakDataset = document.createParagraph(); -// -// XWPFParagraph datasetTemplateParagraph = document.createParagraph(); -// datasetTemplateParagraph.setStyle("Heading2"); -// XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); -// runDatasetTemplate1.setText("Template: "); -// runDatasetTemplate1.setBold(true); -// runDatasetTemplate1.setFontSize(12); -// XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); -// runDatasetTemplate.setText(datasetEntity.getProfile().getLabel()); -// runDatasetTemplate.setColor("2E75B6"); -// runDatasetTemplate.setBold(true); -// runDatasetTemplate.setFontSize(12); -// -// wordBuilder.addParagraphContent(datasetEntity.getDescription(), document, ParagraphStyle.HTML, BigInteger.ZERO); - - /*XWPFParagraph externalReferencesParagraph = document.createParagraph(); - externalReferencesParagraph.setStyle("Heading2"); - XWPFRun externalReferencesRun = externalReferencesParagraph.createRun(); - externalReferencesRun.setText("External References"); - externalReferencesRun.setColor("2E75B6"); - externalReferencesRun.setBold(true); - externalReferencesRun.setFontSize(12); - - wordBuilder.addParagraphContent("Data Repositories", document, ParagraphStyle.HEADER3, BigInteger.ZERO); - if (datasetEntity.getDatasetDataRepositories().size() > 0) { - wordBuilder.addParagraphContent(datasetEntity.getDatasetDataRepositories().stream().map(DatasetDataRepository::getDataRepository).map(DataRepository::getLabel).collect(Collectors.joining(", ")) - , document, ParagraphStyle.TEXT, BigInteger.ZERO); - } - wordBuilder.addParagraphContent("External Datasets", document, ParagraphStyle.HEADER3, BigInteger.ZERO); - if (datasetEntity.getDatasetExternalDatasets().size() > 0) { - wordBuilder.addParagraphContent(datasetEntity.getDatasetExternalDatasets().stream().map(DatasetExternalDataset::getExternalDataset).map(ExternalDataset::getLabel).collect(Collectors.joining(", ")) - , document, ParagraphStyle.TEXT, BigInteger.ZERO); - } - wordBuilder.addParagraphContent("Registries", document, ParagraphStyle.HEADER3, BigInteger.ZERO); - if (datasetEntity.getRegistries().size() > 0) { - wordBuilder.addParagraphContent(datasetEntity.getRegistries().stream().map(Registry::getLabel).collect(Collectors.joining(", ")) - , document, ParagraphStyle.TEXT, BigInteger.ZERO); - } - wordBuilder.addParagraphContent("Services", document, ParagraphStyle.HEADER3, BigInteger.ZERO); - if (datasetEntity.getServices().size() > 0) { - wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) - , document, ParagraphStyle.TEXT, BigInteger.ZERO); - }*/ - /*wordBuilder.addParagraphContent("Tags", document, ParagraphStyle.HEADER3, BigInteger.ZERO); - if (datasetEntity.().size() > 0) { - wordBuilder.addParagraphContent(datasetEntity.getServices().stream().map(DatasetService::getService).map(Service::getLabel).collect(Collectors.joining(", ")) - , document, ParagraphStyle.HEADER4, BigInteger.ZERO); - }*/ - -// wordBuilder.addParagraphContent("Dataset Description", document, ParagraphStyle.HEADER2, BigInteger.ZERO); - wordBuilder.build(document, descriptionFileTransformerModelEntityEntity.getDescriptionTemplate()); - String label = descriptionFileTransformerModelEntityEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); -// File exportFile = new File(label + ".docx"); - - // Removes the top empty headings. -// for (int i = 0; i < 6; i++) { -// document.removeBodyElement(0); -// } - - if(powered_pos != -1) { - document.getLastParagraph().setPageBreak(false); - document.createParagraph(); - document.setParagraph(powered_par, document.getParagraphs().size() - 1); - - document.createParagraph(); - document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); - - document.removeBodyElement(powered_pos + 1); - document.removeBodyElement(powered_pos + 1); - } - - label = descriptionFileTransformerModelEntityEntity.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); - FileEnvelopeInternal exportEnvelope = new FileEnvelopeInternal(); - exportEnvelope.setFilename(label + ".docx"); - String uuid = UUID.randomUUID().toString(); - File exportFile = new File(fileStorageProperties.getTemp() + uuid + ".docx"); - FileOutputStream out = new FileOutputStream(exportFile); - document.write(out); - out.close(); - exportEnvelope.setFile(exportFile); - - return exportEnvelope; - //FileOutputStream out = new FileOutputStream(exportFile); - // document.write(out); - // out.close(); - // return exportFile; - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/model/enums/FileFormats.java b/core/src/main/java/eu/eudat/file/transformer/model/enums/FileFormats.java index cb45367..987dd60 100644 --- a/core/src/main/java/eu/eudat/file/transformer/model/enums/FileFormats.java +++ b/core/src/main/java/eu/eudat/file/transformer/model/enums/FileFormats.java @@ -2,13 +2,12 @@ package eu.eudat.file.transformer.model.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -import eu.eudat.file.transformer.enums.DatabaseEnum; -import eu.eudat.file.transformer.enums.DmpVersionStatus; -import eu.eudat.file.transformer.enums.EnumUtils; +import eu.eudat.commonmodels.enums.EnumUtils; +import eu.eudat.commonmodels.enums.EnumValueProvider; import java.util.Map; -public enum FileFormats implements DatabaseEnum { +public enum FileFormats implements EnumValueProvider { DOCX("docx"), PDF("pdf"); diff --git a/core/src/main/java/eu/eudat/file/transformer/model/enums/ParagraphStyle.java b/core/src/main/java/eu/eudat/file/transformer/model/enums/ParagraphStyle.java new file mode 100644 index 0000000..319e3de --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/model/enums/ParagraphStyle.java @@ -0,0 +1,31 @@ +package eu.eudat.file.transformer.model.enums; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import eu.eudat.commonmodels.enums.EnumUtils; +import eu.eudat.commonmodels.enums.EnumValueProvider; + +import java.util.Map; + +public enum ParagraphStyle implements EnumValueProvider { + TEXT(0), HEADER1(1), HEADER2(2), HEADER3(3), HEADER4(4), TITLE(5), FOOTER(6), COMMENT(7), HEADER5(8), HEADER6(9), HTML(10), IMAGE(11); + + private final Integer value; + + private ParagraphStyle(Integer value) { + this.value = value; + } + + @JsonValue + public Integer getValue() { + return value; + } + + + private static final Map map = EnumUtils.getEnumValueMap(ParagraphStyle.class); + + @JsonCreator + public static ParagraphStyle of(Integer i) { + return map.get(i); + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/model/file/FileEnvelopeInternal.java b/core/src/main/java/eu/eudat/file/transformer/model/file/FileEnvelopeInternal.java deleted file mode 100644 index c3b2501..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/model/file/FileEnvelopeInternal.java +++ /dev/null @@ -1,28 +0,0 @@ -package eu.eudat.file.transformer.model.file; - -import java.io.File; - -/** - * Created by ikalyvas on 3/6/2018. - */ - -public class FileEnvelopeInternal { - private String filename; - private File file; - - public String getFilename() { - return filename; - } - - public void setFilename(String filename) { - this.filename = filename; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/interfaces/ApplierWithValue.java b/core/src/main/java/eu/eudat/file/transformer/model/interfaces/ApplierWithValue.java similarity index 70% rename from core/src/main/java/eu/eudat/file/transformer/utils/interfaces/ApplierWithValue.java rename to core/src/main/java/eu/eudat/file/transformer/model/interfaces/ApplierWithValue.java index d14f7ee..f614ec7 100644 --- a/core/src/main/java/eu/eudat/file/transformer/utils/interfaces/ApplierWithValue.java +++ b/core/src/main/java/eu/eudat/file/transformer/model/interfaces/ApplierWithValue.java @@ -1,4 +1,4 @@ -package eu.eudat.file.transformer.utils.interfaces; +package eu.eudat.file.transformer.model.interfaces; /** * Created by ikalyvas on 2/27/2018. diff --git a/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfService.java b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfService.java new file mode 100644 index 0000000..26f3726 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfService.java @@ -0,0 +1,5 @@ +package eu.eudat.file.transformer.service.pdf; + +public interface PdfService { + byte[] convertToPDF(byte[] file); +} diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/FilePathConfiguration.java b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceConfiguration.java similarity index 52% rename from core/src/main/java/eu/eudat/file/transformer/configuration/FilePathConfiguration.java rename to core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceConfiguration.java index ce08a8f..338c8be 100644 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/FilePathConfiguration.java +++ b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceConfiguration.java @@ -1,9 +1,9 @@ -package eu.eudat.file.transformer.configuration; +package eu.eudat.file.transformer.service.pdf; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration -@EnableConfigurationProperties({FilePathProperties.class}) -public class FilePathConfiguration { +@EnableConfigurationProperties({PdfServiceProperties.class}) +public class PdfServiceConfiguration { } diff --git a/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceImpl.java b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceImpl.java new file mode 100644 index 0000000..b828eaf --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceImpl.java @@ -0,0 +1,36 @@ +package eu.eudat.file.transformer.service.pdf; + +import org.springframework.core.io.ByteArrayResource; +import org.springframework.http.MediaType; +import org.springframework.http.client.MultipartBodyBuilder; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.UUID; + +@Component +public class PdfServiceImpl implements PdfService { + + private final PdfServiceProperties pdfServiceProperties; + + public PdfServiceImpl(PdfServiceProperties pdfServiceProperties) { + this.pdfServiceProperties = pdfServiceProperties; + } + + @Override + public byte[] convertToPDF(byte[] file) { + WebClient webClient = WebClient.builder().baseUrl(pdfServiceProperties.getUrl()).build(); + MultipartBodyBuilder builder = new MultipartBodyBuilder(); + builder.part("files", new ByteArrayResource(file)).filename(UUID.randomUUID() + ".docx"); + + return webClient.post().uri("forms/libreoffice/convert") + .headers(httpHeaders -> { + httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); + httpHeaders.add("Content-disposition", "attachment; filename=" + UUID.randomUUID() + ".pdf"); + httpHeaders.add("Content-type", "application/pdf"); + }) + .body(BodyInserters.fromMultipartData(builder.build())) + .retrieve().bodyToMono(byte[].class).block(); + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/PdfProperties.java b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceProperties.java similarity index 72% rename from core/src/main/java/eu/eudat/file/transformer/configuration/PdfProperties.java rename to core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceProperties.java index d794a2b..0f264ca 100644 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/PdfProperties.java +++ b/core/src/main/java/eu/eudat/file/transformer/service/pdf/PdfServiceProperties.java @@ -1,14 +1,14 @@ -package eu.eudat.file.transformer.configuration; +package eu.eudat.file.transformer.service.pdf; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.ConstructorBinding; @ConfigurationProperties(prefix = "pdf.converter") -public class PdfProperties { +public class PdfServiceProperties { private final String url; @ConstructorBinding - public PdfProperties(String url) { + public PdfServiceProperties(String url) { this.url = url; } diff --git a/core/src/main/java/eu/eudat/file/transformer/service/pid/PidService.java b/core/src/main/java/eu/eudat/file/transformer/service/pid/PidService.java new file mode 100644 index 0000000..23c2250 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/pid/PidService.java @@ -0,0 +1,10 @@ +package eu.eudat.file.transformer.service.pid; + +import eu.eudat.file.transformer.model.PidLink; + +import java.util.List; + +public interface PidService { + PidLink getPid(String pidType); + List loadPidLinks(); +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/pid/PidServiceImpl.java b/core/src/main/java/eu/eudat/file/transformer/service/pid/PidServiceImpl.java new file mode 100644 index 0000000..c95c962 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/pid/PidServiceImpl.java @@ -0,0 +1,50 @@ +package eu.eudat.file.transformer.service.pid; + +import com.fasterxml.jackson.databind.ObjectMapper; +import eu.eudat.file.transformer.service.wordfiletransformer.WordFileTransformerServiceProperties; +import eu.eudat.file.transformer.model.PidLink; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.util.ResourceUtils; + +import java.io.IOException; +import java.util.List; + +@Component +public class PidServiceImpl implements PidService { + private static final Logger logger = LoggerFactory.getLogger(PidServiceImpl.class); + private final WordFileTransformerServiceProperties properties; + private final ObjectMapper objectMapper = new ObjectMapper(); + private List pidLinks = null; + public PidServiceImpl(WordFileTransformerServiceProperties properties) { + this.properties = properties; + } + + @Override + public List loadPidLinks() { + if (pidLinks != null) return pidLinks; + try { + pidLinks = objectMapper.readValue(ResourceUtils.getFile(this.properties.getPidTemplate()), PidLinksWrapper.class).getPidLinks(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + return pidLinks; + } + @Override + public PidLink getPid(String pidType) { + return this.loadPidLinks().stream().filter(pl -> pl.getPid().equals(pidType)).findFirst().orElse(null); + } + + protected static class PidLinksWrapper { + private List pidLinks; + + public List getPidLinks() { + return pidLinks; + } + + public void setPidLinks(List pidLinks) { + this.pidLinks = pidLinks; + } + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageService.java b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageService.java new file mode 100644 index 0000000..d9df16f --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageService.java @@ -0,0 +1,7 @@ +package eu.eudat.file.transformer.service.storage; + +public interface FileStorageService { + String storeFile(byte[] data); + + byte[] readFile(String fileRef); +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceConfiguration.java b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceConfiguration.java new file mode 100644 index 0000000..2ea965e --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceConfiguration.java @@ -0,0 +1,9 @@ +package eu.eudat.file.transformer.service.storage; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties({FileStorageServiceProperties.class}) +public class FileStorageServiceConfiguration { +} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/storage/FileStorageService.java b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceImpl.java similarity index 71% rename from core/src/main/java/eu/eudat/file/transformer/utils/storage/FileStorageService.java rename to core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceImpl.java index 5a08e1a..ad4d0a0 100644 --- a/core/src/main/java/eu/eudat/file/transformer/utils/storage/FileStorageService.java +++ b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceImpl.java @@ -1,6 +1,5 @@ -package eu.eudat.file.transformer.utils.storage; +package eu.eudat.file.transformer.service.storage; -import eu.eudat.file.transformer.configuration.FileStorageProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -12,22 +11,24 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; +import java.util.Locale; import java.util.UUID; @Service -public class FileStorageService { - private final static Logger logger = LoggerFactory.getLogger(FileStorageService.class); +public class FileStorageServiceImpl implements FileStorageService { + private final static Logger logger = LoggerFactory.getLogger(FileStorageServiceImpl.class); - private final FileStorageProperties properties; + private final FileStorageServiceProperties properties; @Autowired - public FileStorageService(FileStorageProperties properties) { + public FileStorageServiceImpl(FileStorageServiceProperties properties) { this.properties = properties; } + @Override public String storeFile(byte[] data) { try { - String fileName = UUID.randomUUID().toString(); + String fileName = UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); Path storagePath = Paths.get(properties.getTransientPath() + "/" + fileName); Files.write(storagePath, data, StandardOpenOption.CREATE_NEW); return fileName; @@ -37,12 +38,13 @@ public class FileStorageService { return null; } + @Override public byte[] readFile(String fileRef) { try (FileInputStream inputStream = new FileInputStream(properties.getTransientPath() + "/" + fileRef)) { return inputStream.readAllBytes(); } catch (IOException e) { logger.error(e.getMessage(), e); } - return new byte[1]; + return new byte[0]; } } diff --git a/core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageProperties.java b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceProperties.java similarity index 74% rename from core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageProperties.java rename to core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceProperties.java index 5ba191d..2402ec5 100644 --- a/core/src/main/java/eu/eudat/file/transformer/configuration/FileStorageProperties.java +++ b/core/src/main/java/eu/eudat/file/transformer/service/storage/FileStorageServiceProperties.java @@ -1,15 +1,15 @@ -package eu.eudat.file.transformer.configuration; +package eu.eudat.file.transformer.service.storage; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.bind.ConstructorBinding; @ConfigurationProperties(prefix = "file.storage") -public class FileStorageProperties { +public class FileStorageServiceProperties { private final String temp; private final String transientPath; @ConstructorBinding - public FileStorageProperties(String temp, String transientPath) { + public FileStorageServiceProperties(String temp, String transientPath) { this.temp = temp; this.transientPath = transientPath; } diff --git a/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerService.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerService.java new file mode 100644 index 0000000..897104e --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerService.java @@ -0,0 +1,485 @@ +package eu.eudat.file.transformer.service.wordfiletransformer; + +import eu.eudat.commonmodels.enums.DescriptionStatus; +import eu.eudat.commonmodels.enums.DmpAccessType; +import eu.eudat.commonmodels.enums.DmpStatus; +import eu.eudat.commonmodels.models.dmp.DmpBlueprintValueModel; +import eu.eudat.commonmodels.models.dmp.DmpModel; +import eu.eudat.commonmodels.models.FileEnvelopeModel; +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.descriptiotemplate.DescriptionTemplateModel; +import eu.eudat.commonmodels.models.dmpblueprint.*; +import eu.eudat.commonmodels.models.dmpreference.DmpReferenceModel; +import eu.eudat.commonmodels.models.reference.ReferenceModel; +import eu.eudat.file.transformer.interfaces.FileTransformerClient; +import eu.eudat.file.transformer.interfaces.FileTransformerConfiguration; +import eu.eudat.file.transformer.model.enums.FileFormats; +import eu.eudat.file.transformer.models.misc.FileFormat; +import eu.eudat.file.transformer.service.pdf.PdfService; +import eu.eudat.file.transformer.model.enums.ParagraphStyle; +import eu.eudat.file.transformer.service.storage.FileStorageService; +import eu.eudat.file.transformer.service.wordfiletransformer.word.WordBuilder; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; +import org.springframework.util.ResourceUtils; + +import javax.management.InvalidApplicationException; +import java.io.*; +import java.math.BigInteger; +import java.time.Instant; +import java.util.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class WordFileTransformerService implements FileTransformerClient { + private final static Logger logger = LoggerFactory.getLogger(WordFileTransformerService.class); + + private final static List FILE_FORMATS = List.of( + new FileFormat(FileFormats.PDF.getValue(), true, "fa-file-pdf-o"), + new FileFormat(FileFormats.DOCX.getValue(), true, "fa-file-word-o")); + + private final WordFileTransformerServiceProperties wordFileTransformerServiceProperties; + private final PdfService pdfService; + private final WordBuilder wordBuilder; + private final FileStorageService storageService; + @Autowired + public WordFileTransformerService( + WordFileTransformerServiceProperties wordFileTransformerServiceProperties, + PdfService pdfService, WordBuilder wordBuilder, FileStorageService storageService) { + this.wordFileTransformerServiceProperties = wordFileTransformerServiceProperties; + this.pdfService = pdfService; + this.wordBuilder = wordBuilder; + this.storageService = storageService; + } + + @Override + public FileEnvelopeModel exportDmp(DmpModel dmp, String variant) throws IOException, InvalidApplicationException { + FileFormats fileFormat = FileFormats.of(variant); + byte[] bytes = this.buildDmpWordDocument(dmp); + String filename = switch (fileFormat) { + case DOCX -> this.getDmpFileName(dmp, ".docx"); + case PDF -> { + bytes = this.pdfService.convertToPDF(bytes); + yield this.getDmpFileName(dmp, ".pdf"); + } + default -> throw new InvalidApplicationException("Invalid type " + fileFormat); + }; + String fileRef = this.storageService.storeFile(bytes); + FileEnvelopeModel wordFile = new FileEnvelopeModel(); + wordFile.setFileRef(fileRef); + wordFile.setFilename(filename); + return wordFile; + } + + @Override + public FileEnvelopeModel exportDescription(DescriptionModel descriptionModel, String variant) throws InvalidApplicationException, IOException { + FileFormats fileFormat = FileFormats.of(variant); + byte[] bytes = this.buildDescriptionWordDocument(descriptionModel); + String filename = switch (fileFormat) { + case DOCX -> this.getDescriptionFileName(descriptionModel, ".docx"); + case PDF -> { + bytes = this.pdfService.convertToPDF(bytes); + yield this.getDescriptionFileName(descriptionModel, ".pdf"); + } + default -> throw new InvalidApplicationException("Invalid type " + fileFormat); + }; + String fileRef = this.storageService.storeFile(bytes); + + FileEnvelopeModel wordFile = new FileEnvelopeModel(); + wordFile.setFileRef(fileRef); + wordFile.setFilename(filename); + return wordFile; + } + + + @Override + public DmpModel importDmp(FileEnvelopeModel envelope) { + throw new UnsupportedOperationException("import not supported"); + } + + @Override + public DescriptionModel importDescription(FileEnvelopeModel envelope) { + throw new UnsupportedOperationException("import not supported"); + } + + @Override + public FileTransformerConfiguration getConfiguration() { + FileTransformerConfiguration configuration = new FileTransformerConfiguration(); + configuration.setFileTransformerId("docx/pdf"); + configuration.setExportVariants(FILE_FORMATS); + configuration.setImportVariants(null); + configuration.setUseSharedStorage(true); + return configuration; + } + + private List getReferenceModelOfTypeCode(DmpModel dmp, String code, UUID blueprintId){ + List response = new ArrayList<>(); + if (dmp.getReferences() == null) return response; + for (DmpReferenceModel dmpReferenceModel : dmp.getReferences()){ + if (dmpReferenceModel.getReference() != null && dmpReferenceModel.getReference().getType() != null && dmpReferenceModel.getReference().getType().getCode() != null && dmpReferenceModel.getReference().getType().getCode().equals(code)){ + if (blueprintId == null || (dmpReferenceModel.getData() != null && blueprintId.equals(dmpReferenceModel.getData().getBlueprintFieldId()))) response.add(dmpReferenceModel.getReference()); + + } + } + return response; + } + + + private byte[] buildDmpWordDocument(DmpModel dmpEntity) throws IOException, InvalidApplicationException { + if (dmpEntity == null) throw new IllegalArgumentException("DmpEntity required"); + DmpBlueprintModel dmpBlueprintModel = dmpEntity.getDmpBlueprint(); + if (dmpBlueprintModel == null) throw new IllegalArgumentException("DmpBlueprint required"); + if (dmpBlueprintModel.getDefinition() == null) throw new IllegalArgumentException("DmpBlueprint Definition required"); + if (dmpBlueprintModel.getDefinition().getSections() == null) throw new IllegalArgumentException("DmpBlueprint Section required"); + + XWPFDocument document = new XWPFDocument(new FileInputStream(ResourceUtils.getFile(this.wordFileTransformerServiceProperties.getWordDmpTemplate()))); + + this.wordBuilder.fillFirstPage(dmpEntity, null, document, false); + + int powered_pos = this.wordBuilder.findPosOfPoweredBy(document); + XWPFParagraph powered_par = null; + XWPFParagraph argos_img_par = null; + if (powered_pos != -1) { + powered_par = document.getParagraphArray(powered_pos); + argos_img_par = document.getParagraphArray(powered_pos + 1); + } + + for (SectionModel sectionModel : dmpBlueprintModel.getDefinition().getSections()) { + buildDmpSection(dmpEntity, sectionModel, document); + } + + if (powered_pos != -1) { + document.getLastParagraph().setPageBreak(false); + document.createParagraph(); + document.setParagraph(powered_par, document.getParagraphs().size() - 1); + + document.createParagraph(); + document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); + + document.removeBodyElement(powered_pos + 1); + document.removeBodyElement(powered_pos + 1); + } + + this.wordBuilder.fillFooter(dmpEntity, null, document); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + document.write(out); + byte[] bytes = out.toByteArray(); + out.close(); + + return bytes; + } + + private void buildDmpSection(DmpModel dmpEntity, SectionModel sectionModel, XWPFDocument document) throws InvalidApplicationException { + this.wordBuilder.addParagraphContent("Section " + sectionModel.getOrdinal(), document, ParagraphStyle.HEADER1, BigInteger.ZERO, 0); + XWPFParagraph sectionInfoParagraph = document.createParagraph(); + sectionInfoParagraph.setSpacingBetween(1.0); + XWPFRun runSectionTitle = sectionInfoParagraph.createRun(); + runSectionTitle.setText("Title: "); + runSectionTitle.setColor("000000"); + XWPFRun runSectionTitleText = sectionInfoParagraph.createRun(); + runSectionTitleText.setText(sectionModel.getLabel()); + runSectionTitleText.setColor("116a78"); + XWPFParagraph sectionDescriptionParagraph = document.createParagraph(); + XWPFRun runSectionDescription = sectionDescriptionParagraph.createRun(); + runSectionDescription.setText("Description: "); + runSectionDescription.setColor("000000"); + XWPFRun runSectionDescriptionText = sectionDescriptionParagraph.createRun(); + runSectionDescriptionText.setText(sectionModel.getDescription()); + runSectionDescriptionText.setColor("116a78"); + + this.wordBuilder.addParagraphContent("Section Fields", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); + if (sectionModel.getFields() != null) { + sectionModel.getFields().sort(Comparator.comparingInt(FieldModel::getOrdinal)); + for (FieldModel fieldModel : sectionModel.getFields()) { + buildDmpSectionField(dmpEntity, document, fieldModel); + } + } + + final boolean isFinalized = dmpEntity.getStatus() != null && dmpEntity.getStatus().equals(DmpStatus.Finalized); + final boolean isPublic = dmpEntity.getPublicAfter() != null && dmpEntity.getPublicAfter().isAfter(Instant.now()); + + List descriptions = dmpEntity.getDescriptions().stream() + .filter(item -> item.getStatus() != DescriptionStatus.Canceled) + .filter(item -> !isPublic && !isFinalized || item.getStatus() == DescriptionStatus.Finalized) + .filter(item -> item.getSectionId().equals(sectionModel.getId())) + .sorted(Comparator.comparing(DescriptionModel::getCreatedAt)).toList(); + + if (!descriptions.isEmpty()) { + buildSectionDescriptions(document, descriptions); + } + } + + private void buildSectionDescriptions(XWPFDocument document, List descriptions) { + if (document == null) throw new IllegalArgumentException("Document required"); + if (descriptions == null) throw new IllegalArgumentException("Descriptions required"); + + List descriptionTemplateModels = descriptions.stream().map(DescriptionModel::getDescriptionTemplate).toList(); + if (descriptionTemplateModels.isEmpty()) return; + + this.wordBuilder.addParagraphContent("Section descriptions", document, ParagraphStyle.HEADER2, BigInteger.ZERO, 0); + this.wordBuilder.addParagraphContent("Description Templates", document, ParagraphStyle.HEADER4, BigInteger.ZERO, 0); + for (DescriptionTemplateModel descriptionTemplateModelEntity : descriptionTemplateModels) { + XWPFParagraph templateParagraph = document.createParagraph(); + XWPFRun runTemplateLabel = templateParagraph.createRun(); + runTemplateLabel.setText("• " + descriptionTemplateModelEntity.getLabel()); + runTemplateLabel.setColor("116a78"); + } + + for (DescriptionModel descriptionModel : descriptions){ + buildSectionDescription(document, descriptionModel); + } + } + + private void buildSectionDescription(XWPFDocument document, DescriptionModel descriptionModel) { + if (document == null) throw new IllegalArgumentException("Document required"); + if (descriptionModel == null) throw new IllegalArgumentException("DescriptionModel required"); + + DescriptionTemplateModel descriptionTemplateModelFileModel = descriptionModel.getDescriptionTemplate(); + + // Dataset Description custom style. + XWPFParagraph datasetDescriptionParagraph = document.createParagraph(); + datasetDescriptionParagraph.setStyle("Heading4"); + datasetDescriptionParagraph.setSpacingBetween(1.5); + XWPFRun datasetDescriptionRun = datasetDescriptionParagraph.createRun(); + datasetDescriptionRun.setText("Dataset Description"); + datasetDescriptionRun.setFontSize(15); + + + // Custom style for the Dataset title. + XWPFParagraph datasetLabelParagraph = document.createParagraph(); + datasetLabelParagraph.setSpacingBetween(1.0); + XWPFRun runDatasetTitle1 = datasetLabelParagraph.createRun(); + runDatasetTitle1.setText("Title: "); + runDatasetTitle1.setColor("000000"); + XWPFRun runDatasetTitle = datasetLabelParagraph.createRun(); + runDatasetTitle.setText(descriptionModel.getLabel()); + runDatasetTitle.setColor("116a78"); + + XWPFParagraph datasetTemplateParagraph = document.createParagraph(); + XWPFRun runDatasetTemplate1 = datasetTemplateParagraph.createRun(); + runDatasetTemplate1.setText("Template: "); + runDatasetTemplate1.setColor("000000"); + + XWPFRun runDatasetTemplate = datasetTemplateParagraph.createRun(); + runDatasetTemplate.setText(descriptionTemplateModelFileModel != null ? descriptionTemplateModelFileModel.getLabel() : ""); + runDatasetTemplate.setColor("116a78"); + + XWPFParagraph datasetDescParagraph = document.createParagraph(); + XWPFRun runDatasetDescription1 = datasetDescParagraph.createRun(); + runDatasetDescription1.setText("Description: "); + runDatasetDescription1.setColor("000000"); + XWPFRun runDatasetDescription = datasetDescParagraph.createRun(); + runDatasetDescription.setText(descriptionTemplateModelFileModel != null ? descriptionTemplateModelFileModel.getLabel() : ""); + runDatasetDescription.setColor("116a78"); + + document.createParagraph(); + + + try { + this.wordBuilder.build(document, descriptionModel.getDescriptionTemplate(), descriptionModel.getProperties()); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + // Page break at the end of the Dataset. + XWPFParagraph parBreakDataset = document.createParagraph(); + parBreakDataset.setPageBreak(true); + } + + + private void buildDmpSectionField(DmpModel dmpEntity, XWPFDocument document, FieldModel fieldModel) throws InvalidApplicationException { + if (fieldModel == null) throw new IllegalArgumentException("Field required"); + if (fieldModel.getCategory() == null) throw new IllegalArgumentException("Field is required" + fieldModel.getId() + " " + fieldModel.getLabel()); + switch (fieldModel.getCategory()){ + case System -> { + buildDmpSectionSystemField(dmpEntity, document, (SystemFieldModel) fieldModel); + } + case Extra -> buildDmpSectionExtraField(dmpEntity, document, (ExtraFieldModel) fieldModel); + case ReferenceType -> { + buildDmpSectionFieldTitleDescription(document, fieldModel); + buildDmpSectionReferenceTypeField(dmpEntity, document, (ReferenceTypeFieldModel) fieldModel); + } + default -> throw new InvalidApplicationException("Invalid type " + fieldModel.getCategory()); + } + } + + private void buildDmpSectionReferenceTypeField(DmpModel dmpEntity, XWPFDocument document, ReferenceTypeFieldModel referenceField) { + if (referenceField == null) throw new IllegalArgumentException("ReferenceField required"); + if (dmpEntity == null) throw new IllegalArgumentException("DmpEntity required"); + if (document == null) throw new IllegalArgumentException("Document required"); + if (referenceField.getReferenceType() == null) throw new IllegalArgumentException("ReferenceField type required"); + if (referenceField.getReferenceType().getCode() == null && !referenceField.getReferenceType().getCode().isBlank()) throw new IllegalArgumentException("ReferenceField type code required"); + + XWPFParagraph systemFieldInput = document.createParagraph(); + systemFieldInput.setSpacingBetween(1.0); + XWPFRun runInput = systemFieldInput.createRun(); + runInput.setText("Input: "); + runInput.setColor("000000"); + List referenceModels = this.getReferenceModelOfTypeCode(dmpEntity, referenceField.getReferenceType().getCode(), referenceField.getId()); + if (referenceModels != null) { + for (ReferenceModel reference : referenceModels) { + XWPFRun runResearcher = systemFieldInput.createRun(); + runResearcher.setText("• " + reference.getLabel()); + runResearcher.setColor("116a78"); + } + } + + document.createParagraph(); + } + + private void buildDmpSectionFieldTitleDescription(XWPFDocument document, FieldModel fieldModel){ + if (fieldModel == null) throw new IllegalArgumentException("FieldModel required"); + if (document == null) throw new IllegalArgumentException("Document required"); + XWPFParagraph systemFieldParagraph = document.createParagraph(); + systemFieldParagraph.setSpacingBetween(1.0); + XWPFRun runSyStemFieldTitle = systemFieldParagraph.createRun(); + runSyStemFieldTitle.setText("Title: "); + runSyStemFieldTitle.setColor("000000"); + XWPFRun runSystemFieldTitleText = systemFieldParagraph.createRun(); + runSystemFieldTitleText.setText(fieldModel.getLabel()); + runSystemFieldTitleText.setColor("116a78"); + if (fieldModel.getDescription() != null && !fieldModel.getDescription().isEmpty()) { + XWPFParagraph systemFieldDescription = document.createParagraph(); + systemFieldDescription.setSpacingBetween(1.0); + XWPFRun runSyStemFieldDescription = systemFieldDescription.createRun(); + runSyStemFieldDescription.setText("Description: "); + runSyStemFieldDescription.setColor("000000"); + XWPFRun runSystemFieldDescriptionText = systemFieldDescription.createRun(); + runSystemFieldDescriptionText.setText(fieldModel.getDescription()); + runSystemFieldDescriptionText.setColor("116a78"); + } + } + + private void buildDmpSectionSystemField(DmpModel dmpEntity, XWPFDocument document, SystemFieldModel systemField) throws InvalidApplicationException { + if (systemField == null) throw new IllegalArgumentException("SystemField required"); + if (dmpEntity == null) throw new IllegalArgumentException("DmpEntity required"); + if (document == null) throw new IllegalArgumentException("Document required"); + + XWPFParagraph systemFieldInput = document.createParagraph(); + systemFieldInput.setSpacingBetween(1.0); + XWPFRun runInput = systemFieldInput.createRun(); + runInput.setText("Input: "); + runInput.setColor("000000"); + switch (systemField.getSystemFieldType()) { + case Title: + XWPFRun runTitle = systemFieldInput.createRun(); + runTitle.setText(dmpEntity.getLabel()); + runTitle.setColor("116a78"); + break; + case Description: + XWPFRun runDescription = systemFieldInput.createRun(); + runDescription.setText(dmpEntity.getDescription()); + runDescription.setColor("116a78"); + break; + case AccessRights: + if (dmpEntity.getAccessType() != null) { + XWPFRun runAccessRights = systemFieldInput.createRun(); + runAccessRights.setText(dmpEntity.getAccessType().equals(DmpAccessType.Public) ? "Public" : "Restricted"); //TODO + //runAccessRights.setText(dmpProperties.get("visible").toString()); + runAccessRights.setColor("116a78"); + } + break; + case Contact: + if (dmpEntity.getCreator() != null) { + XWPFRun runContact = systemFieldInput.createRun(); + runContact.setText(dmpEntity.getCreator().getName()); + runContact.setColor("116a78"); + } + break; + case User: + case Language: + break; + default: + throw new InvalidApplicationException("Invalid type " + systemField.getSystemFieldType()); + } + document.createParagraph(); + } + + private void buildDmpSectionExtraField(DmpModel dmpEntity, XWPFDocument document, ExtraFieldModel extraFieldModel) { + if (extraFieldModel == null) throw new IllegalArgumentException("ExtraFieldModel required"); + XWPFParagraph extraFieldParagraph = document.createParagraph(); + extraFieldParagraph.setSpacingBetween(1.0); + XWPFRun runExtraFieldLabel = extraFieldParagraph.createRun(); + runExtraFieldLabel.setText(extraFieldModel.getLabel()); + runExtraFieldLabel.setColor("116a78"); + if (extraFieldModel.getDescription() != null && !extraFieldModel.getDescription().isEmpty()) { + XWPFRun runExtraFieldDescription = extraFieldParagraph.createRun(); + runExtraFieldDescription.setText(extraFieldModel.getDescription()); + runExtraFieldDescription.setColor("116a78"); + } + XWPFRun runExtraFieldInput = extraFieldParagraph.createRun(); + DmpBlueprintValueModel dmpBlueprintValueModel = dmpEntity.getProperties() != null && dmpEntity.getProperties().getDmpBlueprintValues() != null ? dmpEntity.getProperties().getDmpBlueprintValues().stream().filter(x -> extraFieldModel.getId().equals(x.getFieldId())).findFirst().orElse(null) : null; + if (dmpBlueprintValueModel != null && dmpBlueprintValueModel.getValue() != null) { + runExtraFieldInput.setText(dmpBlueprintValueModel.getValue()); + } + runExtraFieldInput.setColor("116a78"); + } + + private String getDmpFileName(DmpModel dmpModel, String extension){ + if (dmpModel == null) throw new IllegalArgumentException("DmpEntity required"); + + List grants = this.getReferenceModelOfTypeCode(dmpModel, this.wordFileTransformerServiceProperties.getGrantReferenceCode(), null); + String fileName; + if (!grants.isEmpty() && grants.getFirst().getLabel() != null) { + fileName = "DMP_" + grants.getFirst().getLabel(); + } + else { + fileName = "DMP_" + dmpModel.getLabel(); + } + fileName += "_" + dmpModel.getVersion(); + return fileName + extension; + } + + private byte[] buildDescriptionWordDocument(DescriptionModel descriptionModel) throws IOException { + if (descriptionModel == null) throw new IllegalArgumentException("DmpEntity required"); + DmpModel dmpEntity = descriptionModel.getDmp(); + if (dmpEntity == null) throw new IllegalArgumentException("Dmp is invalid"); + XWPFDocument document = new XWPFDocument(new FileInputStream(ResourceUtils.getFile(this.wordFileTransformerServiceProperties.getWordDescriptionTemplate()))); + + this.wordBuilder.fillFirstPage(dmpEntity, descriptionModel, document, true); + this.wordBuilder.fillFooter(dmpEntity, descriptionModel, document); + + int powered_pos = this.wordBuilder.findPosOfPoweredBy(document); + XWPFParagraph powered_par = null; + XWPFParagraph argos_img_par = null; + if(powered_pos != -1) { + powered_par = document.getParagraphArray(powered_pos); + argos_img_par = document.getParagraphArray(powered_pos + 1); + } + + this.wordBuilder.build(document, descriptionModel.getDescriptionTemplate(), descriptionModel.getProperties()); + + if(powered_pos != -1) { + document.getLastParagraph().setPageBreak(false); + document.createParagraph(); + document.setParagraph(powered_par, document.getParagraphs().size() - 1); + + document.createParagraph(); + document.setParagraph(argos_img_par, document.getParagraphs().size() - 1); + + document.removeBodyElement(powered_pos + 1); + document.removeBodyElement(powered_pos + 1); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + document.write(out); + byte[] bytes = out.toByteArray(); + out.close(); + + return bytes; + } + + private String getDescriptionFileName(DescriptionModel descriptionModel, String extension){ + if (descriptionModel == null) throw new IllegalArgumentException("DmpEntity required"); + String fileName = descriptionModel.getLabel().replaceAll("[^a-zA-Z0-9+ ]", ""); + + return fileName + extension; + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceConfiguration.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceConfiguration.java new file mode 100644 index 0000000..4ba86dd --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceConfiguration.java @@ -0,0 +1,9 @@ +package eu.eudat.file.transformer.service.wordfiletransformer; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableConfigurationProperties({WordFileTransformerServiceProperties.class}) +public class WordFileTransformerServiceConfiguration { +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceProperties.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceProperties.java new file mode 100644 index 0000000..e516554 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/WordFileTransformerServiceProperties.java @@ -0,0 +1,106 @@ +package eu.eudat.file.transformer.service.wordfiletransformer; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "word-file-transformer") +public class WordFileTransformerServiceProperties { + private String wordDmpTemplate; + private String pidTemplate; + private String wordDescriptionTemplate; + private String organizationReferenceCode; + private String grantReferenceCode; + private String funderReferenceCode; + private String researcherReferenceCode; + private String licenceReferenceCode; + private String projectReferenceCode; + private String datasetReferenceCode; + private String publicationReferenceCode; + + public String getOrganizationReferenceCode() { + return organizationReferenceCode; + } + + public void setOrganizationReferenceCode(String organizationReferenceCode) { + this.organizationReferenceCode = organizationReferenceCode; + } + + public String getGrantReferenceCode() { + return grantReferenceCode; + } + + public void setGrantReferenceCode(String grantReferenceCode) { + this.grantReferenceCode = grantReferenceCode; + } + + public String getFunderReferenceCode() { + return funderReferenceCode; + } + + public void setFunderReferenceCode(String funderReferenceCode) { + this.funderReferenceCode = funderReferenceCode; + } + + public String getResearcherReferenceCode() { + return researcherReferenceCode; + } + + public void setResearcherReferenceCode(String researcherReferenceCode) { + this.researcherReferenceCode = researcherReferenceCode; + } + + public String getLicenceReferenceCode() { + return licenceReferenceCode; + } + + public void setLicenceReferenceCode(String licenceReferenceCode) { + this.licenceReferenceCode = licenceReferenceCode; + } + + public String getProjectReferenceCode() { + return projectReferenceCode; + } + + public void setProjectReferenceCode(String projectReferenceCode) { + this.projectReferenceCode = projectReferenceCode; + } + + public String getDatasetReferenceCode() { + return datasetReferenceCode; + } + + public void setDatasetReferenceCode(String datasetReferenceCode) { + this.datasetReferenceCode = datasetReferenceCode; + } + + public String getPublicationReferenceCode() { + return publicationReferenceCode; + } + + public void setPublicationReferenceCode(String publicationReferenceCode) { + this.publicationReferenceCode = publicationReferenceCode; + } + + public String getWordDmpTemplate() { + return wordDmpTemplate; + } + + public void setWordDmpTemplate(String wordDmpTemplate) { + this.wordDmpTemplate = wordDmpTemplate; + } + + public String getPidTemplate() { + return pidTemplate; + } + + public void setPidTemplate(String pidTemplate) { + this.pidTemplate = pidTemplate; + } + + public String getWordDescriptionTemplate() { + return wordDescriptionTemplate; + } + + public void setWordDescriptionTemplate(String wordDescriptionTemplate) { + this.wordDescriptionTemplate = wordDescriptionTemplate; + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/word/HtmlToWorldBuilder.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/HtmlToWorldBuilder.java similarity index 99% rename from core/src/main/java/eu/eudat/file/transformer/utils/word/HtmlToWorldBuilder.java rename to core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/HtmlToWorldBuilder.java index d844d61..7dd49f2 100644 --- a/core/src/main/java/eu/eudat/file/transformer/utils/word/HtmlToWorldBuilder.java +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/HtmlToWorldBuilder.java @@ -1,4 +1,4 @@ -package eu.eudat.file.transformer.utils.word; +package eu.eudat.file.transformer.service.wordfiletransformer.word; import org.apache.poi.xwpf.usermodel.*; import org.apache.xmlbeans.XmlCursor; diff --git a/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilder.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilder.java new file mode 100644 index 0000000..6313804 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilder.java @@ -0,0 +1,24 @@ +package eu.eudat.file.transformer.service.wordfiletransformer.word; + +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.description.PropertyDefinitionModel; +import eu.eudat.commonmodels.models.descriptiotemplate.DescriptionTemplateModel; +import eu.eudat.commonmodels.models.dmp.DmpModel; +import eu.eudat.file.transformer.model.enums.ParagraphStyle; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; + +import java.io.IOException; +import java.math.BigInteger; + +public interface WordBuilder { + void build(XWPFDocument document, DescriptionTemplateModel descriptionTemplate, PropertyDefinitionModel propertyDefinitionModel) throws IOException; + + XWPFParagraph addParagraphContent(Object content, XWPFDocument mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent); + + int findPosOfPoweredBy(XWPFDocument document); + + void fillFirstPage(DmpModel dmpEntity, DescriptionModel descriptionModel, XWPFDocument document, boolean isDescription); + + void fillFooter(DmpModel dmpEntity, DescriptionModel descriptionModel, XWPFDocument document); +} diff --git a/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilderImpl.java b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilderImpl.java new file mode 100644 index 0000000..7207025 --- /dev/null +++ b/core/src/main/java/eu/eudat/file/transformer/service/wordfiletransformer/word/WordBuilderImpl.java @@ -0,0 +1,1027 @@ +package eu.eudat.file.transformer.service.wordfiletransformer.word; + +import eu.eudat.commonmodels.enums.FieldType; +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.description.PropertyDefinitionFieldSetItemModel; +import eu.eudat.commonmodels.models.description.PropertyDefinitionFieldSetModel; +import eu.eudat.commonmodels.models.description.PropertyDefinitionModel; +import eu.eudat.commonmodels.models.descriptiotemplate.*; +import eu.eudat.commonmodels.models.descriptiotemplate.fielddata.*; +import eu.eudat.commonmodels.models.dmp.DmpModel; +import eu.eudat.commonmodels.models.dmpreference.DmpReferenceModel; +import eu.eudat.commonmodels.models.reference.ReferenceFieldModel; +import eu.eudat.commonmodels.models.reference.ReferenceModel; +import eu.eudat.file.transformer.service.storage.FileStorageServiceProperties; +import eu.eudat.file.transformer.service.wordfiletransformer.WordFileTransformerServiceProperties; +import eu.eudat.file.transformer.model.PidLink; +import eu.eudat.file.transformer.model.interfaces.ApplierWithValue; +import eu.eudat.file.transformer.service.pid.PidService; +import eu.eudat.file.transformer.model.enums.ParagraphStyle; +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.util.Units; +import org.apache.poi.xwpf.usermodel.*; +import org.apache.xmlbeans.XmlCursor; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.select.NodeTraversor; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; +import javax.management.InvalidApplicationException; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.*; + +import static org.apache.poi.xwpf.usermodel.Document.*; + +@Component +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class WordBuilderImpl implements WordBuilder { + private static final Logger logger = LoggerFactory.getLogger(WordBuilderImpl.class); + private static final Map IMAGE_TYPE_MAP = Map.of( + "image/jpeg", PICTURE_TYPE_JPEG, + "image/png", PICTURE_TYPE_PNG, + "image/gif", PICTURE_TYPE_GIF, + "image/tiff", PICTURE_TYPE_TIFF, + "image/bmp", PICTURE_TYPE_BMP, + "image/wmf", PICTURE_TYPE_WMF + ); + private BigInteger numId; + private Integer indent; + private Integer imageCount; + private final CTAbstractNum cTAbstractNum; + private final FileStorageServiceProperties fileStorageServiceProperties; + private final WordFileTransformerServiceProperties wordFileTransformerServiceProperties; + private final PidService pidService; + private final Map> options = new HashMap<>(); + private final Map> optionsInTable = new HashMap<>(); + + public WordBuilderImpl(FileStorageServiceProperties fileStorageServiceProperties, WordFileTransformerServiceProperties wordFileTransformerServiceProperties, PidService pidService) { + this.fileStorageServiceProperties = fileStorageServiceProperties; + this.wordFileTransformerServiceProperties = wordFileTransformerServiceProperties; + this.pidService = pidService; + this.cTAbstractNum = CTAbstractNum.Factory.newInstance(); + this.cTAbstractNum.setAbstractNumId(BigInteger.valueOf(1)); + this.indent = 0; + this.imageCount = 0; + this.buildOptions(); + this.buildOptionsInTable(); + } + + private void buildOptionsInTable() { + this.optionsInTable.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText("" + item); + run.setFontSize(11); + return paragraph; + }); + this.optionsInTable.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { + Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convertInTable(mainDocumentPart, htmlDoc, 0); + return htmlToWorldBuilder.getParagraph(); + }); + this.optionsInTable.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + paragraph.setStyle("Title"); + paragraph.setAlignment(ParagraphAlignment.CENTER); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + run.setBold(true); + run.setFontSize(14); + return paragraph; + }); + this.optionsInTable.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.addParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText(((Map)item).get("name")); + run.setFontSize(11); + run.setItalic(true); + return paragraph; + }); + } + + private void buildOptions() { + this.options.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + if (item != null) + run.setText("" + item); + run.setFontSize(11); + return paragraph; + }); + this.options.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { + Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convert(mainDocumentPart, htmlDoc, this.indent); + return htmlToWorldBuilder.getParagraph(); + }); + this.options.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Title"); + paragraph.setAlignment(ParagraphAlignment.CENTER); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + run.setBold(true); + run.setFontSize(14); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER1, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading1"); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER2, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading2"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER3, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading3"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER4, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading4"); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER5, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading5"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.HEADER6, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setStyle("Heading6"); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + return paragraph; + }); + this.options.put(ParagraphStyle.FOOTER, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + run.setText((String)item); + return paragraph; + }); + this.options.put(ParagraphStyle.COMMENT, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + XWPFRun run = paragraph.createRun(); + run.setText("" + item); + run.setItalic(true); + return paragraph; + }); + this.options.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setPageBreak(true); + paragraph.setSpacingAfter(0); + paragraph.setAlignment(ParagraphAlignment.CENTER); //GK: Center the image if it is too small + XWPFRun run = paragraph.createRun(); + String imageId = ((Map)item).get("id"); + String fileName = ((Map)item).get("name"); + String fileType = ((Map)item).get("type"); + int format; + format = IMAGE_TYPE_MAP.getOrDefault(fileType, 0); + try { + FileInputStream image = new FileInputStream(fileStorageServiceProperties.getTemp() + imageId); + ImageInputStream iis = ImageIO.createImageInputStream(new File(fileStorageServiceProperties.getTemp() + imageId)); + Iterator readers = ImageIO.getImageReaders(iis); + if (readers.hasNext()) { + ImageReader reader = readers.next(); + reader.setInput(iis); + + int initialImageWidth = reader.getWidth(0); + int initialImageHeight = reader.getHeight(0); + + float ratio = initialImageHeight / (float)initialImageWidth; + + int marginLeftInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getLeft(); + int marginRightInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getRight(); + int pageWidthInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getW(); + int pageWidth = Math.round((pageWidthInDXA - marginLeftInDXA - marginRightInDXA) / (float)20); // /20 converts dxa to points + + int imageWidth = Math.round(initialImageWidth*(float)0.75); // *0.75 converts pixels to points + int width = Math.min(imageWidth, pageWidth); + + int marginTopInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getTop(); + int marginBottomInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getBottom(); + int pageHeightInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getH(); + int pageHeight = Math.round((pageHeightInDXA - marginTopInDXA - marginBottomInDXA) / (float)20); // /20 converts dxa to points + + int imageHeight = Math.round(initialImageHeight * ((float)0.75)); // *0.75 converts pixels to points + + int height = Math.round(width*ratio); + if(height > pageHeight) { + // height calculated with ratio is too large. Image may have Portrait (vertical) orientation. Recalculate image dimensions. + height = Math.min(imageHeight, pageHeight); + width = Math.round(height/ratio); + } + + run.addPicture(image, format, fileName, Units.toEMU(width), Units.toEMU(height)); + paragraph.setPageBreak(false); + imageCount++; + XWPFParagraph captionParagraph = mainDocumentPart.createParagraph(); + captionParagraph.setAlignment(ParagraphAlignment.CENTER); + captionParagraph.setSpacingBefore(0); + captionParagraph.setStyle("Caption"); + XWPFRun captionRun = captionParagraph.createRun(); + captionRun.setText("Image " + imageCount); + + } + } catch (IOException | InvalidFormatException e){ + logger.error(e.getMessage(), e); + } + return paragraph; + }); + } + + @Override + public void build(XWPFDocument document, DescriptionTemplateModel descriptionTemplate, PropertyDefinitionModel propertyDefinitionModel) { + createPages(descriptionTemplate.getDefinition().getPages(), propertyDefinitionModel, document); + } + + private void createPages(List datasetProfilePages, PropertyDefinitionModel propertyDefinitionModel, XWPFDocument mainDocumentPart) { + datasetProfilePages.stream().filter(item -> item.getSections() != null).forEach(item -> { + try { + createSections(item.getSections(), propertyDefinitionModel, mainDocumentPart, 0, false, item.getOrdinal() + 1, null); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + }); + } + + private void createSections(List sections, PropertyDefinitionModel propertyDefinitionModel, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, Integer page, String sectionString) { + if (createListing) this.addListing(indent, false, true); + boolean hasValue = false; + + for (SectionModel section: sections) { + int paragraphPos = -1; + String tempSectionString = sectionString != null ? sectionString + "." + (section.getOrdinal() + 1) : "" + (section.getOrdinal() + 1); + if (!createListing) { + XWPFParagraph paragraph = addParagraphContent(page + "." + tempSectionString + " " + section.getTitle(), mainDocumentPart, ParagraphStyle.HEADER5, numId, indent); + paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); + } + if (section.getSections() != null) { + createSections(section.getSections(), propertyDefinitionModel, mainDocumentPart, indent + 1, createListing, page, tempSectionString); + } + if (section.getFieldSets() != null) { + hasValue = createFieldSetFields(section.getFieldSets(), propertyDefinitionModel, mainDocumentPart, indent + 1, createListing, page, tempSectionString); + } + + if (!hasValue && paragraphPos > -1) { + mainDocumentPart.removeBodyElement(paragraphPos); + } + } + } + + private Boolean createFieldSetFields(List fieldSetModels, PropertyDefinitionModel propertyDefinitionModel, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, Integer page, String section) { + if (createListing) this.addListing(indent, true, true); + boolean hasValue = false; + boolean returnedValue = false; + + for (FieldSetModel fieldSetModel : fieldSetModels) { + PropertyDefinitionFieldSetModel propertyDefinitionFieldSetModel = propertyDefinitionModel.getFieldSets().getOrDefault(fieldSetModel.getId(), null); + List propertyDefinitionFieldSetItemModels = propertyDefinitionFieldSetModel != null && propertyDefinitionFieldSetModel.getItems() != null ? propertyDefinitionFieldSetModel.getItems() : new ArrayList<>(); + propertyDefinitionFieldSetItemModels = propertyDefinitionFieldSetItemModels.stream().sorted(Comparator.comparingInt(PropertyDefinitionFieldSetItemModel::getOrdinal)).toList(); + + char c = 'a'; + int multiplicityItems = 0; + boolean hasMultiplicityItems = false; + int paragraphPos = -1; + + if (fieldSetModel.getTitle() != null && !fieldSetModel.getTitle().isEmpty() && !createListing) { + XWPFParagraph paragraph = addParagraphContent(page + "." + section + "." + (fieldSetModel.getOrdinal() + 1) + " " + fieldSetModel.getTitle(), mainDocumentPart, ParagraphStyle.HEADER6, numId, indent); + paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); + } + + if (!propertyDefinitionFieldSetItemModels.isEmpty()) { + if (fieldSetModel.getMultiplicity() != null) { + if (fieldSetModel.getMultiplicity().getTableView()) { + XWPFTable tbl = mainDocumentPart.createTable(); + int numOfRows = 0; + + tbl.setTableAlignment(TableRowAlign.CENTER); + mainDocumentPart.createParagraph(); + createHeadersInTable(fieldSetModel.getFields(), tbl); + numOfRows = tbl.getRows().size(); + + for (PropertyDefinitionFieldSetItemModel propertyDefinitionFieldSetItemModel : propertyDefinitionFieldSetItemModels) { + XWPFTableRow row = tbl.createRow(); + hasValue = createFieldsInTable(fieldSetModel, propertyDefinitionFieldSetItemModel, row, indent, createListing, false, numOfRows); + numOfRows++; + if (hasValue) returnedValue = true; + } + } else { + for (PropertyDefinitionFieldSetItemModel propertyDefinitionFieldSetItemModel : propertyDefinitionFieldSetItemModels) { + int paragraphPosInner = -1; + if (!fieldSetModel.getMultiplicity().getTableView() && !createListing) { + XWPFParagraph paragraphInner = addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.TEXT, numId, indent); + c++; + paragraphPosInner = mainDocumentPart.getPosOfParagraph(paragraphInner); + hasMultiplicityItems = true; + multiplicityItems++; + } + hasValue = createFields(fieldSetModel, propertyDefinitionFieldSetItemModel, mainDocumentPart, indent, createListing, hasMultiplicityItems); + if (hasValue) { + returnedValue = true; + } else if (paragraphPosInner > -1) { + mainDocumentPart.removeBodyElement(paragraphPosInner); + c--; + multiplicityItems--; + } + } + } + if (multiplicityItems == 1) { + String text = mainDocumentPart.getLastParagraph().getRuns().getFirst().getText(0); + if (text.equals("a. ")) { + mainDocumentPart.getLastParagraph().removeRun(0); + } + } + } else { + hasValue = createFields(fieldSetModel, propertyDefinitionFieldSetItemModels.getFirst(), mainDocumentPart, indent, createListing, false); + } + if (hasValue && propertyDefinitionFieldSetItemModels.getFirst().getComment() != null && !propertyDefinitionFieldSetItemModels.getFirst().getComment().isEmpty() && !createListing) { + addParagraphContent("Comment:\n"+ propertyDefinitionFieldSetItemModels.getFirst().getComment(), mainDocumentPart, ParagraphStyle.HTML, numId, indent); + } + } + + if (!hasValue && paragraphPos > -1) { + mainDocumentPart.removeBodyElement(paragraphPos); + } + } + + return returnedValue; + } + + private void createHeadersInTable(List fields, XWPFTable table) { + boolean atLeastOneHeader = false; + List tempFields = fields.stream().sorted(Comparator.comparingInt(FieldModel::getOrdinal)).toList(); + int index = 0; + XWPFTableRow row = table.getRow(0); + for (FieldModel field: tempFields) { + if (field.getIncludeInExport()) { + XWPFTableCell cell; + if (index == 0) { + cell = row.getCell(0); + } else { + cell = row.createCell(); + } + cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); + String label = field.getData().getLabel(); + if (label != null && !label.isBlank()) { + XWPFParagraph paragraph = cell.getParagraphs().getFirst(); + paragraph.setIndentationFirstLine(50); + XWPFRun run = paragraph.createRun(); + run.setText(label); + run.setBold(true); + run.setFontSize(12); + paragraph.setAlignment(ParagraphAlignment.CENTER); + paragraph.setSpacingBefore(100); + + atLeastOneHeader = true; + } + } + index++; + } + + if(!atLeastOneHeader) { + table.removeRow(0); + } + } + + private Boolean createFieldsInTable(FieldSetModel fieldSetModel, PropertyDefinitionFieldSetItemModel propertyDefinitionFieldSetItemModel, XWPFTableRow mainDocumentPart, Integer indent, Boolean createListing, boolean hasMultiplicityItems, int numOfRows) { + int numOfCells = 0; + boolean hasValue = false; + List tempFields = fieldSetModel.getFields().stream().sorted(Comparator.comparingInt(FieldModel::getOrdinal)).toList(); + for (FieldModel field: tempFields) { + if (field.getIncludeInExport()) { + if (!createListing) { + try { + eu.eudat.commonmodels.models.description.FieldModel fieldValueModel = propertyDefinitionFieldSetItemModel.getFields().getOrDefault(field.getId(), null); + if(field.getData().getFieldType().equals(FieldType.UPLOAD)){ + boolean isImage = false; + for(UploadDataModel.UploadOptionModel type: ((UploadDataModel)field.getData()).getTypes()){ + String fileFormat = type.getValue(); + if(IMAGE_TYPE_MAP.containsKey(fileFormat)){ + isImage = true; + break; + } + } + if(isImage){ + if (fieldValueModel != null && fieldValueModel.getTextValue() != null && !fieldValueModel.getTextValue().isEmpty()) { + XWPFParagraph paragraph = addCellContent(fieldValueModel.getTextValue(), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0, numOfRows, numOfCells, 0); //TODO + if (paragraph != null) { + hasValue = true; + } + if(hasMultiplicityItems){ + hasMultiplicityItems = false; + } + } + } + } + else if (fieldValueModel != null) { + this.indent = indent; + String format = this.formatter(field, fieldValueModel); + Boolean hasMultiAutoComplete = false; + boolean isResearcher = false; + if (field.getData() instanceof LabelAndMultiplicityDataModel){ + hasMultiAutoComplete = ((LabelAndMultiplicityDataModel)field.getData()).getMultipleSelect(); + } + if (field.getData() instanceof SelectDataModel){ + hasMultiAutoComplete = ((SelectDataModel)field.getData()).getMultipleSelect(); + } + if (field.getData() instanceof ReferenceTypeDataModel){ + hasMultiAutoComplete = ((ReferenceTypeDataModel)field.getData()).getMultipleSelect(); + isResearcher = ((ReferenceTypeDataModel)field.getData()).getReferenceType().getCode().equals(this.wordFileTransformerServiceProperties.getResearcherReferenceCode()); + } + + if(format != null && !format.isEmpty()){ + boolean isMultiAutoComplete = hasMultiAutoComplete != null && hasMultiAutoComplete; + boolean arrayStringFormat = format.charAt(0) == '['; + if(arrayStringFormat || isMultiAutoComplete){ + List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); + if(values.size() > 1) { + boolean orcidResearcher; + int numOfValuesInCell = 0; + for (String val : values) { + orcidResearcher = false; + String orcId = null; + if(isResearcher && val.contains("orcid:")){ + orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); + val = val.substring(0, val.indexOf(':') + 1) + " "; + orcidResearcher = true; + } + format = "• " + val; + if(hasMultiplicityItems){ + XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); + paragraph.createRun().setText(format); + if(orcidResearcher){ + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + hasMultiplicityItems = false; + } + else{ + XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, field.getData().getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, numOfValuesInCell); + numOfValuesInCell++; + if(orcidResearcher){ + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + if (paragraph != null) { + hasValue = true; + } + } + format = null; + } + } + else if(values.size() == 1){ + format = values.getFirst(); + } + } + } + if(hasMultiplicityItems && format != null){ + XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); + paragraph.createRun().setText(format); + hasMultiplicityItems = false; + hasValue = true; + } + else{ + XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, field.getData().getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, 0); + if (paragraph != null) { + hasValue = true; + } + } + } + } catch (InvalidApplicationException e) { + logger.error(e.getMessage(), e); + } + } + numOfCells++; + } + } + return hasValue; + } + + private void createHypeLink(XWPFDocument mainDocumentPart, String format, String pidType, String pid, boolean hasMultiplicityItems, boolean isMultiAutoComplete){ + PidLink pidLink = pidService.getPid(pidType); + if (pidLink != null) { + if (!hasMultiplicityItems) { + XWPFParagraph paragraph = mainDocumentPart.createParagraph(); + paragraph.setIndentFromLeft(400 * indent); + if (numId != null) { + paragraph.setNumID(numId); + } + } + if (isMultiAutoComplete) { + XWPFRun r = mainDocumentPart.getLastParagraph().createRun(); + r.setText("• "); + } + XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun(pidLink.getLink().replace("{pid}", pid)); + run.setText(format); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + run.setFontSize(11); + } + else { + String newFormat = (isMultiAutoComplete) ? "• " + format : format; + if (hasMultiplicityItems) { + mainDocumentPart.getLastParagraph().createRun().setText(newFormat); + } + else { + addParagraphContent(newFormat, mainDocumentPart, ParagraphStyle.TEXT, numId, indent); + } + } + } + + private Boolean createFields(FieldSetModel fieldSetModel, PropertyDefinitionFieldSetItemModel propertyDefinitionFieldSetItemModel, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, boolean hasMultiplicityItems) { + if (createListing) this.addListing(indent, false, false); + boolean hasValue = false; + List tempFields = fieldSetModel.getFields().stream().sorted(Comparator.comparingInt(FieldModel::getOrdinal)).toList(); + for (FieldModel field: tempFields) { + if (field.getIncludeInExport()) { + if (!createListing) { + try { + eu.eudat.commonmodels.models.description.FieldModel fieldValueModel = propertyDefinitionFieldSetItemModel.getFields().getOrDefault(field.getId(), null); + if (field.getData() != null) { + if (field.getData().getFieldType().equals(FieldType.UPLOAD)) { + boolean isImage = false; + for (UploadDataModel.UploadOptionModel type : ((UploadDataModel) field.getData()).getTypes()) { + String fileFormat = type.getValue(); + if (IMAGE_TYPE_MAP.containsKey(fileFormat)) { + isImage = true; + break; + } + } + if (isImage) { + if (fieldValueModel.getTextValue() != null && !fieldValueModel.getTextValue().isEmpty()) { + XWPFParagraph paragraph = addParagraphContent(fieldValueModel.getTextValue(), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0); //TODO + if (paragraph != null) { + hasValue = true; + } + if (hasMultiplicityItems) { + hasMultiplicityItems = false; + } + } + } + } else if (fieldValueModel != null) { + this.indent = indent; + String format = this.formatter(field, fieldValueModel); + Boolean isMultiAutoComplete = false; + boolean isResearcher = false; + boolean isOrganization = false; + boolean isExternalDataset = false; + boolean isPublication = false; + if (field.getData() instanceof LabelAndMultiplicityDataModel) { + isMultiAutoComplete = ((LabelAndMultiplicityDataModel) field.getData()).getMultipleSelect(); + } + if (field.getData() instanceof SelectDataModel) { + isMultiAutoComplete = ((SelectDataModel) field.getData()).getMultipleSelect(); + } + if (field.getData() instanceof ReferenceTypeDataModel) { + isMultiAutoComplete = ((ReferenceTypeDataModel) field.getData()).getMultipleSelect(); + isResearcher = ((ReferenceTypeDataModel) field.getData()).getReferenceType().getCode().equals(this.wordFileTransformerServiceProperties.getResearcherReferenceCode()); + isOrganization = ((ReferenceTypeDataModel) field.getData()).getReferenceType().getCode().equals(this.wordFileTransformerServiceProperties.getOrganizationReferenceCode()); + isExternalDataset = ((ReferenceTypeDataModel) field.getData()).getReferenceType().getCode().equals(this.wordFileTransformerServiceProperties.getDatasetReferenceCode()); + isPublication = ((ReferenceTypeDataModel) field.getData()).getReferenceType().getCode().equals(this.wordFileTransformerServiceProperties.getPublicationReferenceCode()); + } + + if (isOrganization || isExternalDataset || isPublication) { + if(fieldValueModel.getReferences() != null){ + for (ReferenceModel referenceModel : fieldValueModel.getReferences()) + createHypeLink(mainDocumentPart, format, referenceModel.getDefinition().getFields().stream().filter(x-> x.getCode().equals("pidTypeField")).map(ReferenceFieldModel::getValue).findFirst().orElse(null), referenceModel.getReference(), hasMultiplicityItems, isMultiAutoComplete && fieldValueModel.getReferences().size() > 1); + if (hasMultiplicityItems) hasMultiplicityItems = false; + + hasValue = true; + } + + } else { + if (format != null && !format.isEmpty()) { + boolean arrayStringFormat = format.charAt(0) == '['; + if (arrayStringFormat || isMultiAutoComplete) { + List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); + if (values.size() > 1) { + boolean orcidResearcher; + for (String val : values) { + orcidResearcher = false; + String orcId = null; + if (isResearcher && val.contains("orcid:")) { + orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); + val = val.substring(0, val.indexOf(':') + 1) + " "; + orcidResearcher = true; + } + format = "• " + val; + if (hasMultiplicityItems) { + mainDocumentPart.getLastParagraph().createRun().setText(format); + if (orcidResearcher) { + XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + mainDocumentPart.getLastParagraph().createRun().setText(")"); + } + hasMultiplicityItems = false; + } else { + XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, field.getData().getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); + if (orcidResearcher) { + XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); + run.setText(orcId); + run.setUnderline(UnderlinePatterns.SINGLE); + run.setColor("0000FF"); + paragraph.createRun().setText(")"); + } + if (paragraph != null) { + hasValue = true; + } + } + format = null; + } + } else if (values.size() == 1) { + format = values.getFirst(); + } + } + } + if (format != null) { + if (hasMultiplicityItems) { + mainDocumentPart.getLastParagraph().createRun().setText(format); + hasMultiplicityItems = false; + hasValue = true; + } else { + XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, field.getData().getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); + if (paragraph != null) { + hasValue = true; + } + } + } + } + } + } + } catch (InvalidApplicationException e) { + throw new RuntimeException(e); + } + } + } + } + return hasValue; + } + + private XWPFParagraph addCellContent(Object content, XWPFTableRow mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent, int numOfRows, int numOfCells, int numOfValuesInCell) { + if (content != null) { + if (content instanceof String && ((String)content).isEmpty()) { + return null; + } + this.indent = indent; + XWPFTableCell cell; + if(numOfRows > 0 || numOfValuesInCell > 0) { + cell = mainDocumentPart.getCell(numOfCells); + } else { + cell = mainDocumentPart.createCell(); + } + cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); + if(numOfValuesInCell == 0) { + cell.removeParagraph(0); + } + + XWPFParagraph paragraph = this.optionsInTable.get(style).apply(cell, content); + if (paragraph != null) { + paragraph.setAlignment(ParagraphAlignment.CENTER); + paragraph.setSpacingBefore(100); + if (numId != null) { + paragraph.setNumID(numId); + } + return paragraph; + } + } + return null; + } + + @Override + public XWPFParagraph addParagraphContent(Object content, XWPFDocument mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent) { + if (content != null) { + if (content instanceof String && ((String)content).isEmpty()) { + return null; + } + this.indent = indent; + XWPFParagraph paragraph = this.options.get(style).apply(mainDocumentPart, content); + if (paragraph != null) { + paragraph.setIndentFromLeft(400*indent); + if (numId != null) { + paragraph.setNumID(numId); + } + return paragraph; + } + } + return null; + } + + private void addListing(int indent, boolean question, Boolean hasIndication) { + CTLvl cTLvl = this.cTAbstractNum.addNewLvl(); + + if (question) { + cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } else { + if (hasIndication) { + cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } else { + cTLvl.addNewNumFmt().setVal(STNumberFormat.NONE); + cTLvl.setIlvl(BigInteger.valueOf(indent)); + } + } + } + + private String formatter(FieldModel field, eu.eudat.commonmodels.models.description.FieldModel fieldValueModel) throws InvalidApplicationException { + if (fieldValueModel == null || field == null || field.getData() == null) { + return null; + } + switch (field.getData().getFieldType()) { + case REFERENCE_TYPES: { + List values = new ArrayList<>(); + if (fieldValueModel.getReferences() != null && !fieldValueModel.getReferences().isEmpty()) { + for (ReferenceModel referenceModel : fieldValueModel.getReferences()) { + if (referenceModel != null) { + if (referenceModel.getLabel() != null && !referenceModel.getLabel().isBlank()) { + values.add(referenceModel.getLabel()); + } + if (referenceModel.getDescription() != null && !referenceModel.getDescription().isBlank()) { + values.add(referenceModel.getLabel()); + } + } + } + } + + return String.join(", ", values); + } + case TAGS: + case CURRENCY: { + List values = new ArrayList<>(); + if (fieldValueModel.getTextListValue() != null && !fieldValueModel.getTextListValue().isEmpty()) { + values.addAll(fieldValueModel.getTextListValue()); + } + return String.join(", ", values); + } + case SELECT: { + List values = new ArrayList<>(); + if (fieldValueModel.getTextListValue() != null && !fieldValueModel.getTextListValue().isEmpty()) { + SelectDataModel selectDataModel = (SelectDataModel)field.getData(); + if (selectDataModel != null && selectDataModel.getOptions() != null && !selectDataModel.getOptions().isEmpty()){ + for (SelectDataModel.OptionModel option : selectDataModel.getOptions()){ + if (fieldValueModel.getTextListValue().contains(option.getValue()) || fieldValueModel.getTextListValue().contains(option.getLabel())) values.add(option.getLabel()); + } + } + } + return String.join(", ", values); + } + case BOOLEAN_DECISION: + if (fieldValueModel.getTextValue() != null && fieldValueModel.getTextValue().equals("true")) return "Yes"; + if (fieldValueModel.getTextValue() != null && fieldValueModel.getTextValue().equals("false")) return "No"; + return null; + case RADIO_BOX: + RadioBoxDataModel radioBoxDataModel = (RadioBoxDataModel) field.getData(); + if (fieldValueModel.getTextValue() != null && radioBoxDataModel != null && radioBoxDataModel.getOptions() != null) { + for (RadioBoxDataModel.RadioBoxOptionModel option : radioBoxDataModel.getOptions()){ + if (option.getValue().equals(fieldValueModel.getTextValue()) || option.getLabel().equals(fieldValueModel.getTextValue())) return option.getLabel(); + } + } + return null; + case CHECK_BOX: + LabelDataModel checkBoxData = (LabelDataModel) field.getData(); + if (fieldValueModel.getTextValue() != null || fieldValueModel.getTextValue().equals("false")) return null; + return checkBoxData != null ? checkBoxData.getLabel() : null; + case DATE_PICKER:{ + return fieldValueModel.getDateValue() != null ? DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(fieldValueModel.getDateValue()) : ""; + } + case FREE_TEXT: + case TEXT_AREA: + case RICH_TEXT_AREA: + return fieldValueModel.getTextValue() != null ? fieldValueModel.getTextValue() : ""; + case DATASET_IDENTIFIER: + case VALIDATION: + if (fieldValueModel.getExternalIdentifier() != null) { + return "id: " + fieldValueModel.getExternalIdentifier().getIdentifier() + ", Type: " + fieldValueModel.getExternalIdentifier().getType(); + } + return ""; + case UPLOAD: + case INTERNAL_ENTRIES_DESCRIPTIONS: + case INTERNAL_ENTRIES_DMPS: return null; + default: throw new InvalidApplicationException("Invalid type " + field.getData().getFieldType()); + } + } + + @Override + public int findPosOfPoweredBy(XWPFDocument document) { + if (document == null) throw new IllegalArgumentException("Document required"); + if (document.getParagraphs() == null) return -1; + + for (XWPFParagraph p : document.getParagraphs()) { + List runs = p.getRuns(); + if (runs != null) { + for (XWPFRun r : runs) { + String text = r.getText(0); + if (text != null) { + if (text.equals("Powered by")) { + return document.getPosOfParagraph(p) - 1; + } + } + } + } + } + return -1; + } + + private List getReferenceModelOfTypeCode(DmpModel dmp, String code){ + List response = new ArrayList<>(); + if (dmp.getReferences() == null) return response; + for (DmpReferenceModel dmpReferenceModel : dmp.getReferences()){ + if (dmpReferenceModel.getReference() != null && dmpReferenceModel.getReference().getType() != null && dmpReferenceModel.getReference().getType().getCode() != null && dmpReferenceModel.getReference().getType().getCode().equals(code)){ + response.add(dmpReferenceModel.getReference()); + } + } + return response; + } + + @Override + public void fillFirstPage(DmpModel dmpEntity, DescriptionModel descriptionModel, XWPFDocument document, boolean isDescription) { + if (dmpEntity == null) throw new IllegalArgumentException("DmpEntity required"); + if (document == null) throw new IllegalArgumentException("Document required"); + + int parPos = 0; + int descrParPos = -1; + XWPFParagraph descrPar = null; + List grants = this.getReferenceModelOfTypeCode(dmpEntity, this.wordFileTransformerServiceProperties.getGrantReferenceCode()); + List researchers = this.getReferenceModelOfTypeCode(dmpEntity, this.wordFileTransformerServiceProperties.getResearcherReferenceCode()); + List organizations = this.getReferenceModelOfTypeCode(dmpEntity, this.wordFileTransformerServiceProperties.getOrganizationReferenceCode()); + List funders = this.getReferenceModelOfTypeCode(dmpEntity, this.wordFileTransformerServiceProperties.getFunderReferenceCode()); + + for(XWPFParagraph p: document.getParagraphs()){ + List runs = p.getRuns(); + if(runs != null){ + for(XWPFRun r : runs){ + String text = r.getText(0); + if(text != null){ + if(text.contains("{ARGOS.DMP.TITLE}")) { + text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); + r.setText(text, 0); + } else if(text.contains("{ARGOS.DMP.VERSION}")) { + text = text.replace("{ARGOS.DMP.VERSION}", "Version " + dmpEntity.getVersion()); + r.setText(text, 0); + } else if(descriptionModel != null && text.contains("{ARGOS.DATASET.TITLE}")) { + text = text.replace("{ARGOS.DATASET.TITLE}", descriptionModel.getLabel()); + r.setText(text, 0); + } else if((text.contains("{ARGOS.DMP.DESCRIPTION}") && !isDescription) || (descriptionModel != null && text.contains("{ARGOS.DATASET.DESCRIPTION}") && isDescription)) { + descrParPos = parPos; + descrPar = p; + if(!isDescription) { + text = text.replace("{ARGOS.DMP.DESCRIPTION}", ""); + } else { + text = text.replace("{ARGOS.DATASET.DESCRIPTION}", ""); + } + r.setText(text, 0); + } else if(text.equals("{ARGOS.DMP.RESEARCHERS}")) { + StringBuilder researchersNames = new StringBuilder(); + int i = 0; + for(ReferenceModel researcher : researchers){ + i++; + researchersNames.append(researcher.getLabel()).append(i < researchers.size() ? ", " : ""); + } + text = text.replace("{ARGOS.DMP.RESEARCHERS}", researchersNames.toString()); + r.setText(text, 0); + r.setFontSize(17); + } else if(text.equals("{ARGOS.DMP.ORGANIZATIONS}")) { + StringBuilder organisationsNames = new StringBuilder(); + int i = 0; + for(ReferenceModel organisation : organizations){ + i++; + organisationsNames.append(organisation.getLabel()).append(i < organizations.size() ? ", " : ""); + } + text = text.replace("{ARGOS.DMP.ORGANIZATIONS}", organisationsNames.toString()); + r.setText(text, 0); + r.setFontSize(17); + } + } + } + } + parPos++; + } + + if((descrParPos != -1) && (dmpEntity.getDescription() != null) && !isDescription) { + XmlCursor cursor = descrPar.getCTP().newCursor(); + cursor.toNextSibling(); + Document htmlDoc = Jsoup.parse((dmpEntity.getDescription()).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); + } + if((descrParPos != -1) && (descriptionModel != null) && (descriptionModel.getDescription() != null) && isDescription) { + XmlCursor cursor = descrPar.getCTP().newCursor(); + cursor.toNextSibling(); + Document htmlDoc = Jsoup.parse(( descriptionModel.getDescription()).replaceAll("\n", "
")); + HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); + NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); + } + + + XWPFTable tbl = document.getTables().getFirst(); + Iterator it = tbl.getRows().iterator(); + it.next(); // skip first row + if(it.hasNext() && !funders.isEmpty()){ + XWPFParagraph p = it.next().getCell(0).getParagraphs().getFirst(); + XWPFRun run = p.createRun(); + run.setText(funders.getFirst().getLabel()); + run.setFontSize(17); + p.setAlignment(ParagraphAlignment.CENTER); + } + it = tbl.getRows().iterator(); + it.next(); + + if(it.hasNext() && !grants.isEmpty()){ + XWPFParagraph p = it.next().getCell(1).getParagraphs().getFirst(); + XWPFRun run = p.createRun(); + String text = grants.getFirst().getLabel(); + String reference = grants.getFirst().getReference(); + if(reference != null) { + String[] parts = reference.split("::"); + text += parts.length > 1 ? "/ No "+parts[parts.length - 1] : ""; + } + run.setText(text); + run.setFontSize(17); + p.setAlignment(ParagraphAlignment.CENTER); + } + } + + @Override + public void fillFooter(DmpModel dmpEntity, DescriptionModel descriptionModel, XWPFDocument document) { + if (dmpEntity == null) throw new IllegalArgumentException("DmpEntity required"); + + List licences = this.getReferenceModelOfTypeCode(dmpEntity, this.wordFileTransformerServiceProperties.getLicenceReferenceCode()); + document.getFooterList().forEach(xwpfFooter -> { + List runs = xwpfFooter.getParagraphs().getFirst().getRuns(); + if(runs != null){ + for(XWPFRun r : runs){ + String text = r.getText(0); + if(text != null){ + if(text.contains("{ARGOS.DMP.TITLE}")){ + text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DATASET.TITLE}") && descriptionModel != null){ + text = text.replace("{ARGOS.DATASET.TITLE}", descriptionModel.getLabel()); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.LICENSE}")){ + if (!licences.isEmpty()){ + text = text.replace("{ARGOS.DMP.LICENSE}", licences.getFirst().getReference()); + } + else { + text = text.replace("{ARGOS.DMP.LICENSE}", "License: -"); + } + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.DOI}")){ + if(dmpEntity.getEntityDois() != null && !dmpEntity.getEntityDois().isEmpty()) + text = text.replace("{ARGOS.DMP.DOI}", dmpEntity.getEntityDois().getFirst().getDoi()); + else + text = text.replace("{ARGOS.DMP.DOI}", "-"); + r.setText(text, 0); + } + if(text.contains("{ARGOS.DMP.LAST_MODIFIED}")){ + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withZone(ZoneId.systemDefault()); + text = text.replace("{ARGOS.DMP.LAST_MODIFIED}", formatter.format(dmpEntity.getUpdatedAt())); + r.setText(text, 0); + } + } + } + } + }); + } +} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/pdf/PDFUtils.java b/core/src/main/java/eu/eudat/file/transformer/utils/pdf/PDFUtils.java deleted file mode 100644 index ccefd6f..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/pdf/PDFUtils.java +++ /dev/null @@ -1,36 +0,0 @@ -package eu.eudat.file.transformer.utils.pdf; - -import eu.eudat.file.transformer.model.file.FileEnvelopeInternal; -import org.springframework.core.io.FileSystemResource; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.WebClient; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.util.UUID; - -public class PDFUtils { - - public static File convertToPDF(FileEnvelopeInternal file, String tempPath, String pdfUrl) throws IOException { - WebClient webClient = WebClient.builder().baseUrl(pdfUrl).build(); - - - byte[] queueResult = webClient.post().uri("forms/libreoffice/convert") - .headers(httpHeaders -> httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA)) - .body(BodyInserters.fromMultipartData("file", new FileSystemResource(file.getFile()))) - .retrieve().bodyToMono(byte[].class).block(); - - File resultPdf = new File(tempPath + "/" + UUID.randomUUID() + ".pdf"); - if (queueResult != null) { - try (FileOutputStream output = new FileOutputStream(resultPdf)) { - output.write(queueResult); - } - } - Files.deleteIfExists(file.getFile().toPath()); - - return resultPdf; - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/pid/PidLoader.java b/core/src/main/java/eu/eudat/file/transformer/utils/pid/PidLoader.java deleted file mode 100644 index b6f74f8..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/pid/PidLoader.java +++ /dev/null @@ -1,36 +0,0 @@ -package eu.eudat.file.transformer.utils.pid; - -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.file.transformer.model.PidLink; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.ResourceUtils; - -import java.io.IOException; -import java.util.List; - -public class PidLoader { - private static final Logger logger = LoggerFactory.getLogger(PidLoader.class); - private static final ObjectMapper objectMapper = new ObjectMapper(); - - public static List loadPidLinks(String pidPath) { - try { - return objectMapper.readValue(ResourceUtils.getFile(pidPath), PidLinksWrapper.class).getPidLinks(); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - return null; - } - - protected class PidLinksWrapper { - private List pidLinks; - - public List getPidLinks() { - return pidLinks; - } - - public void setPidLinks(List pidLinks) { - this.pidLinks = pidLinks; - } - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/types/ParagraphStyle.java b/core/src/main/java/eu/eudat/file/transformer/utils/types/ParagraphStyle.java deleted file mode 100644 index 6551ffe..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/types/ParagraphStyle.java +++ /dev/null @@ -1,49 +0,0 @@ -package eu.eudat.file.transformer.utils.types; - -/** - * Created by ikalyvas on 2/26/2018. - */ -public enum ParagraphStyle { - TEXT(0), HEADER1(1), HEADER2(2), HEADER3(3), HEADER4(4), TITLE(5), FOOTER(6), COMMENT(7), HEADER5(8), HEADER6(9), HTML(10), IMAGE(11); - - private Integer value; - - private ParagraphStyle(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - public static ParagraphStyle fromInteger(Integer value) { - switch (value) { - case 0: - return TEXT; - case 1: - return HEADER1; - case 2: - return HEADER2; - case 3: - return HEADER3; - case 4: - return HEADER4; - case 5: - return TITLE; - case 6: - return FOOTER; - case 7: - return COMMENT; - case 8: - return HEADER5; - case 9: - return HEADER6; - case 10: - return HTML; - case 11: - return IMAGE; - default: - throw new RuntimeException("Unsupported ParagraphStyle Code"); - } - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/types/TextStyle.java b/core/src/main/java/eu/eudat/file/transformer/utils/types/TextStyle.java deleted file mode 100644 index 6bc8400..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/types/TextStyle.java +++ /dev/null @@ -1,31 +0,0 @@ -package eu.eudat.file.transformer.utils.types; - -/** - * Created by ikalyvas on 2/27/2018. - */ -public enum TextStyle { - ITALIC(0), BOLD(1), CAPS(2); - - private Integer value; - - private TextStyle(Integer value) { - this.value = value; - } - - public Integer getValue() { - return value; - } - - public static TextStyle fromInteger(Integer value) { - switch (value) { - case 0: - return ITALIC; - case 1: - return BOLD; - case 2: - return CAPS; - default: - throw new RuntimeException("Unsupported TextStyle Code"); - } - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/word/WordBuilder.java b/core/src/main/java/eu/eudat/file/transformer/utils/word/WordBuilder.java deleted file mode 100644 index 1aa8d7d..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/word/WordBuilder.java +++ /dev/null @@ -1,1154 +0,0 @@ -package eu.eudat.file.transformer.utils.word; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import eu.eudat.file.transformer.configuration.FilePathProperties; -import eu.eudat.file.transformer.configuration.FileStorageProperties; -import eu.eudat.file.transformer.enums.FieldType; -import eu.eudat.file.transformer.enums.ReferenceType; -import eu.eudat.file.transformer.model.*; -import eu.eudat.file.transformer.models.descriptiontemplate.DescriptionTemplateFileTransformerModel; -import eu.eudat.file.transformer.models.description.DescriptionFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.definition.FieldFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.definition.FieldSetFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.definition.PageFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.definition.SectionFileTransformerModel; -import eu.eudat.file.transformer.models.descriptiontemplate.definition.fielddata.*; -import eu.eudat.file.transformer.models.dmp.DmpFileTransformerModel; -import eu.eudat.file.transformer.models.dmp.DmpReferenceFileTransformerModel; -import eu.eudat.file.transformer.models.reference.ReferenceFileTransformerModel; -import eu.eudat.file.transformer.utils.interfaces.ApplierWithValue; -import eu.eudat.file.transformer.utils.pid.PidLoader; -import eu.eudat.file.transformer.utils.types.ParagraphStyle; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlCursor; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.select.NodeTraversor; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTAbstractNum; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTLvl; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.STNumberFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.stream.ImageInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.*; -import java.util.stream.Collectors; - -import static org.apache.poi.xwpf.usermodel.Document.*; - -public class WordBuilder { - private static final Logger logger = LoggerFactory.getLogger(WordBuilder.class); - private static final Map IMAGE_TYPE_MAP = Map.of( - "image/jpeg", PICTURE_TYPE_JPEG, - "image/png", PICTURE_TYPE_PNG, - "image/gif", PICTURE_TYPE_GIF, - "image/tiff", PICTURE_TYPE_TIFF, - "image/bmp", PICTURE_TYPE_BMP, - "image/wmf", PICTURE_TYPE_WMF - ); - - private Map> options = new HashMap<>(); - private Map> optionsInTable = new HashMap<>(); - private CTAbstractNum cTAbstractNum; - private BigInteger numId; - private Integer indent; - private final ObjectMapper mapper; - private Integer imageCount; - private final FilePathProperties fileTemplateProperties; - private final FileStorageProperties fileStorageProperties; - - public WordBuilder(FilePathProperties fileTemplateProperties, FileStorageProperties fileStorageProperties) { - this.fileTemplateProperties = fileTemplateProperties; - this.fileStorageProperties = fileStorageProperties; - this.cTAbstractNum = CTAbstractNum.Factory.newInstance(); - this.cTAbstractNum.setAbstractNumId(BigInteger.valueOf(1)); - this.indent = 0; - this.imageCount = 0; - this.mapper = new ObjectMapper(); - this.buildOptions(); - this.buildOptionsInTable(); - } - - private void buildOptionsInTable() { - this.optionsInTable.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.addParagraph(); - XWPFRun run = paragraph.createRun(); - if (item != null) - run.setText("" + item); - run.setFontSize(11); - return paragraph; - }); - this.optionsInTable.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { - Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); - HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convertInTable(mainDocumentPart, htmlDoc, 0); - return htmlToWorldBuilder.getParagraph(); - }); - this.optionsInTable.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.addParagraph(); - paragraph.setStyle("Title"); - paragraph.setAlignment(ParagraphAlignment.CENTER); - XWPFRun run = paragraph.createRun(); - run.setText((String)item); - run.setBold(true); - run.setFontSize(14); - return paragraph; - }); - this.optionsInTable.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.addParagraph(); - XWPFRun run = paragraph.createRun(); - if (item != null) - run.setText(((Map)item).get("name")); - run.setFontSize(11); - run.setItalic(true); - return paragraph; - }); - } - - private void buildOptions() { - this.options.put(ParagraphStyle.TEXT, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - XWPFRun run = paragraph.createRun(); - if (item != null) - run.setText("" + item); - run.setFontSize(11); - return paragraph; - }); - this.options.put(ParagraphStyle.HTML, (mainDocumentPart, item) -> { - Document htmlDoc = Jsoup.parse(((String)item).replaceAll("\n", "
")); - HtmlToWorldBuilder htmlToWorldBuilder = HtmlToWorldBuilder.convert(mainDocumentPart, htmlDoc, this.indent); - return htmlToWorldBuilder.getParagraph(); - }); - this.options.put(ParagraphStyle.TITLE, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Title"); - paragraph.setAlignment(ParagraphAlignment.CENTER); - XWPFRun run = paragraph.createRun(); - run.setText((String)item); - run.setBold(true); - run.setFontSize(14); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER1, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading1"); - XWPFRun run = paragraph.createRun(); - run.setText((String)item); -// run.setBold(true); -// run.setFontSize(12); -// run.setStyle("0"); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER2, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading2"); - XWPFRun run = paragraph.createRun(); - run.setText("" + item); -// run.setBold(true); -// run.setFontSize(12); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER3, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading3"); - XWPFRun run = paragraph.createRun(); - run.setText("" + item); -// run.setBold(true); -// run.setFontSize(11); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER4, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading4"); - XWPFRun run = paragraph.createRun(); - run.setText((String)item); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER5, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading5"); - XWPFRun run = paragraph.createRun(); - run.setText("" + item); - return paragraph; - }); - this.options.put(ParagraphStyle.HEADER6, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setStyle("Heading6"); - XWPFRun run = paragraph.createRun(); - run.setText("" + item); - return paragraph; - }); - this.options.put(ParagraphStyle.FOOTER, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - XWPFRun run = paragraph.createRun(); - run.setText((String)item); - return paragraph; - }); - this.options.put(ParagraphStyle.COMMENT, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - XWPFRun run = paragraph.createRun(); - run.setText("" + item); - run.setItalic(true); - return paragraph; - }); - this.options.put(ParagraphStyle.IMAGE, (mainDocumentPart, item) -> { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setPageBreak(true); - paragraph.setSpacingAfter(0); - paragraph.setAlignment(ParagraphAlignment.CENTER); //GK: Center the image if it is too small - XWPFRun run = paragraph.createRun(); - String imageId = ((Map)item).get("id"); - String fileName = ((Map)item).get("name"); - String fileType = ((Map)item).get("type"); - int format; - format = IMAGE_TYPE_MAP.getOrDefault(fileType, 0); - try { - FileInputStream image = new FileInputStream(fileStorageProperties.getTemp() + imageId); - ImageInputStream iis = ImageIO.createImageInputStream(new File(fileStorageProperties.getTemp() + imageId)); - Iterator readers = ImageIO.getImageReaders(iis); - if (readers.hasNext()) { - ImageReader reader = readers.next(); - reader.setInput(iis); - - int initialImageWidth = reader.getWidth(0); - int initialImageHeight = reader.getHeight(0); - - float ratio = initialImageHeight / (float)initialImageWidth; - - int marginLeftInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getLeft(); - int marginRightInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getRight(); - int pageWidthInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getW(); - int pageWidth = Math.round((pageWidthInDXA - marginLeftInDXA - marginRightInDXA) / (float)20); // /20 converts dxa to points - - int imageWidth = Math.round(initialImageWidth*(float)0.75); // *0.75 converts pixels to points - int width = Math.min(imageWidth, pageWidth); - - int marginTopInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getTop(); - int marginBottomInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgMar().getBottom(); - int pageHeightInDXA = (int) mainDocumentPart.getDocument().getBody().getSectPr().getPgSz().getH(); - int pageHeight = Math.round((pageHeightInDXA - marginTopInDXA - marginBottomInDXA) / (float)20); // /20 converts dxa to points - - int imageHeight = Math.round(initialImageHeight * ((float)0.75)); // *0.75 converts pixels to points - - int height = Math.round(width*ratio); - if(height > pageHeight) { - // height calculated with ratio is too large. Image may have Portrait (vertical) orientation. Recalculate image dimensions. - height = Math.min(imageHeight, pageHeight); - width = Math.round(height/ratio); - } - - XWPFPicture picture = run.addPicture(image, format, fileName, Units.toEMU(width), Units.toEMU(height)); - paragraph.setPageBreak(false); - imageCount++; - XWPFParagraph captionParagraph = mainDocumentPart.createParagraph(); - captionParagraph.setAlignment(ParagraphAlignment.CENTER); - captionParagraph.setSpacingBefore(0); - captionParagraph.setStyle("Caption"); - XWPFRun captionRun = captionParagraph.createRun(); - captionRun.setText("Image " + imageCount); - - } - } catch (IOException | InvalidFormatException e){ - logger.error(e.getMessage(), e); - } - return paragraph; - }); - } - - public XWPFDocument build(XWPFDocument document, DescriptionTemplateFileTransformerModel descriptionTemplate) throws IOException { -// createPages(pagedDatasetProfile.getPages(), document, true, visibilityRuleService); -// XWPFNumbering numbering = document.createNumbering(); -// BigInteger tempNumId = BigInteger.ONE; -// boolean found = false; -// while (!found) { -// Object o = numbering.getAbstractNum(tempNumId); -// found = (o == null); -// if (!found) tempNumId = tempNumId.add(BigInteger.ONE); -// } -// cTAbstractNum.setAbstractNumId(tempNumId); -// XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum); -// BigInteger abstractNumID = numbering.addAbstractNum(abstractNum); -// this.numId = numbering.addNum(abstractNumID); - - createPages(descriptionTemplate.getDefinition().getPages(), document, false); - return document; - } - - private void createPages(List datasetProfilePages, XWPFDocument mainDocumentPart, Boolean createListing) { - datasetProfilePages.stream().filter(item -> item.getSections() != null).forEach(item -> { - try { - createSections(item.getSections(), mainDocumentPart, ParagraphStyle.HEADER5, 0, createListing, item.getOrdinal() + 1, null); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - }); - } - - private void createSections(List sections, XWPFDocument mainDocumentPart, ParagraphStyle style, Integer indent, Boolean createListing, Integer page, String sectionString) { - if (createListing) this.addListing(mainDocumentPart, indent, false, true); - boolean hasValue = false; - - for (SectionFileTransformerModel section: sections) { - int paragraphPos = -1; - String tempSectionString = sectionString != null ? sectionString + "." + (section.getOrdinal() + 1) : "" + (section.getOrdinal() + 1); - if (!createListing) { - XWPFParagraph paragraph = addParagraphContent(page + "." + tempSectionString + " " + section.getTitle(), mainDocumentPart, style, numId, indent); -// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -// number.setVal(BigInteger.valueOf(indent)); - paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); - } - if (section.getSections() != null) { - createSections(section.getSections(), mainDocumentPart, ParagraphStyle.HEADER5, indent + 1, createListing, page, tempSectionString); - } - if (section.getFieldSets() != null) { - hasValue = createCompositeFields(section.getFieldSets(), mainDocumentPart, indent + 1, createListing, page, tempSectionString); - } - - if (!hasValue && paragraphPos > -1) { - mainDocumentPart.removeBodyElement(paragraphPos); - } - } - } - - private Boolean createCompositeFields(List compositeFields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, Integer page, String section) { - if (createListing) this.addListing(mainDocumentPart, indent, true, true); - boolean hasValue = false; - boolean returnedValue = false; - - for (FieldSetFileTransformerModel compositeField: compositeFields) { - char c = 'a'; - int multiplicityItems = 0; - boolean hasMultiplicityItems = false; - int paragraphPos = -1; - int paragraphPosInner = -1; - if (compositeField.getTitle() != null && !compositeField.getTitle().isEmpty() && !createListing) { - XWPFParagraph paragraph = addParagraphContent(page + "." + section + "." + (compositeField.getOrdinal() +1) + " " + compositeField.getTitle(), mainDocumentPart, ParagraphStyle.HEADER6, numId, indent); -// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -// number.setVal(BigInteger.valueOf(indent)); - paragraphPos = mainDocumentPart.getPosOfParagraph(paragraph); - //TODO: dtziotzios implement multiplicity -// if(compositeField.getMultiplicity() != null && !compositeField.getMultiplicity().getTableView() && compositeField.getMultiplicityItems() != null && !compositeField.getMultiplicityItems().isEmpty()){ -// XWPFParagraph paragraphInner = addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.TEXT, numId, indent); -// paragraphPosInner = mainDocumentPart.getPosOfParagraph(paragraphInner); -// hasMultiplicityItems = true; -// multiplicityItems++; -// } - } - XWPFTable tbl = null; - XWPFTableRow row = null; - int numOfRows = 0; - if(compositeField.getMultiplicity() != null && compositeField.getMultiplicity().getTableView()) { - tbl = mainDocumentPart.createTable(); - tbl.setTableAlignment(TableRowAlign.CENTER); - mainDocumentPart.createParagraph(); - createHeadersInTable(compositeField.getFields(), tbl); - numOfRows = tbl.getRows().size(); - row = tbl.createRow(); - } - if(compositeField.getMultiplicity() != null && compositeField.getMultiplicity().getTableView()) { - hasValue = createFieldsInTable(compositeField.getFields(), row, indent, createListing, hasMultiplicityItems, numOfRows); - numOfRows++; - } else { - hasValue = createFields(compositeField.getFields(), mainDocumentPart, indent, createListing, hasMultiplicityItems); - } - if(hasValue){ - returnedValue = true; - } else if(paragraphPosInner > -1){ - mainDocumentPart.removeBodyElement(paragraphPosInner); - c--; - multiplicityItems--; - } - //TODO: Multiplicity Items??? - //TODO: dtziotzios implement multiplicity -// if (compositeField.getMultiplicityItems() != null && !compositeField.getMultiplicityItems().isEmpty()) { -// List list = compositeField.getMultiplicityItems().stream().sorted(Comparator.comparingInt(FieldSetFileTransformerModel::getOrdinal)).collect(Collectors.toList()); -// for (FieldSetFileTransformerModel multiplicityFieldset : list) { -// paragraphPosInner = -1; -// if(!compositeField.getMultiplicity().getTableView() && !createListing){ -// c++; -//// addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.HEADER6, numId); -// XWPFParagraph paragraphInner = addParagraphContent(c + ". ", mainDocumentPart, ParagraphStyle.TEXT, numId, indent); -// paragraphPosInner = mainDocumentPart.getPosOfParagraph(paragraphInner); -// hasMultiplicityItems = true; -// multiplicityItems++; -// } -//// hasValue = createFields(multiplicityFieldset.getFields(), mainDocumentPart, 3, createListing, visibilityRuleService, hasMultiplicityItems); -// boolean hasValueInner = false; -// if(compositeField.getMultiplicity().getTableView()) { -// row = tbl.createRow(); -// hasValueInner = createFieldsInTable(multiplicityFieldset.getFields(), row, indent, createListing, visibilityRuleService, hasMultiplicityItems, numOfRows); -// numOfRows++; -// } else { -// hasValueInner = createFields(multiplicityFieldset.getFields(), mainDocumentPart, indent, createListing, visibilityRuleService, hasMultiplicityItems); -// } -//// if(hasValue){ -// if(hasValueInner){ -// hasValue = true; -// returnedValue = true; -// } else if(paragraphPosInner > -1){ -// mainDocumentPart.removeBodyElement(paragraphPosInner); -// c--; -// multiplicityItems--; -// } -// } -// if(multiplicityItems == 1) { -// String text = mainDocumentPart.getLastParagraph().getRuns().get(0).getText(0); -// if(text.equals("a. ")) { -// mainDocumentPart.getLastParagraph().removeRun(0); -// } -// } -// } - //TODO: Dataset Profile -// if (hasValue && compositeField.getHasCommentField() && compositeField.getCommentFieldValue() != null && !compositeField.getCommentFieldValue().isEmpty() && !createListing) { -// XWPFParagraph paragraph = addParagraphContent("Comment:\n"+compositeField.getCommentFieldValue(), mainDocumentPart, ParagraphStyle.HTML, numId, indent); -//// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -//// number.setVal(BigInteger.valueOf(indent)); -// } - if (!hasValue && paragraphPos > -1) { - mainDocumentPart.removeBodyElement(paragraphPos); - } - } - - return returnedValue; - } - - private void createHeadersInTable(List fields, XWPFTable table) { - boolean atLeastOneHeader = false; - List tempFields = fields.stream().sorted(Comparator.comparingInt(FieldFileTransformerModel::getOrdinal)).collect(Collectors.toList()); - int index = 0; - XWPFTableRow row = table.getRow(0); - for (FieldFileTransformerModel field: tempFields) { - if (field.getIncludeInExport()) { - XWPFTableCell cell; - if (index == 0) { - cell = row.getCell(0); - } else { - cell = row.createCell(); - } - cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); - String label = field.getData().getLabel(); - if (label != null && label != "") { - XWPFParagraph paragraph = cell.getParagraphs().get(0); - paragraph.setIndentationFirstLine(50); - XWPFRun run = paragraph.createRun(); - run.setText(label); - run.setBold(true); - run.setFontSize(12); - paragraph.setAlignment(ParagraphAlignment.CENTER); - paragraph.setSpacingBefore(100); - - atLeastOneHeader = true; - } - } - index++; - } - - if(!atLeastOneHeader) { - table.removeRow(0); - } - } - - private Boolean createFieldsInTable(List fields, XWPFTableRow mainDocumentPart, Integer indent, Boolean createListing, boolean hasMultiplicityItems, int numOfRows) { - int numOfCells = 0; - boolean hasValue = false; - List tempFields = fields.stream().sorted(Comparator.comparingInt(FieldFileTransformerModel::getOrdinal)).collect(Collectors.toList()); - for (FieldFileTransformerModel field: tempFields) { - if (field.getIncludeInExport()) { - if (!createListing) { - try { - if(field.getData().getFieldType().equals(FieldType.UPLOAD)){ - boolean isImage = false; - for(UploadDataFileTransformerModel.UploadDataOptionFileTransformerModel type: ((UploadDataFileTransformerModel)field.getData()).getTypes()){ - String fileFormat = type.getValue(); - if(IMAGE_TYPE_MAP.containsKey(fileFormat)){ - isImage = true; - break; - } - } - if(isImage){ - if (field.getData().getValue() != null && !field.getData().getValue().toString().isEmpty()) { - XWPFParagraph paragraph = addCellContent(mapper.convertValue(field.getData().getValue(), Map.class), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0, numOfRows, numOfCells, 0); - if (paragraph != null) { - hasValue = true; - } - if(hasMultiplicityItems){ - hasMultiplicityItems = false; - } - } - } - } - else if (field.getData().getValue() != null && !field.getData().getValue().toString().isEmpty()) { - this.indent = indent; - String format = this.formatter(field); - if (((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.TAGS)) { - format = getCommaSeparatedFormatsFromJson(format, "name"); - } else if (((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.EXTERNAL_SELECT)) { - format = getCommaSeparatedFormatsFromJson(format, "label"); - } - boolean isResearcher = ((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.RESEARCHERS); - if(format != null && !format.isEmpty()){ - Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); - boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean)hasMultiAutoComplete; - boolean arrayStringFormat = format.charAt(0) == '['; - if(arrayStringFormat || isMultiAutoComplete){ - List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); - if(values.size() > 1) { - boolean orcidResearcher; - int numOfValuesInCell = 0; - for (String val : values) { - orcidResearcher = false; - String orcId = null; - if(isResearcher && val.contains("orcid:")){ - orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); - val = val.substring(0, val.indexOf(':') + 1) + " "; - orcidResearcher = true; - } - format = "• " + val; - if(hasMultiplicityItems){ - XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); - paragraph.createRun().setText(format); - if(orcidResearcher){ - XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); - run.setText(orcId); - run.setUnderline(UnderlinePatterns.SINGLE); - run.setColor("0000FF"); - paragraph.createRun().setText(")"); - } - hasMultiplicityItems = false; - } - else{ - XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, ((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, numOfValuesInCell); - numOfValuesInCell++; - if(orcidResearcher){ - XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); - run.setText(orcId); - run.setUnderline(UnderlinePatterns.SINGLE); - run.setColor("0000FF"); - paragraph.createRun().setText(")"); - } - if (paragraph != null) { - hasValue = true; - } - } - format = null; - } - } - else if(values.size() == 1){ - format = values.get(0); - } - } - } - if(hasMultiplicityItems && format != null){ - XWPFParagraph paragraph = mainDocumentPart.getCell(mainDocumentPart.getTableCells().size()).addParagraph(); - paragraph.createRun().setText(format); - hasMultiplicityItems = false; - hasValue = true; - } - else{ - XWPFParagraph paragraph = addCellContent(format, mainDocumentPart, ((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent, numOfRows, numOfCells, 0); - if (paragraph != null) { - hasValue = true; - } - } - } - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - } - numOfCells++; - } - } - return hasValue; - } - - private void createHypeLink(XWPFDocument mainDocumentPart, String format, String pidType, String pid, boolean hasMultiplicityItems, boolean isMultiAutoComplete){ - PidLink pidLink = PidLoader.loadPidLinks(this.fileTemplateProperties.getPidTemplate()).stream().filter(pl -> pl.getPid().equals(pidType)).findFirst().orElse(null); - if (pidLink != null) { - if (!hasMultiplicityItems) { - XWPFParagraph paragraph = mainDocumentPart.createParagraph(); - paragraph.setIndentFromLeft(400 * indent); - if (numId != null) { - paragraph.setNumID(numId); - } - } - if (isMultiAutoComplete) { - XWPFRun r = mainDocumentPart.getLastParagraph().createRun(); - r.setText("• "); - } - XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun(pidLink.getLink().replace("{pid}", pid)); - run.setText(format); - run.setUnderline(UnderlinePatterns.SINGLE); - run.setColor("0000FF"); - run.setFontSize(11); - } - else { - String newFormat = (isMultiAutoComplete) ? "• " + format : format; - if (hasMultiplicityItems) { - mainDocumentPart.getLastParagraph().createRun().setText(newFormat); - } - else { - addParagraphContent(newFormat, mainDocumentPart, ParagraphStyle.TEXT, numId, indent); - } - } - } - - private Boolean createFields(List fields, XWPFDocument mainDocumentPart, Integer indent, Boolean createListing, boolean hasMultiplicityItems) { - if (createListing) this.addListing(mainDocumentPart, indent, false, false); - boolean hasValue = false; - List tempFields = fields.stream().sorted(Comparator.comparingInt(FieldFileTransformerModel::getOrdinal)).collect(Collectors.toList()); - for (FieldFileTransformerModel field: tempFields) { - if (field.getIncludeInExport()) { - if (!createListing) { - try { - if (field.getData() != null) { - if (field.getData().getFieldType().equals(FieldType.UPLOAD)) { - boolean isImage = false; - for (UploadDataFileTransformerModel.UploadDataOptionFileTransformerModel type : ((UploadDataFileTransformerModel) field.getData()).getTypes()) { - String fileFormat = type.getValue(); - if (IMAGE_TYPE_MAP.containsKey(fileFormat)) { - isImage = true; - break; - } - } - if (isImage) { - if (field.getData().getValue() != null && !field.getData().getValue().isEmpty()) { - XWPFParagraph paragraph = addParagraphContent(mapper.convertValue(field.getData().getValue(), Map.class), mainDocumentPart, ParagraphStyle.IMAGE, numId, 0); - if (paragraph != null) { -// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -// number.setVal(BigInteger.valueOf(indent)); - hasValue = true; - } - if (hasMultiplicityItems) { - hasMultiplicityItems = false; - } - } - } - } else if (field.getData().getValue() != null && !field.getData().getValue().isEmpty()) { - this.indent = indent; - String format = this.formatter(field); - if (field.getData().getFieldType().equals(FieldType.TAGS)) { - format = getCommaSeparatedFormatsFromJson(format, "name"); - } else if (field.getData().getFieldType().equals(FieldType.EXTERNAL_SELECT)) { - format = getCommaSeparatedFormatsFromJson(format, "label"); - } - switch (((BaseFieldDataFileTransformerModel) field.getData()).getFieldType()) { - case ORGANIZATIONS: - case EXTERNAL_DATASETS: - case PUBLICATIONS: - if (format != null && !format.isEmpty()) { - Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); - boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean) hasMultiAutoComplete; - if (!isMultiAutoComplete) { - Map value = mapper.readValue(field.getData().getValue(), Map.class); - if (hasMultiplicityItems) { - createHypeLink(mainDocumentPart, format, value.get("pidTypeField"), value.get("pid"), true, false); - hasMultiplicityItems = false; - } else { - createHypeLink(mainDocumentPart, format, value.get("pidTypeField"), value.get("pid"), false, false); - } - } else { - mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - List> values = new ArrayList<>(); - try { - values = Arrays.asList(mapper.readValue(field.getData().getValue(), HashMap[].class)); - } catch (Exception e) { - Map map = new HashMap<>(); - map.put("label", field.getData().getValue()); - values.add(map); - } - if (values.size() > 1) { - for (Map value : values) { - if (hasMultiplicityItems) { - createHypeLink(mainDocumentPart, (String) value.get("name"), (String) value.get("pidTypeField"), (String) value.get("pid"), true, true); - hasMultiplicityItems = false; - } else { - createHypeLink(mainDocumentPart, (String) value.get("name"), (String) value.get("pidTypeField"), (String) value.get("pid"), false, true); - } - } - } else if (values.size() == 1) { - if (hasMultiplicityItems) { - createHypeLink(mainDocumentPart, format, (String) values.get(0).get("pidTypeField"), (String) values.get(0).get("pid"), true, false); - hasMultiplicityItems = false; - } else { - createHypeLink(mainDocumentPart, format, (String) values.get(0).get("pidTypeField"), (String) values.get(0).get("pid"), false, false); - } - } - } - hasValue = true; - } - break; - default: - boolean isResearcher = field.getData().getFieldType().equals(FieldType.RESEARCHERS); - if (format != null && !format.isEmpty()) { - Object hasMultiAutoComplete = mapper.convertValue(field.getData(), Map.class).get("multiAutoComplete"); - boolean isMultiAutoComplete = hasMultiAutoComplete != null && (boolean) hasMultiAutoComplete; - boolean arrayStringFormat = format.charAt(0) == '['; - if (arrayStringFormat || isMultiAutoComplete) { - List values = (arrayStringFormat) ? Arrays.asList(format.substring(1, format.length() - 1).split(",[ ]*")) : Arrays.asList(format.split(",[ ]*")); - if (values.size() > 1) { - boolean orcidResearcher; - for (String val : values) { - orcidResearcher = false; - String orcId = null; - if (isResearcher && val.contains("orcid:")) { - orcId = val.substring(val.indexOf(':') + 1, val.indexOf(')')); - val = val.substring(0, val.indexOf(':') + 1) + " "; - orcidResearcher = true; - } - format = "• " + val; - if (hasMultiplicityItems) { - mainDocumentPart.getLastParagraph().createRun().setText(format); - if (orcidResearcher) { - XWPFHyperlinkRun run = mainDocumentPart.getLastParagraph().createHyperlinkRun("https://orcid.org/" + orcId); - run.setText(orcId); - run.setUnderline(UnderlinePatterns.SINGLE); - run.setColor("0000FF"); - mainDocumentPart.getLastParagraph().createRun().setText(")"); - } - hasMultiplicityItems = false; - } else { - XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, ((BaseFieldDataFileTransformerModel) field.getData()).getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); - if (orcidResearcher) { - XWPFHyperlinkRun run = paragraph.createHyperlinkRun("https://orcid.org/" + orcId); - run.setText(orcId); - run.setUnderline(UnderlinePatterns.SINGLE); - run.setColor("0000FF"); - paragraph.createRun().setText(")"); - } - if (paragraph != null) { -// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -// number.setVal(BigInteger.valueOf(indent)); - hasValue = true; - } - } - format = null; - } - } else if (values.size() == 1) { - format = values.get(0); - } - } - } - if (format != null) { - if (hasMultiplicityItems) { - mainDocumentPart.getLastParagraph().createRun().setText(format); - hasMultiplicityItems = false; - hasValue = true; - } else { - XWPFParagraph paragraph = addParagraphContent(format, mainDocumentPart, field.getData().getFieldType().equals(FieldType.RICH_TEXT_AREA) ? ParagraphStyle.HTML : ParagraphStyle.TEXT, numId, indent); - if (paragraph != null) { -// CTDecimalNumber number = paragraph.getCTP().getPPr().getNumPr().addNewIlvl(); -// number.setVal(BigInteger.valueOf(indent)); - hasValue = true; - } - } - } - } - } - } - } catch (IOException e) { - logger.error(e.getMessage(), e); - } - } - } - } - return hasValue; - } - - private String getCommaSeparatedFormatsFromJson(String format, String attribute){ - if((format == null || format.isEmpty()) || (attribute == null || attribute.isEmpty())){ - return null; - } - try { - List> array = mapper.readValue(format, ArrayList.class); - StringBuilder multipleFormats = new StringBuilder(); - for (int i = 0; i < array.size(); i++) { - multipleFormats.append(array.get(i).get(attribute)).append(", "); - } - if (multipleFormats.length() > 0) { - multipleFormats.setLength(multipleFormats.length() - 2); - } - return multipleFormats.toString(); - } catch (JsonProcessingException e) { - return format; - } - } - - public XWPFParagraph addCellContent(Object content, XWPFTableRow mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent, int numOfRows, int numOfCells, int numOfValuesInCell) { - if (content != null) { - if (content instanceof String && ((String)content).isEmpty()) { - return null; - } - this.indent = indent; - XWPFTableCell cell; - if(numOfRows > 0 || numOfValuesInCell > 0) { - cell = mainDocumentPart.getCell(numOfCells); - } else { - cell = mainDocumentPart.createCell(); - } - cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf("CENTER")); - if(numOfValuesInCell == 0) { - cell.removeParagraph(0); - } - - XWPFParagraph paragraph = this.optionsInTable.get(style).apply(cell, content); - if (paragraph != null) { - paragraph.setAlignment(ParagraphAlignment.CENTER); - paragraph.setSpacingBefore(100); - if (numId != null) { - paragraph.setNumID(numId); - } - return paragraph; - } - } - return null; - } - - public XWPFParagraph addParagraphContent(Object content, XWPFDocument mainDocumentPart, ParagraphStyle style, BigInteger numId, int indent) { -// this.indent = 0; - if (content != null) { - if (content instanceof String && ((String)content).isEmpty()) { - return null; - } - this.indent = indent; - XWPFParagraph paragraph = this.options.get(style).apply(mainDocumentPart, content); - if (paragraph != null) { - paragraph.setIndentFromLeft(400*indent); - if (numId != null) { - paragraph.setNumID(numId); - } - return paragraph; - } - } - return null; - } - - private void addListing(XWPFDocument document, int indent, Boolean question, Boolean hasIndication) { - CTLvl cTLvl = this.cTAbstractNum.addNewLvl(); - - String textLevel = ""; - for (int i = 0; i <= indent; i++) { - textLevel += "%" + (i + 1) + "."; - } - - if (question) { - cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); -// cTLvl.addNewLvlText().setVal(""); - cTLvl.setIlvl(BigInteger.valueOf(indent)); - } else if (!question && hasIndication) { - cTLvl.addNewNumFmt().setVal(STNumberFormat.DECIMAL); -// cTLvl.addNewLvlText().setVal(""); - cTLvl.setIlvl(BigInteger.valueOf(indent)); - } - if (!question && !hasIndication) { - cTLvl.addNewNumFmt().setVal(STNumberFormat.NONE); -// cTLvl.addNewLvlText().setVal(""); - cTLvl.setIlvl(BigInteger.valueOf(indent)); - } - } - - private String formatter(FieldFileTransformerModel field) throws IOException { - if (field.getData().getValue() == null) { - return null; - } - switch (field.getData().getFieldType()) { - case RESEARCHERS: -// case "projects": //TODO: Description Templatedefinition - case ORGANIZATIONS: - case EXTERNAL_DATASETS: - case DATA_REPOSITORIES: - case PUB_REPOSITORIES: - case JOURNAL_REPOSITORIES: - case TAXONOMIES: - case LICENSES: - case PUBLICATIONS: - case REGISTRIES: - case SERVICES: - case TAGS: - case CURRENCY: - case EXTERNAL_SELECT: { - mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); - if (field.getData().getValue() == null) return null; - List> mapList = new ArrayList<>(); - if (!field.getData().getValue().equals("") && field.getData().getValue().toString() != null) { - try { - mapList = Arrays.asList(mapper.readValue(field.getData().getValue().toString(), HashMap[].class)); - } catch (Exception e) { - // logger.warn(e.getMessage(), e); - // logger.info("Moving to fallback parsing"); - Map map = new HashMap<>(); - map.put("label", field.getData().getValue().toString()); - mapList.add(map); - } - } - StringBuilder sb = new StringBuilder(); - int index = 0; - for (Map map : mapList) { - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() != null && (entry.getKey().equals("label") || entry.getKey().equals("description") || entry.getKey().equals("name"))) { - sb.append(entry.getValue()); - break; - } - } - if (index != mapList.size() - 1) sb.append(", "); - index++; - } - return sb.toString(); - } - case SELECT: { - SelectDataFileTransformerModel wordListDataEntity = (SelectDataFileTransformerModel) field.getData(); - if (field.getData().getValue() != null) { - SelectDataFileTransformerModel.OptionFileTransformerModel selectedOption = null; - if (!wordListDataEntity.getOptions().isEmpty()) { - for (SelectDataFileTransformerModel.OptionFileTransformerModel option : wordListDataEntity.getOptions()) { - if (option.getValue().equals(field.getData().getValue())) { - selectedOption = option; - } - } - } - return selectedOption != null ? selectedOption.getLabel() : field.getData().getValue().toString(); - } - return ""; - } - case BOOLEAN_DECISION: - if (field.getData().getValue() != null && field.getData().getValue().equals("true")) return "Yes"; - if (field.getData().getValue() != null && field.getData().getValue().equals("false")) return "No"; - return null; - case RADIO_BOX: - return field.getData().getValue() != null ? field.getData().getValue().toString() : null; - case CHECK_BOX: - LabelDataFileTransformerModel data = (LabelDataFileTransformerModel) field.getData(); - if (field.getData().getValue() == null || field.getData().getValue().equals("false")) return null; - return data.getLabel(); - case DATE_PICKER:{ - Instant instant; - if (!((String)field.getData().getValue()).isEmpty()) { - try { - instant = Instant.parse((String) field.getData().getValue()); - } catch (DateTimeParseException ex) { - instant = LocalDate.parse((String) field.getData().getValue()).atStartOfDay().toInstant(ZoneOffset.UTC); - } - return field.getData().getValue() != null ? DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant) : ""; - } - return (String) field.getData().getValue(); - } - case FREE_TEXT: - case TEXT_AREA: - case RICH_TEXT_AREA: - return field.getData().getValue() != null ? field.getData().getValue().toString(): ""; - case DATASET_IDENTIFIER: - case VALIDATION: - if (field.getData().getValue() != null && !field.getData().getValue().toString().isEmpty()) { - Map identifierData; - try { - identifierData = mapper.readValue(field.getData().getValue().toString(), HashMap.class); - } catch (Exception ex) { - // logger.warn(ex.getLocalizedMessage(), ex); - // logger.info("Reverting to custom parsing"); - identifierData = customParse(field.getData().getValue().toString()); - } - return "id: " + identifierData.get("identifier") + ", Type: " + identifierData.get("type"); - } - return ""; - } - return null; - } - - private Map customParse(String value) { - Map result = new LinkedHashMap<>(); - String parsedValue = value.replaceAll("[^a-zA-Z0-9\\s:=,]", ""); - StringTokenizer commaTokens = new StringTokenizer(parsedValue, ", "); - String delimeter = parsedValue.contains("=") ? "=" : ":"; - while (commaTokens.hasMoreTokens()) { - String token = commaTokens.nextToken(); - StringTokenizer delimiterTokens = new StringTokenizer(token, delimeter); - result.put(delimiterTokens.nextToken(), delimiterTokens.nextToken()); - } - return result; - } - - public int findPosOfPoweredBy(XWPFDocument document) { - for (XWPFParagraph p : document.getParagraphs()) { - List runs = p.getRuns(); - if (runs != null) { - for (XWPFRun r : runs) { - String text = r.getText(0); - if (text != null) { - if (text.equals("Powered by")) { - return document.getPosOfParagraph(p) - 1; - } - } - } - } - } - return -1; - } - - public void fillFirstPage(DmpFileTransformerModel dmpEntity, DescriptionFileTransformerModel descriptionFileTransformerModelEntityEntity, XWPFDocument document, boolean isDataset) { - int parPos = 0; - int descrParPos = -1; - XWPFParagraph descrPar = null; - List grants = new ArrayList<>(); - List researchers = new ArrayList<>(); - List organizations = new ArrayList<>(); - List funders = new ArrayList<>(); - if (dmpEntity.getDmpReferences() != null) { - grants = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Grants)).toList(); - researchers = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(reference -> reference.getType().equals(ReferenceType.Researcher)).toList(); - organizations = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Organizations)).toList(); - funders = dmpEntity.getDmpReferences().stream().map(DmpReferenceFileTransformerModel::getReference).filter(referenceFileModel -> referenceFileModel.getType().equals(ReferenceType.Funder)).toList(); - } - for(XWPFParagraph p: document.getParagraphs()){ - List runs = p.getRuns(); - if(runs != null){ - for(XWPFRun r : runs){ - String text = r.getText(0); - if(text != null){ - if(text.contains("{ARGOS.DMP.TITLE}")) { - text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); - r.setText(text, 0); - } else if(text.contains("{ARGOS.DMP.VERSION}")) { - text = text.replace("{ARGOS.DMP.VERSION}", "Version " + dmpEntity.getVersion()); - r.setText(text, 0); - } else if(descriptionFileTransformerModelEntityEntity != null && text.contains("{ARGOS.DATASET.TITLE}")) { - text = text.replace("{ARGOS.DATASET.TITLE}", descriptionFileTransformerModelEntityEntity.getLabel()); - r.setText(text, 0); -// } else if(text.equals("Description") && ((!isDataset && (dmpEntity == null || dmpEntity.getDescription() != null)) || (isDataset && (datasetEntity == null || datasetEntity.getDescription() == null)))) { -// r.setText("", 0); - } else if((dmpEntity != null && text.contains("{ARGOS.DMP.DESCRIPTION}") && !isDataset) || (descriptionFileTransformerModelEntityEntity != null && text.contains("{ARGOS.DATASET.DESCRIPTION}") && isDataset)) { - descrParPos = parPos; - descrPar = p; - if(dmpEntity != null && !isDataset) { - text = text.replace("{ARGOS.DMP.DESCRIPTION}", ""); - } else if(descriptionFileTransformerModelEntityEntity != null && isDataset) { - text = text.replace("{ARGOS.DATASET.DESCRIPTION}", ""); - } - r.setText(text, 0); - } else if(text.equals("{ARGOS.DMP.RESEARCHERS}")) { - String researchersNames = ""; - int i = 0; - for(ReferenceFileTransformerModel researcher : researchers){ - i++; - researchersNames += researcher.getLabel() + (i < researchers.size() ? ", " : ""); - } - text = text.replace("{ARGOS.DMP.RESEARCHERS}", researchersNames); - r.setText(text, 0); - r.setFontSize(17); - } else if(text.equals("{ARGOS.DMP.ORGANIZATIONS}")) { - String organisationsNames = ""; - int i = 0; - for(ReferenceFileTransformerModel organisation : organizations){ - i++; - organisationsNames += organisation.getLabel() + (i < organizations.size() ? ", " : ""); - } - text = text.replace("{ARGOS.DMP.ORGANIZATIONS}", organisationsNames); - r.setText(text, 0); - r.setFontSize(17); - } - } - } - } - parPos++; - } - - if((descrParPos != -1) && (dmpEntity!=null) && (dmpEntity.getDescription() != null) && !isDataset) { - XmlCursor cursor = descrPar.getCTP().newCursor(); - cursor.toNextSibling(); - Document htmlDoc = Jsoup.parse(((String)dmpEntity.getDescription()).replaceAll("\n", "
")); - HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); - NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); - } - if((descrParPos != -1) && (descriptionFileTransformerModelEntityEntity != null) && (descriptionFileTransformerModelEntityEntity.getDescription() != null) && isDataset) { - XmlCursor cursor = descrPar.getCTP().newCursor(); - cursor.toNextSibling(); - Document htmlDoc = Jsoup.parse(((String) descriptionFileTransformerModelEntityEntity.getDescription()).replaceAll("\n", "
")); - HtmlToWorldBuilder htmlToWorldBuilder = new HtmlToWorldBuilder(descrPar, 0, cursor); - NodeTraversor.traverse(htmlToWorldBuilder, htmlDoc); - } - - - XWPFTable tbl = document.getTables().get(0); - Iterator it = tbl.getRows().iterator(); - it.next(); // skip first row - if(it.hasNext() && !funders.isEmpty()){ - XWPFParagraph p = it.next().getCell(0).getParagraphs().get(0); - XWPFRun run = p.createRun(); - run.setText(funders.get(0).getLabel()); - run.setFontSize(17); - p.setAlignment(ParagraphAlignment.CENTER); - } - it = tbl.getRows().iterator(); - it.next(); - - if(it.hasNext() && !grants.isEmpty()){ - XWPFParagraph p = it.next().getCell(1).getParagraphs().get(0); - XWPFRun run = p.createRun(); - String text = grants.get(0).getLabel(); - String reference = grants.get(0).getReference(); - if(reference != null) { - String[] parts = reference.split("::"); - text += parts.length > 1 ? "/ No "+parts[parts.length - 1] : ""; - } - run.setText(text); - run.setFontSize(17); - p.setAlignment(ParagraphAlignment.CENTER); - } - } - - public void fillFooter(DmpFileTransformerModel dmpEntity, DescriptionFileTransformerModel descriptionFileTransformerModelEntityEntity, XWPFDocument document, boolean isDataset) { - document.getFooterList().forEach(xwpfFooter -> { - List runs = xwpfFooter.getParagraphs().get(0).getRuns(); - if(runs != null){ - for(XWPFRun r : runs){ - String text = r.getText(0); - if(text != null){ - if(text.contains("{ARGOS.DMP.TITLE}")){ - text = text.replace("{ARGOS.DMP.TITLE}", dmpEntity.getLabel()); - r.setText(text, 0); - } - if(text.contains("{ARGOS.DATASET.TITLE}") && descriptionFileTransformerModelEntityEntity != null){ - text = text.replace("{ARGOS.DATASET.TITLE}", descriptionFileTransformerModelEntityEntity.getLabel()); - r.setText(text, 0); - } - if(text.contains("{ARGOS.DMP.LICENSE}")){ - try{ - Map license = ((Map) mapper.readValue(dmpEntity.getProperties(), Map.class).get("license")); - text = text.replace("{ARGOS.DMP.LICENSE}", license.get("pid")); - } - catch (JsonProcessingException | NullPointerException e){ - text = text.replace("{ARGOS.DMP.LICENSE}", "License: -"); - } - r.setText(text, 0); - } - if(text.contains("{ARGOS.DMP.DOI}")){ - if(dmpEntity.getEntityDois() != null && !dmpEntity.getEntityDois().isEmpty()) - text = text.replace("{ARGOS.DMP.DOI}", dmpEntity.getEntityDois().iterator().next().getDoi()); - else - text = text.replace("{ARGOS.DMP.DOI}", "-"); - r.setText(text, 0); - } - if(text.contains("{ARGOS.DMP.LAST_MODIFIED}")){ - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withZone(ZoneId.systemDefault()); - text = text.replace("{ARGOS.DMP.LAST_MODIFIED}", formatter.format(dmpEntity.getUpdatedAt())); - r.setText(text, 0); - } - } - } - } - }); - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlDocument.java b/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlDocument.java deleted file mode 100644 index f1855e3..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlDocument.java +++ /dev/null @@ -1,63 +0,0 @@ -package eu.eudat.file.transformer.utils.word; - -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackagePart; -import org.apache.poi.openxml4j.opc.PackagePartName; -import org.apache.poi.openxml4j.opc.PackagingURIHelper; -import org.apache.poi.xwpf.usermodel.XWPFDocument; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.UUID; - -public class XWPFHtmlDocument extends POIXMLDocumentPart { - - private String html; - private String id; - - public XWPFHtmlDocument(PackagePart pkg, String id) { - super(pkg); - this.html = "HTML import

"; - this.id = id; - } - - public String getHtml() { - return html; - } - - public void setHtml(String html) { - this.html = this.html.replace("

", html); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - protected void commit() throws IOException { - PackagePart packagePart = getPackagePart(); - OutputStream outputStream = packagePart.getOutputStream(); - Writer writer = new OutputStreamWriter(outputStream, "UTF-8"); - writer.write(html); - writer.close(); - outputStream.close(); - } - - public static XWPFHtmlDocument addHtmlDocument(XWPFDocument document) throws InvalidFormatException { - OPCPackage oPCPackage = document.getPackage(); - String id = UUID.randomUUID().toString(); - PackagePartName partName = PackagingURIHelper.createPartName("/word/" + id + ".html"); - PackagePart part = oPCPackage.createPart(partName, "text/html"); - XWPFHtmlDocument xWPFHtmlDocument = new XWPFHtmlDocument(part, id); - document.addRelation(xWPFHtmlDocument.getId(), new XWPFHtmlRelation(), xWPFHtmlDocument); - return xWPFHtmlDocument; - } -} diff --git a/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlRelation.java b/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlRelation.java deleted file mode 100644 index 2f90057..0000000 --- a/core/src/main/java/eu/eudat/file/transformer/utils/word/XWPFHtmlRelation.java +++ /dev/null @@ -1,11 +0,0 @@ -package eu.eudat.file.transformer.utils.word; - -import org.apache.poi.ooxml.POIXMLRelation; - -public class XWPFHtmlRelation extends POIXMLRelation { - public XWPFHtmlRelation() { - super("text/html", - "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk", - "/word/htmlDoc#.html"); - } -} diff --git a/web/src/main/java/eu/eudat/file/transformer/controller/FileTransformerController.java b/web/src/main/java/eu/eudat/file/transformer/controller/FileTransformerController.java index 76b384b..6c391b9 100644 --- a/web/src/main/java/eu/eudat/file/transformer/controller/FileTransformerController.java +++ b/web/src/main/java/eu/eudat/file/transformer/controller/FileTransformerController.java @@ -1,18 +1,16 @@ package eu.eudat.file.transformer.controller; +import eu.eudat.commonmodels.models.FileEnvelopeModel; +import eu.eudat.commonmodels.models.description.DescriptionModel; +import eu.eudat.commonmodels.models.dmp.DmpModel; import eu.eudat.file.transformer.interfaces.FileTransformerClient; import eu.eudat.file.transformer.interfaces.FileTransformerConfiguration; -import eu.eudat.file.transformer.models.description.DescriptionFileTransformerModel; -import eu.eudat.file.transformer.models.dmp.DmpFileTransformerModel; -import eu.eudat.file.transformer.models.misc.FileEnvelope; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import java.util.List; - @RestController -@RequestMapping("/api/file") -public class FileTransformerController { +@RequestMapping("/api/file-transformer") +public class FileTransformerController implements eu.eudat.file.transformer.interfaces.FileTransformerController { private final FileTransformerClient fileTransformerExecutor; @@ -21,27 +19,22 @@ public class FileTransformerController { this.fileTransformerExecutor = fileTransformerExecutor; } - @PostMapping("/export/dmp") - public FileEnvelope exportDmp(@RequestBody DmpFileTransformerModel dmpDepositModel) throws Exception { - return fileTransformerExecutor.exportDmp(dmpDepositModel); + public FileEnvelopeModel exportDmp(@RequestBody DmpModel dmpDepositModel, @RequestParam(value = "format",required = false)String format) throws Exception { + return fileTransformerExecutor.exportDmp(dmpDepositModel, format); } - @PostMapping("/export/description") - public FileEnvelope exportDescription(@RequestBody DescriptionFileTransformerModel descriptionFileTransformerModel, @RequestParam(value = "format",required = false)String format, @RequestParam(value = "descriptionId",required = false) String descriptionId) throws Exception { - return fileTransformerExecutor.exportDescription(descriptionFileTransformerModel, format); + public FileEnvelopeModel exportDescription(@RequestBody DescriptionModel descriptionModel, @RequestParam(value = "format",required = false)String format) throws Exception { + return fileTransformerExecutor.exportDescription(descriptionModel, format); } - @PostMapping("/import/dmp") - public DmpFileTransformerModel importFileToDmp(@RequestBody FileEnvelope fileEnvelope) { + public DmpModel importFileToDmp(@RequestBody FileEnvelopeModel fileEnvelope) { return fileTransformerExecutor.importDmp(fileEnvelope); } - @PostMapping("/import/description") - public DescriptionFileTransformerModel importFileToDescription(@RequestBody FileEnvelope fileEnvelope) { + public DescriptionModel importFileToDescription(@RequestBody FileEnvelopeModel fileEnvelope) { return fileTransformerExecutor.importDescription(fileEnvelope); } - @GetMapping("/formats") public FileTransformerConfiguration getSupportedFormats() { return fileTransformerExecutor.getConfiguration(); } diff --git a/web/src/main/resources/config/application.yml b/web/src/main/resources/config/application.yml index 9bb90cb..d8d9331 100644 --- a/web/src/main/resources/config/application.yml +++ b/web/src/main/resources/config/application.yml @@ -7,5 +7,6 @@ spring: optional:classpath:config/storage.yml[.yml], optional:classpath:config/storage-${spring.profiles.active}.yml[.yml], optional:file:../config/storage-${spring.profiles.active}.yml[.yml], optional:classpath:config/security.yml[.yml], optional:classpath:config/security-${spring.profiles.active}.yml[.yml], optional:file:../config/security-${spring.profiles.active}.yml[.yml], optional:classpath:config/cache.yml[.yml], optional:classpath:config/cache-${spring.profiles.active}.yml[.yml], optional:file:../config/cache-${spring.profiles.active}.yml[.yml], + optional:classpath:config/word-file-transormer.yml[.yml], optional:classpath:config/word-file-transormer-${spring.profiles.active}.yml[.yml], optional:file:../config/word-file-transormer-${spring.profiles.active}.yml[.yml], optional:classpath:config/pdf.yml[.yml], optional:classpath:config/pdf-${spring.profiles.active}.yml[.yml], optional:file:../config/pdf-${spring.profiles.active}.yml[.yml] diff --git a/web/src/main/resources/config/security.yml b/web/src/main/resources/config/security.yml index ad38bd8..4613371 100644 --- a/web/src/main/resources/config/security.yml +++ b/web/src/main/resources/config/security.yml @@ -5,16 +5,11 @@ web: allowed-endpoints: [ health ] idp: api-key: - enabled: true - authorization-header: Authorization - client-id: ${IDP_APIKEY_CLIENT_ID:} - client-secret: ${IDP_APIKEY_CLIENT_SECRET:} - scope: ${IDP_APIKEY_SCOPE:} + enabled: false resource: token-type: JWT #| opaque - opaque: - client-id: ${IDP_OPAQUE_CLIENT_ID:} - client-secret: ${IDP_OPAQUE_CLIENT_SECRET:} jwt: claims: [ role, x-role ] - issuer-uri: ${IDP_ISSUER_URI:} \ No newline at end of file + issuer-uri: ${IDP_ISSUER_URI:} + audiences: [ "dmp_zenodo_bridge" ] + validIssuer: ${IDP_ISSUER_URI:} \ No newline at end of file diff --git a/web/src/main/resources/config/storage.yml b/web/src/main/resources/config/storage.yml index 18b1f18..283aecd 100644 --- a/web/src/main/resources/config/storage.yml +++ b/web/src/main/resources/config/storage.yml @@ -1,8 +1,4 @@ file: - template: - word-template: classpath:documents/h2020.docx - pid-template: classpath:pidLinks.json - word-description-template: classpath:documents/h2020_dataset.docx storage: - temp: ${TEMP_PATH} - transient-path: ${TRANSIENT_PATH} \ No newline at end of file + temp: ${STORAGE_PATH}/tmp + transient-path: ${STORAGE_PATH}/shared \ No newline at end of file diff --git a/web/src/main/resources/config/word-file-transormer.yml b/web/src/main/resources/config/word-file-transormer.yml new file mode 100644 index 0000000..2d72e3e --- /dev/null +++ b/web/src/main/resources/config/word-file-transormer.yml @@ -0,0 +1,12 @@ +word-file-transformer: + word-dmp-template: classpath:documents/h2020.docx + pid-template: classpath:pidLinks.json + word-description-template: classpath:documents/h2020_dataset.docx + organizationReferenceCode: "organisations" + grantReferenceCode: "grants" + funderReferenceCode: "funders" + researcherReferenceCode: "researchers" + licenceReferenceCode: "licenses" + projectReferenceCode: "projects" + datasetReferenceCode: "datasets" + publicationReferenceCode: "publications"