Search in sources :

Example 1 with XDocReportException

use of fr.opensagres.xdocreport.core.XDocReportException in project esup-ecandidat by EsupPortail.

the class CandidatureController method downloadDossier.

/**
 * telecharge le dossier
 * @param  candidature
 * @param  listePresentation
 * @param  listeDatePresentation
 * @param  listePj
 * @param  listeForm
 * @param  addPj
 * @return                       l'InputStream du dossier
 */
public OnDemandFile downloadDossier(final Candidature candidature, final List<SimpleTablePresentation> listePresentation, final List<SimpleTablePresentation> listeDatePresentation, final List<PjPresentation> listePj, final List<FormulairePresentation> listeForm, final Boolean addPj) {
    /* Variables utiles */
    final String numDossier = candidature.getCandidat().getCompteMinima().getNumDossierOpiCptMin();
    final String nom = candidature.getCandidat().getNomPatCandidat();
    final String prenom = candidature.getCandidat().getPrenomCandidat();
    final String codForm = candidature.getFormation().getCodForm();
    final String libForm = candidature.getFormation().getLibForm();
    /* Nom du fichier */
    final String fileName = applicationContext.getMessage("candidature.download.file", new Object[] { numDossier, nom, prenom, codForm }, UI.getCurrent().getLocale());
    // Les parametres des PJ
    final Boolean enableAddApogeePJDossier = parametreController.getIsAddApogeePJDossier();
    // Font
    final PDFont font = PDType1Font.HELVETICA_BOLD;
    // le dossier outStream
    ByteArrayInputStream bisDossier = null;
    // liste des InputStream à fermer
    final List<InputStream> listeInputStreamToClose = new ArrayList<>();
    /* Génération du dossier principal */
    try {
        bisDossier = generateDossier(candidature, listePresentation, listeDatePresentation, listePj, listeForm);
        if (bisDossier == null) {
            Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
            return null;
        }
    } catch (IOException | XDocReportException e2) {
        Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
        logger.error("erreur a la génération du dossier", e2);
        return null;
    }
    ByteArrayInOutStream out = new ByteArrayInOutStream();
    InputStream is = null;
    try {
        /* Merger */
        final PDFMergerUtility ut = new PDFMergerUtility();
        /* Propriétés du document */
        final PDDocumentInformation info = new PDDocumentInformation();
        info.setTitle(numDossier + "_" + nom + "_" + prenom + "_" + codForm);
        info.setAuthor(ConstanteUtils.APP_NAME);
        info.setSubject(nom + " " + prenom + " (" + numDossier + ") / " + libForm + " (" + codForm + ")");
        final Calendar calendar = Calendar.getInstance(UI.getCurrent().getLocale());
        info.setCreationDate(calendar);
        info.setModificationDate(calendar);
        ut.setDestinationDocumentInformation(info);
        /* Ajout du dossier */
        ut.addSource(bisDossier);
        /* Gestion des erreurs de pj */
        Boolean errorAddPj = false;
        final List<String> fileNameError = new ArrayList<>();
        /* Calcul si besoin d'ajouter les pj */
        Integer nbFilePJ = 0;
        for (final PjPresentation pj : listePj) {
            if (pj.getFilePj() != null) {
                nbFilePJ++;
            }
        }
        if (addPj && nbFilePJ > 0 && !fileController.isFileServiceMaintenance(applicationContext.getMessage("file.service.maintenance.dossier", null, UI.getCurrent().getLocale()))) {
            for (final PjPresentation e : listePj) {
                // listePj.forEach(e->{
                try {
                    // titre header
                    final String textHeader = e.getLibPj();
                    // PJ doit etre à true
                    if (e.getFilePj() != null && (e.getPjCandidatFromApogee() == null || (e.getPjCandidatFromApogee() != null && enableAddApogeePJDossier))) {
                        final Fichier file = e.getFilePj();
                        final String nameFile = file.getNomFichier();
                        final InputStream inputStreamFile = fileController.getInputStreamFromPjPresentation(e);
                        // on doit fermer l'inputStream apres le merge donc je stock le stream et le ferme apres
                        listeInputStreamToClose.add(inputStreamFile);
                        // cas du PDF
                        if (inputStreamFile != null && MethodUtils.isPdfFileName(nameFile)) {
                            // chargement du pdf avant de l'ajouter -> evite de compiler avec des fichiers corrompus
                            final BufferedInputStream bufferedInputStreamFile = new BufferedInputStream(inputStreamFile);
                            // on doit fermer l'inputStream apres le merge donc je stock le stream et le ferme apres
                            listeInputStreamToClose.add(bufferedInputStreamFile);
                            try {
                                // on place un marker au max du buffer du stream (mark = nb byte qu'il peut lire avant d'etre invalide.. mais comme on lit tout le fichier..)
                                bufferedInputStreamFile.mark(ConstanteUtils.MAX_BUFFER_SIZE);
                                // lecture du fichier pour vérifier s'il n'est pas corrompue
                                final PDDocument doc = PDDocument.load(bufferedInputStreamFile);
                                // cloture immédiate du fichier pour libérer la mémoire
                                MethodUtils.closeRessource(doc);
                                // on replace le bufferedInputStreamFile au début
                                bufferedInputStreamFile.reset();
                                // on ajoute l'inputStream
                                ut.addSource(bufferedInputStreamFile);
                            } catch (final Exception ex1) {
                                logger.warn("fichier pdf '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", ex1);
                                errorAddPj = true;
                                fileNameError.add(nameFile);
                            }
                        } else if (inputStreamFile != null && MethodUtils.isImgFileName(nameFile)) {
                            // creation document
                            final PDDocument document = new PDDocument();
                            final ByteArrayInOutStream baosImg = new ByteArrayInOutStream();
                            ByteArrayInputStream bis = null;
                            try {
                                // chargement page A4
                                final PDRectangle PAGE_SIZE_A4 = PDRectangle.A4;
                                // creation page
                                final PDPage page = new PDPage(PAGE_SIZE_A4);
                                // ajout de la page
                                document.addPage(page);
                                // Stream du document
                                final PDPageContentStream contentStream = new PDPageContentStream(document, page);
                                // margin top est calculée si un text de titre a été ajouté
                                Float marginTop = addHeaderPJ(textHeader, font, PAGE_SIZE_A4, contentStream);
                                // on ajoute la marge sous le text (ou la marge depuis le haut du doc si pas de
                                // text)
                                marginTop = marginTop + ConstanteUtils.DOSSIER_MARGIN;
                                // creation de l'image
                                PDImageXObject img = null;
                                // JPG
                                if (MethodUtils.isJpgFileName(nameFile)) {
                                    img = JPEGFactory.createFromStream(document, inputStreamFile);
                                } else // PNG
                                if (MethodUtils.isPngFileName(nameFile)) {
                                    img = LosslessFactory.createFromImage(document, ImageIO.read(inputStreamFile));
                                }
                                // calcul de la largeur et hauteur de l'image
                                Float imgWidth = (float) img.getWidth();
                                Float imgHeight = (float) img.getHeight();
                                // calcul de la largeur et hauteur de la page moins les deux marges
                                final Float a4Width = PAGE_SIZE_A4.getWidth() - 2 * ConstanteUtils.DOSSIER_MARGIN;
                                final Float a4Height = PAGE_SIZE_A4.getHeight() - ConstanteUtils.DOSSIER_MARGIN - marginTop;
                                // calcul du coef à appliquer si l'image est trop grande
                                Float coef = 1.0f;
                                if (imgWidth > a4Width) {
                                    coef = a4Width / imgWidth;
                                    imgWidth = imgWidth * coef;
                                    imgHeight = imgHeight * coef;
                                }
                                // le nouveau coef
                                if (imgHeight > a4Height) {
                                    coef = a4Height / imgHeight;
                                    imgWidth = imgWidth * coef;
                                    imgHeight = imgHeight * coef;
                                }
                                // ecriture de l'image
                                contentStream.drawImage(img, ConstanteUtils.DOSSIER_MARGIN, PAGE_SIZE_A4.getHeight() - imgHeight - marginTop, imgWidth, imgHeight);
                                // il faut d'abord fermer le flux
                                MethodUtils.closeRessource(contentStream);
                                document.save(baosImg);
                                /* Creation du flux */
                                bis = baosImg.getInputStream();
                                /* Ajout de la page au document */
                                ut.addSource(bis);
                            } catch (final Exception e1) {
                                errorAddPj = true;
                                fileNameError.add(nameFile);
                                logger.warn("fichier image '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", e1);
                            } finally {
                                /* Nettoyage des ressources */
                                MethodUtils.closeRessource(document);
                                MethodUtils.closeRessource(bis);
                                MethodUtils.closeRessource(baosImg);
                            }
                        }
                    }
                } catch (final Exception e1) {
                    errorAddPj = true;
                    final String nameFile = e.getFilePj() != null ? e.getFilePj().getNomFichier() : "-";
                    if (e.getFilePj() != null) {
                        fileNameError.add(e.getFilePj().getNomFichier());
                    }
                    logger.warn("fichier '" + nameFile + "' en erreur et non ajouté au dossier '" + fileName + "'", e1);
                }
            }
        }
        if (errorAddPj) {
            String fileNamesError = "";
            if (fileNameError.size() > 0) {
                fileNamesError = " : " + fileNameError.stream().collect(Collectors.joining(", "));
            }
            Notification.show(applicationContext.getMessage("candidature.download.encoding.pj", null, UI.getCurrent().getLocale()) + fileNamesError, Type.WARNING_MESSAGE);
        }
        ut.setDestinationFileName(fileName);
        ut.setDestinationStream(out);
        ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        is = pdfManager.cryptAndSignPdf(out, UI.getCurrent().getLocale());
        return new OnDemandFile(fileName, is);
    } catch (final Exception e) {
        logger.warn("erreur a la génération du dossier '" + fileName + "'", e);
        try {
            out = new ByteArrayInOutStream();
            final PDFMergerUtility ut = new PDFMergerUtility();
            ut.addSource(generateDossier(candidature, listePresentation, listeDatePresentation, listePj, listeForm));
            ut.setDestinationFileName(fileName);
            ut.setDestinationStream(out);
            ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
            is = pdfManager.cryptAndSignPdf(out, UI.getCurrent().getLocale());
            Notification.show(applicationContext.getMessage("candidature.download.error.pj", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
            return new OnDemandFile(fileName, is);
        } catch (final Exception e2) {
            Notification.show(applicationContext.getMessage("candidature.download.error", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
            logger.error("erreur a la génération du dossier", e2);
            return null;
        }
    } finally {
        // fermeture des fichiers
        MethodUtils.closeRessource(is);
        MethodUtils.closeRessource(out);
        MethodUtils.closeRessource(bisDossier);
        /* besoin de fermer les pdf apres coup */
        listeInputStreamToClose.forEach(inputStreamFile -> {
            MethodUtils.closeRessource(inputStreamFile);
        });
        listeInputStreamToClose.clear();
    }
}
Also used : PDFont(org.apache.pdfbox.pdmodel.font.PDFont) PDPage(org.apache.pdfbox.pdmodel.PDPage) ArrayList(java.util.ArrayList) OnDemandFile(fr.univlorraine.ecandidat.vaadin.components.OnDemandFile) Fichier(fr.univlorraine.ecandidat.entities.ecandidat.Fichier) BufferedInputStream(java.io.BufferedInputStream) PDRectangle(org.apache.pdfbox.pdmodel.common.PDRectangle) PDDocumentInformation(org.apache.pdfbox.pdmodel.PDDocumentInformation) ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) PDFMergerUtility(org.apache.pdfbox.multipdf.PDFMergerUtility) IOException(java.io.IOException) IOException(java.io.IOException) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException) PjPresentation(fr.univlorraine.ecandidat.utils.bean.presentation.PjPresentation) PDImageXObject(org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) ByteArrayInputStream(java.io.ByteArrayInputStream) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) PDPageContentStream(org.apache.pdfbox.pdmodel.PDPageContentStream) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Example 2 with XDocReportException

use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.

the class TemplateEngine method generateDocumentDocx.

public byte[] generateDocumentDocx(Properties properties, File templateFile) throws DocumentTemplateException {
    try {
        FileInputStream templateInputStream = new FileInputStream(templateFile);
        IXDocReport report = readXDocReport(templateInputStream);
        IContext context = report.createContext();
        for (Object key : properties.keySet()) {
            if (key instanceof String) {
                Object property = properties.get(key);
                // Sanitize property to avoid XML parsing errors
                if (property instanceof Enum<?> && property.toString() != null) {
                    property = returnSanitizedString(property.toString());
                } else if (property instanceof String) {
                    property = returnSanitizedString((String) property);
                }
                if (property != null && !(property instanceof String && ((String) property).isEmpty())) {
                    context.put((String) key, property);
                }
            }
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        report.process(context, outputStream);
        return outputStream.toByteArray();
    } catch (IOException | XDocReportException | VelocityException e) {
        throw new DocumentTemplateException(String.format(I18nProperties.getString(Strings.errorDocumentGeneration), templateFile.getName()));
    }
}
Also used : IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) IContext(fr.opensagres.xdocreport.template.IContext) DocumentTemplateException(de.symeda.sormas.api.docgeneneration.DocumentTemplateException) VelocityException(org.apache.velocity.exception.VelocityException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Example 3 with XDocReportException

use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.

the class TemplateEngine method extractTemplateVariablesDocx.

public DocumentVariables extractTemplateVariablesDocx(File templateFile) throws DocumentTemplateException {
    try {
        FileInputStream templateInputStream = new FileInputStream(templateFile);
        IXDocReport report = readXDocReport(templateInputStream);
        FieldsExtractor<FieldExtractor> extractor = FieldsExtractor.create();
        report.extractFields(extractor);
        return filterExtractedVariables(extractor);
    } catch (XDocReportException | IOException e) {
        throw new DocumentTemplateException(String.format(I18nProperties.getString(Strings.errorReadingTemplate), templateFile.getName()));
    }
}
Also used : IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) DocumentTemplateException(de.symeda.sormas.api.docgeneneration.DocumentTemplateException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FieldExtractor(fr.opensagres.xdocreport.template.FieldExtractor) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Example 4 with XDocReportException

use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.

the class TemplateEngine method readXDocReport.

protected IXDocReport readXDocReport(InputStream templateInputStream) throws DocumentTemplateException {
    ByteArrayOutputStream outStream;
    try {
        // Sanitize docx template for XXEs
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
        wordMLPackage.getDocumentModel();
        outStream = new ByteArrayOutputStream();
        wordMLPackage.save(outStream);
    } catch (Docx4JException | NullPointerException e) {
        throw new DocumentTemplateException(I18nProperties.getString(Strings.errorTemplateFileCorrupt));
    }
    try {
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        ITemplateEngine templateEngine = new XDocTemplateEngine(xdocVelocityProperties);
        return XDocReportRegistry.getRegistry().loadReport(inStream, templateEngine);
    } catch (IOException | XDocReportException | NullPointerException e) {
        throw new DocumentTemplateException(I18nProperties.getString(Strings.errorProcessingTemplate));
    }
}
Also used : DocumentTemplateException(de.symeda.sormas.api.docgeneneration.DocumentTemplateException) ByteArrayInputStream(java.io.ByteArrayInputStream) ITemplateEngine(fr.opensagres.xdocreport.template.ITemplateEngine) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) Docx4JException(org.docx4j.openpackaging.exceptions.Docx4JException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Example 5 with XDocReportException

use of fr.opensagres.xdocreport.core.XDocReportException in project SORMAS-Project by hzi-braunschweig.

the class TemplateEngine method validateTemplateDocx.

public void validateTemplateDocx(InputStream templateInputStream) throws DocumentTemplateException {
    try {
        IXDocReport report = readXDocReport(templateInputStream);
        FieldsExtractor<FieldExtractor> extractor = FieldsExtractor.create();
        report.extractFields(extractor);
    } catch (XDocReportException | IOException e) {
        throw new DocumentTemplateException(I18nProperties.getString(Strings.errorProcessingTemplate));
    }
}
Also used : IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) DocumentTemplateException(de.symeda.sormas.api.docgeneneration.DocumentTemplateException) IOException(java.io.IOException) FieldExtractor(fr.opensagres.xdocreport.template.FieldExtractor) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Aggregations

XDocReportException (fr.opensagres.xdocreport.core.XDocReportException)8 IOException (java.io.IOException)7 IXDocReport (fr.opensagres.xdocreport.document.IXDocReport)5 DocumentTemplateException (de.symeda.sormas.api.docgeneneration.DocumentTemplateException)4 IContext (fr.opensagres.xdocreport.template.IContext)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 InputStream (java.io.InputStream)3 Options (fr.opensagres.xdocreport.converter.Options)2 XDocConverterException (fr.opensagres.xdocreport.converter.XDocConverterException)2 FieldExtractor (fr.opensagres.xdocreport.template.FieldExtractor)2 ByteArrayInOutStream (fr.univlorraine.ecandidat.utils.ByteArrayInOutStream)2 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 ArrayList (java.util.ArrayList)2 ITemplateEngine (fr.opensagres.xdocreport.template.ITemplateEngine)1 Candidat (fr.univlorraine.ecandidat.entities.ecandidat.Candidat)1 Commission (fr.univlorraine.ecandidat.entities.ecandidat.Commission)1 CompteMinima (fr.univlorraine.ecandidat.entities.ecandidat.CompteMinima)1 Fichier (fr.univlorraine.ecandidat.entities.ecandidat.Fichier)1