Search in sources :

Example 1 with ByteArrayInOutStream

use of fr.univlorraine.ecandidat.utils.ByteArrayInOutStream in project esup-ecandidat by EsupPortail.

the class PdfManager method cryptPdf.

/**
 * Crypte un pdf
 * @param  inStream
 * @param  locale
 * @return             un pdf crypté
 * @throws IOException
 */
private ByteArrayInOutStream cryptPdf(final ByteArrayInOutStream inStream) throws IOException {
    /* Si on ne crypte pas on renvoit le stream original */
    if (!isCryptPdfEnable()) {
        return inStream;
    }
    final ByteArrayInOutStream outCrypted = new ByteArrayInOutStream();
    final PDDocument pdd = PDDocument.load(inStream.getInputStream());
    final AccessPermission ap = new AccessPermission();
    ap.setCanAssembleDocument(cryptHasAuth(CRYPT_AUTH_ASSEMBLE));
    ap.setCanExtractContent(cryptHasAuth(CRYPT_AUTH_EXTRACT));
    ap.setCanExtractForAccessibility(cryptHasAuth(CRYPT_AUTH_EXTRACT_FOR_ACC));
    ap.setCanFillInForm(cryptHasAuth(CRYPT_AUTH_FILL_IN));
    ap.setCanModify(cryptHasAuth(CRYPT_AUTH_MODIFY));
    ap.setCanModifyAnnotations(cryptHasAuth(CRYPT_AUTH_MODIFY_ANNOT));
    ap.setCanPrint(cryptHasAuth(CRYPT_AUTH_PRINT));
    ap.setCanPrintDegraded(cryptHasAuth(CRYPT_AUTH_PRINT_DEGRAD));
    final StandardProtectionPolicy stpp = new StandardProtectionPolicy(pdfCryptPass, null, ap);
    stpp.setEncryptionKeyLength(128);
    stpp.setPermissions(ap);
    pdd.protect(stpp);
    pdd.save(outCrypted);
    pdd.close();
    return outCrypted;
}
Also used : ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) StandardProtectionPolicy(org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) AccessPermission(org.apache.pdfbox.pdmodel.encryption.AccessPermission)

Example 2 with ByteArrayInOutStream

use of fr.univlorraine.ecandidat.utils.ByteArrayInOutStream in project esup-ecandidat by EsupPortail.

the class CandidatureController method downlaodMultipleDossierZip.

/**
 * @param  liste
 * @param  nameFile
 * @return          un zip contenant tous les dossiers
 */
private OnDemandFile downlaodMultipleDossierZip(final List<Candidature> liste, final String nameFile) {
    final ByteArrayInOutStream out = new ByteArrayInOutStream();
    final ZipOutputStream zos = new ZipOutputStream(out);
    Boolean error = false;
    for (final Candidature candidature : liste) {
        OnDemandFile bisDossier = null;
        try {
            // le dossier outStream
            bisDossier = downloadDossier(candidature, getInformationsCandidature(candidature, false), getInformationsDateCandidature(candidature, false), candidaturePieceController.getPjCandidature(candidature), candidaturePieceController.getFormulaireCandidature(candidature), parametreController.getIsDownloadMultipleAddPj());
            final String fileName = applicationContext.getMessage("candidature.download.file", new Object[] { candidature.getCandidat().getCompteMinima().getNumDossierOpiCptMin(), candidature.getCandidat().getNomPatCandidat(), candidature.getCandidat().getPrenomCandidat(), candidature.getFormation().getCodForm() }, UI.getCurrent().getLocale());
            zos.putNextEntry(new ZipEntry(fileName));
            int count;
            final byte[] data = new byte[2048];
            while ((count = bisDossier.getInputStream().read(data, 0, 2048)) != -1) {
                zos.write(data, 0, count);
            }
            zos.closeEntry();
        } catch (final IOException e) {
            error = true;
            logger.error("erreur a la génération d'un dossier lors du zip", e);
        } finally {
        /* Nettoyage des ressources */
        // MethodUtils.closeRessource(bisDossier);
        }
    }
    if (error) {
        Notification.show(applicationContext.getMessage("candidature.download.multiple.error.file", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
    }
    try {
        zos.finish();
        zos.close();
        return new OnDemandFile(nameFile + ".zip", out.getInputStream());
    } catch (final IOException e) {
        logger.error("erreur a la génération du zip", e);
        Notification.show(applicationContext.getMessage("candidature.download.multiple.error.zip", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
        return null;
    } finally {
        /* Nettoyage des ressources */
        MethodUtils.closeRessource(zos);
        MethodUtils.closeRessource(out);
    }
}
Also used : ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) ZipOutputStream(java.util.zip.ZipOutputStream) ZipEntry(java.util.zip.ZipEntry) CentreCandidature(fr.univlorraine.ecandidat.entities.ecandidat.CentreCandidature) TypeDecisionCandidature(fr.univlorraine.ecandidat.entities.ecandidat.TypeDecisionCandidature) Candidature(fr.univlorraine.ecandidat.entities.ecandidat.Candidature) ExportDossierCandidature(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidature) SecurityCentreCandidature(fr.univlorraine.ecandidat.services.security.SecurityCentreCandidature) OnDemandFile(fr.univlorraine.ecandidat.vaadin.components.OnDemandFile) IOException(java.io.IOException)

Example 3 with ByteArrayInOutStream

use of fr.univlorraine.ecandidat.utils.ByteArrayInOutStream 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 4 with ByteArrayInOutStream

use of fr.univlorraine.ecandidat.utils.ByteArrayInOutStream in project esup-ecandidat by EsupPortail.

the class CandidatureController method downlaodMultipleDossierPdf.

/**
 * @param  liste
 * @param  nameFile
 * @return          un pdf contenant tous les dossiers
 */
private OnDemandFile downlaodMultipleDossierPdf(final List<Candidature> liste, final String nameFile) {
    final ByteArrayInOutStream out = new ByteArrayInOutStream();
    final PDFMergerUtility ut = new PDFMergerUtility();
    Boolean error = false;
    for (final Candidature candidature : liste) {
        OnDemandFile bisDossier = null;
        try {
            bisDossier = downloadDossier(candidature, getInformationsCandidature(candidature, false), getInformationsDateCandidature(candidature, false), candidaturePieceController.getPjCandidature(candidature), candidaturePieceController.getFormulaireCandidature(candidature), parametreController.getIsDownloadMultipleAddPj());
            ut.addSource(bisDossier.getInputStream());
        } catch (final Exception e) {
            error = true;
            logger.error("erreur a la génération d'un dossier lors du zip", e);
        } finally {
        /* Nettoyage des ressources */
        // MethodUtils.closeRessource(bisDossier);
        }
    }
    if (error) {
        Notification.show(applicationContext.getMessage("candidature.download.multiple.error.file", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
    }
    try {
        ut.setDestinationFileName(nameFile);
        ut.setDestinationStream(out);
        ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new OnDemandFile(nameFile + ".pdf", out.getInputStream());
    } catch (final IOException e) {
        logger.error("erreur a la génération du pdf multiple", e);
        Notification.show(applicationContext.getMessage("candidature.download.multiple.error.pdf", null, UI.getCurrent().getLocale()), Type.WARNING_MESSAGE);
        return null;
    } finally {
        /* Nettoyage des ressources */
        MethodUtils.closeRessource(out);
    }
}
Also used : ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) PDFMergerUtility(org.apache.pdfbox.multipdf.PDFMergerUtility) CentreCandidature(fr.univlorraine.ecandidat.entities.ecandidat.CentreCandidature) TypeDecisionCandidature(fr.univlorraine.ecandidat.entities.ecandidat.TypeDecisionCandidature) Candidature(fr.univlorraine.ecandidat.entities.ecandidat.Candidature) ExportDossierCandidature(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidature) SecurityCentreCandidature(fr.univlorraine.ecandidat.services.security.SecurityCentreCandidature) OnDemandFile(fr.univlorraine.ecandidat.vaadin.components.OnDemandFile) IOException(java.io.IOException) IOException(java.io.IOException) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException)

Example 5 with ByteArrayInOutStream

use of fr.univlorraine.ecandidat.utils.ByteArrayInOutStream in project esup-ecandidat by EsupPortail.

the class CandidatureController method generateDossier.

/**
 * @param  candidature
 * @param  listePresentation
 * @param  listeDatePresentation
 * @param  adresse
 * @param  listePj
 * @param  listeForm
 * @return                       l'InputStream d'export
 * @throws IOException
 * @throws XDocReportException
 */
private ByteArrayInputStream generateDossier(final Candidature candidature, final List<SimpleTablePresentation> listePresentation, final List<SimpleTablePresentation> listeDatePresentation, final List<PjPresentation> listePj, final List<FormulairePresentation> listeForm) throws IOException, XDocReportException {
    InputStream in = null;
    final ByteArrayInOutStream out = new ByteArrayInOutStream();
    try {
        // 1) Load Docx file by filling Velocity template engine and cache
        // it to the registry
        in = MethodUtils.getXDocReportTemplate(ConstanteUtils.TEMPLATE_DOSSIER, i18nController.getLangueCandidat(), cacheController.getLangueDefault().getCodLangue());
        if (in == null) {
            return null;
        }
        /* Chargement des données utiles */
        final Candidat candidat = candidature.getCandidat();
        final CompteMinima cptMin = candidat.getCompteMinima();
        final Formation formation = candidature.getFormation();
        final Commission commission = formation.getCommission();
        /* Utilisation de la demat */
        final Boolean isDematerialisation = isCandidatureDematerialise(candidature);
        /* On place les données dans des bean speciales export */
        final ExportDossierCandidature exportCandidature = new ExportDossierCandidature(campagneController.getLibelleCampagne(cptMin.getCampagne()), commission.getLibComm(), adresseController.getLibelleAdresse(commission.getAdresse(), "\n"), commission.getMailComm(), commission.getTelComm(), formation, MethodUtils.formatToExportHtml(i18nController.getI18nTraduction(commission.getI18nCommentRetourComm())));
        final ExportDossierCandidat exportCandidat = new ExportDossierCandidat(cptMin, candidat, formatterDate.format(candidat.getDatNaissCandidat()), adresseController.getLibelleAdresse(candidat.getAdresse(), "\n"), candidat.getIneCandidat(), candidat.getCleIneCandidat());
        final ExportDossierBac exportDossierBac = new ExportDossierBac(candidat);
        final List<ExportDossierCursusInterne> listeCursusInterne = new ArrayList<>();
        candidat.getCandidatCursusInternes().forEach(e -> listeCursusInterne.add(new ExportDossierCursusInterne(e)));
        listeCursusInterne.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierCursusExterne> listeCursusExterne = new ArrayList<>();
        candidat.getCandidatCursusPostBacs().forEach(e -> listeCursusExterne.add(new ExportDossierCursusExterne(e, tableRefController.getLibelleObtenuCursusByCode(e.getObtenuCursus()))));
        listeCursusExterne.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierStage> listeStage = new ArrayList<>();
        candidat.getCandidatStage().forEach(e -> listeStage.add(new ExportDossierStage(e)));
        listeStage.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierCursusPro> listeCursusPro = new ArrayList<>();
        candidat.getCandidatCursusPros().forEach(e -> listeCursusPro.add(new ExportDossierCursusPro(e)));
        listeCursusPro.sort((p1, p2) -> p1.getAnnee().compareTo(p2.getAnnee()));
        final List<ExportDossierMotivationAvis> listeMotivationAvis = new ArrayList<>();
        final List<ExportDossierAvis> listeAvis = new ArrayList<>();
        final List<ExportDossierPj> listeExportPj = new ArrayList<>();
        if (!isDematerialisation) {
            listePj.forEach(e -> {
                if (!(e.getFilePj() == null && e.getPJConditionnel() && e.getCodStatut() != null && e.getCodStatut().equals(NomenclatureUtils.TYP_STATUT_PIECE_NON_CONCERNE))) {
                    listeExportPj.add(new ExportDossierPj(e.getLibPj(), e.getLibStatut(), e.getCommentaire()));
                }
            });
            // listePj.forEach(e->listeExportPj.add(new
            // ExportDossierPj(e.getLibPj(),e.getLibStatut(),e.getCommentaire())));
            motivationAvisController.getMotivationAvisEnServiceByCtrCand(commission.getCentreCandidature()).forEach(e -> listeMotivationAvis.add(new ExportDossierMotivationAvis(i18nController.getI18nTraduction(e.getI18nLibMotiv()))));
            typeDecisionController.getTypeDecisionsEnServiceByCtrCand(commission.getCentreCandidature()).forEach(e -> listeAvis.add(new ExportDossierAvis(i18nController.getI18nTraduction(e.getI18nLibTypDec()), e.getTypeAvis().getCodTypAvis())));
            listeAvis.sort((p1, p2) -> p1.getOrder().compareTo(p2.getOrder()));
        } else {
            listePj.forEach(e -> {
                final ExportDossierPj exportDossierPj = new ExportDossierPj(e.getLibPj(), e.getLibStatut(), e.getCommentaire());
                if (e.getFilePj() != null && e.getFilePj().getFileFichier() != null) {
                    exportDossierPj.setLibFichier(e.getFilePj().getNomFichier());
                }
                listeExportPj.add(exportDossierPj);
            });
        }
        final ExportDossierDate listeDates = new ExportDossierDate(MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datRetourForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datConfirmForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datJuryForm.getName()), MethodUtils.getLibByPresentationCode(listeDatePresentation, "candidature." + Candidature_.formation.getName() + "." + Formation_.datPubliForm.getName()));
        final IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
        // 2) Create fields metadata to manage lazy loop (#foreach velocity) for table
        // row.
        /* FieldsMetadata metadata = report.createFieldsMetadata(); metadata.load(
			 * "cursusInterne", ExportDossierCursusInterne.class, true ); */
        // 3) Create context Java model
        final IContext context = report.createContext();
        // Register project
        context.put("dateheure", formatterDateTime.format(LocalDateTime.now()));
        context.put("adresseEcandidat", loadBalancingController.getApplicationPathForCandidat());
        context.put("candidature", exportCandidature);
        context.put("candidat", exportCandidat);
        context.put("bac", exportDossierBac);
        context.put("cursusInternes", listeCursusInterne);
        context.put("affichageCursusInterne", listeCursusInterne.size() > 0);
        context.put("cursusExternes", listeCursusExterne);
        context.put("affichageCursusExterne", listeCursusExterne.size() > 0);
        context.put("stages", listeStage);
        context.put("affichageStage", listeStage.size() > 0);
        context.put("cursusPros", listeCursusPro);
        context.put("affichageCursusPro", listeCursusPro.size() > 0);
        context.put("listeAvis", listeAvis);
        context.put("listeMotivationAvis", listeMotivationAvis);
        context.put("dates", listeDates);
        context.put("listePiecesJustifs", listeExportPj);
        context.put("non-dematerialisation", !isDematerialisation);
        context.put("affichagePjDemat", (listeExportPj.size() > 0 && isDematerialisation));
        // 4) Generate report by merging Java model with the Docx
        final Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.XWPF);
        report.convert(context, options, out);
        in.close();
        return out.getInputStream();
    } catch (final Exception e) {
        return null;
    } finally {
        // fermeture des fichiers
        MethodUtils.closeRessource(in);
        MethodUtils.closeRessource(out);
    }
}
Also used : Options(fr.opensagres.xdocreport.converter.Options) IContext(fr.opensagres.xdocreport.template.IContext) ExportDossierAvis(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierAvis) ExportDossierCursusPro(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusPro) Commission(fr.univlorraine.ecandidat.entities.ecandidat.Commission) SecurityCommission(fr.univlorraine.ecandidat.services.security.SecurityCommission) ArrayList(java.util.ArrayList) ExportDossierCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidat) Candidat(fr.univlorraine.ecandidat.entities.ecandidat.Candidat) ExportLettreCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportLettreCandidat) ExportDossierCandidat(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidat) ExportDossierCursusExterne(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusExterne) ExportDossierCandidature(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidature) ExportDossierBac(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierBac) ByteArrayInOutStream(fr.univlorraine.ecandidat.utils.ByteArrayInOutStream) IXDocReport(fr.opensagres.xdocreport.document.IXDocReport) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ExportDossierCursusInterne(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCursusInterne) ExportDossierMotivationAvis(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierMotivationAvis) IOException(java.io.IOException) XDocConverterException(fr.opensagres.xdocreport.converter.XDocConverterException) XDocReportException(fr.opensagres.xdocreport.core.XDocReportException) CompteMinima(fr.univlorraine.ecandidat.entities.ecandidat.CompteMinima) ExportDossierDate(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierDate) ExportDossierPj(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierPj) ExportDossierStage(fr.univlorraine.ecandidat.utils.bean.export.ExportDossierStage) Formation(fr.univlorraine.ecandidat.entities.ecandidat.Formation)

Aggregations

ByteArrayInOutStream (fr.univlorraine.ecandidat.utils.ByteArrayInOutStream)8 IOException (java.io.IOException)6 OnDemandFile (fr.univlorraine.ecandidat.vaadin.components.OnDemandFile)5 XDocConverterException (fr.opensagres.xdocreport.converter.XDocConverterException)4 XDocReportException (fr.opensagres.xdocreport.core.XDocReportException)4 InputStream (java.io.InputStream)4 Candidature (fr.univlorraine.ecandidat.entities.ecandidat.Candidature)3 ExportDossierCandidature (fr.univlorraine.ecandidat.utils.bean.export.ExportDossierCandidature)3 BufferedInputStream (java.io.BufferedInputStream)3 Options (fr.opensagres.xdocreport.converter.Options)2 IXDocReport (fr.opensagres.xdocreport.document.IXDocReport)2 IContext (fr.opensagres.xdocreport.template.IContext)2 CentreCandidature (fr.univlorraine.ecandidat.entities.ecandidat.CentreCandidature)2 Fichier (fr.univlorraine.ecandidat.entities.ecandidat.Fichier)2 TypeDecisionCandidature (fr.univlorraine.ecandidat.entities.ecandidat.TypeDecisionCandidature)2 SecurityCentreCandidature (fr.univlorraine.ecandidat.services.security.SecurityCentreCandidature)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ArrayList (java.util.ArrayList)2 PDDocument (org.apache.pdfbox.pdmodel.PDDocument)2 ByteArrayImageProvider (fr.opensagres.xdocreport.document.images.ByteArrayImageProvider)1