Example usage for java.util.zip ZipOutputStream write

List of usage examples for java.util.zip ZipOutputStream write

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream write.

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.panet.imeta.trans.steps.mail.Mail.java

private void setAttachedFilesList(Object[] r, LogWriter log) throws Exception {
    String realSourceFileFoldername = null;
    String realSourceWildcard = null;
    FileObject sourcefile = null;
    FileObject file = null;/*  ww w  .  jav  a  2  s .c o  m*/

    ZipOutputStream zipOutputStream = null;
    File masterZipfile = null;

    if (meta.isZipFilenameDynamic())
        data.ZipFilename = data.previousRowMeta.getString(r, data.indexOfDynamicZipFilename);

    try {

        if (meta.isDynamicFilename()) {
            // dynamic attached filenames
            if (data.indexOfSourceFilename > -1)
                realSourceFileFoldername = data.previousRowMeta.getString(r, data.indexOfSourceFilename);

            if (data.indexOfSourceWildcard > -1)
                realSourceWildcard = data.previousRowMeta.getString(r, data.indexOfSourceWildcard);

        } else {
            // static attached filenames
            realSourceFileFoldername = data.realSourceFileFoldername;
            realSourceWildcard = data.realSourceWildcard;
        }

        if (!Const.isEmpty(realSourceFileFoldername)) {
            sourcefile = KettleVFS.getFileObject(realSourceFileFoldername);
            if (sourcefile.exists()) {
                long FileSize = 0;
                FileObject list[] = null;
                if (sourcefile.getType() == FileType.FILE) {
                    list = new FileObject[1];
                    list[0] = sourcefile;
                } else
                    list = sourcefile
                            .findFiles(new TextFileSelector(sourcefile.toString(), realSourceWildcard));
                if (list.length > 0) {

                    boolean zipFiles = meta.isZipFiles();
                    if (zipFiles && data.zipFileLimit == 0) {
                        masterZipfile = new File(
                                System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + data.ZipFilename);

                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));
                    }

                    for (int i = 0; i < list.length; i++) {

                        file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                        if (zipFiles) {

                            if (data.zipFileLimit == 0) {
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();
                            } else
                                FileSize += file.getContent().getSize();
                        } else {
                            addAttachedFilePart(file);
                        }
                    } // end for
                    if (zipFiles) {
                        if (log.isDebug())
                            log.logDebug(toString(), Messages.getString("Mail.Log.FileSize", "" + FileSize));
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("Mail.Log.LimitSize", "" + data.zipFileLimit));

                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit) {

                            masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                                    + data.ZipFilename);

                            zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                            for (int i = 0; i < list.length; i++) {

                                file = KettleVFS.getFileObject(KettleVFS.getFilename(list[i]));

                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                            }

                        }
                        if (data.zipFileLimit > 0 && FileSize > data.zipFileLimit || data.zipFileLimit == 0) {
                            file = KettleVFS.getFileObject(masterZipfile.getAbsolutePath());
                            addAttachedFilePart(file);
                        }
                    }
                }
            } else {
                log.logError(toString(),
                        Messages.getString("Mail.Error.SourceFileFolderNotExists", realSourceFileFoldername));
            }
        }
    } catch (Exception e) {
        log.logError(toString(), e.getMessage());
    } finally {
        if (sourcefile != null) {
            try {
                sourcefile.close();
            } catch (Exception e) {
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (Exception e) {
            }
        }

        if (zipOutputStream != null) {
            try {
                zipOutputStream.finish();
                zipOutputStream.close();
            } catch (IOException e) {
                log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString());
            }
        }
    }

}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public String storeJsonZips(String digits) {

    if ((digits == null) || (digits.length() == 0)) {
        digits = "0";
    }/* w  w w .ja v  a 2 s.c  om*/
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;

    try {

        for (int i = 0; i < 100; ++i) {

            String zip1 = digits + String.format("%02d", i);
            ParentChild data = getParentChildDao().get(zip1);

            if (data == null) {
                continue;
            }

            Map<String, ParentChild> pcs = new HashMap<String, ParentChild>();
            SortedSet<String> zip2s = new TreeSet<String>();

            for (String json : data.getChildren()) {

                JSONObject jo = new JSONObject(json);
                String key = jo.optString("key", "");
                String zip2 = jo.optString("zip2", "");

                if (key.length() == 0) {
                    continue;
                }
                if (zip2.length() == 0) {
                    continue;
                }

                if (!pcs.containsKey(jo.optString("key", ""))) {
                    pcs.put(key, getParentChildDao().get(key));
                }

                zip2s.add(zip2);
            }

            for (String zip2 : zip2s) {

                String zip = zip1 + zip2;
                String json = toJsonZips(data, zip, pcs);
                ZipEntry entry = new ZipEntry(zip + ".json");
                entry.setTime(timestamp);
                zos.putNextEntry(entry);
                zos.write(json.getBytes("UTF-8"));
                zos.closeEntry();
                ++cnt;
            }
        }

        if (cnt == 0) {

            ZipEntry entry = new ZipEntry("empty.txt");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write("empty".getBytes("UTF-8"));
            zos.closeEntry();
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_zip" + digits + ".zip");
        log.info(digits + ":" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }

    return digits.equals("9") ? null : "" + (Integer.parseInt(digits) + 1);
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }//  w ww. ja  v  a  2  s  . c om

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    if (idsToExport == null || idsToExport.size() == 0) {
        List<String> msg = new ArrayList<String>();
        msg.add(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esporta.erroreSelezioneVuota"));
        throw new ExportException(msg, EsitoOperazione.ERRORE);
    }

    if (idsToExport.size() == 1) {
        return this.esporta(idsToExport.get(0), rawValues, uriInfo, bd, zout);
    }

    String fileName = "Domini.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        DominiBD dominiBD = new DominiBD(bd);

        for (Long idDominio : idsToExport) {
            Dominio dominio = dominiBD.getDominio(idDominio);
            String folderName = dominio.getCodDominio();

            IbanAccreditoBD ibanAccreditoDB = new IbanAccreditoBD(bd);
            IbanAccreditoFilter filter = ibanAccreditoDB.newFilter();
            filter.setIdDominio(idDominio);
            List<IbanAccredito> ibans = ibanAccreditoDB.findAll(filter);
            final byte[] contiAccredito = DominioUtils.buildInformativaContoAccredito(dominio, ibans);

            ZipEntry contiAccreditoXml = new ZipEntry(folderName + "/contiAccredito.xml");
            zout.putNextEntry(contiAccreditoXml);
            zout.write(contiAccredito);
            zout.closeEntry();

            final byte[] informativa = DominioUtils.buildInformativaControparte(dominio, true);

            ZipEntry informativaXml = new ZipEntry(folderName + "/informativa.xml");
            zout.putNextEntry(informativaXml);
            zout.write(informativa);
            zout.closeEntry();

        }
        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }/*from  ww w .j  a v a 2s  .c o  m*/

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    String fileName = "Rendicontazioni.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport();
        FrBD frBD = new FrBD(bd);
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        FrFilter filter = frBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdFr(idsToExport);

        //1. eseguo una count per verificare che il numero dei risultati da esportare sia <= sogliamassimaexport massivo
        boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, frBD, simpleSearch, filter);

        if (!eseguiRicerca) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.operazioneNonPermessa"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        long count = frBD.countExt(filter);

        if (count < 1) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        if (count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        filter.setOffset(0);
        filter.setLimit(limit);
        FilterSortWrapper fsw = new FilterSortWrapper();
        fsw.setField(it.govpay.orm.FR.model().DATA_ORA_FLUSSO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Fr> findAllExt = frBD.findAllExt(filter);

        for (Fr fr : findAllExt) {
            String folderName = "Rendicontazione_" + fr.getIur();

            ZipEntry frXml = new ZipEntry(folderName + "/fr.xml");
            zout.putNextEntry(frXml);
            zout.write(fr.getXml());
            zout.closeEntry();
        }
        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (ExportException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:it.govpay.web.rs.dars.reportistica.pagamenti.PagamentiHandler.java

@Override
public String esporta(Long idToExport, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout)
        throws WebApplicationException, ConsoleException {
    String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]";
    Printer printer = null;//from  w ww.  java 2  s . co m
    int numeroZipEntries = 0;
    try {
        String fileName = "Pagamenti.zip";
        this.log.info("Esecuzione " + methodName + " in corso...");
        Operatore operatore = this.darsService.getOperatoreByPrincipal(bd);
        ProfiloOperatore profilo = operatore.getProfilo();
        boolean isAdmin = profilo.equals(ProfiloOperatore.ADMIN);

        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);
        EstrattiContoBD pagamentiBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = pagamentiBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = new ArrayList<Long>();
        ids.add(idToExport);
        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);

        if (!isAdmin) {

            AclBD aclBD = new AclBD(bd);
            List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId());

            boolean vediTuttiDomini = false;
            List<Long> idDomini = new ArrayList<Long>();
            for (Acl acl : aclOperatore) {
                if (Tipo.DOMINIO.equals(acl.getTipo())) {
                    if (acl.getIdDominio() == null) {
                        vediTuttiDomini = true;
                        break;
                    } else {
                        idDomini.add(acl.getIdDominio());
                    }
                }
            }
            if (!vediTuttiDomini) {
                if (idDomini.isEmpty()) {
                    eseguiRicerca = false;
                } else {
                    filter.setIdDomini(toListCodDomini(idDomini, bd));
                }
            }

            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
            if (eseguiRicerca) {
                filter.setIdSingoloVersamento(ids);
                eseguiRicerca = eseguiRicerca && pagamentiBD.count(filter) > 0;
            }
        }

        if (eseguiRicerca) {
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? pagamentiBD.estrattoContoFromIdSingoliVersamenti(filter)
                    : new ArrayList<EstrattoConto>();

            if (findAll != null && findAll.size() > 0) {
                numeroZipEntries++;
                //ordinamento record
                Collections.sort(findAll, new EstrattoContoComparator());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv");
                    zout.putNextEntry(pagamentoCsv);
                    printer = new Printer(this.getFormat(), baos);
                    printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                    for (EstrattoConto pagamento : findAll) {
                        printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                    }
                } finally {
                    try {
                        if (printer != null) {
                            printer.close();
                        }
                    } catch (Exception e) {
                        throw new Exception("Errore durante la chiusura dello stream ", e);
                    }
                }
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }

            SingoloVersamento singoloVersamento = singoliVersamentiBD.getSingoloVersamento(idToExport);
            Versamento versamento = singoloVersamento.getVersamento(bd);
            UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
            Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());
            // Estratto conto per iban e codiceversamento.
            List<Long> idSingoliVersamentiDominio = new ArrayList<Long>();
            idSingoliVersamentiDominio.add(idToExport);

            it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                    .creaEstrattoContoPagamentiPDF(dominio, idSingoliVersamentiDominio);
            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            listInputEstrattoConto.add(input);
            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                    .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi);

            for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
                Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
                for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                    numeroZipEntries++;
                    ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                    ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry);
                    zout.putNextEntry(estrattoContoEntry);
                    zout.write(baos.toByteArray());
                    zout.closeEntry();
                }
            }

        }
        // se non ho inserito nessuna entry
        if (numeroZipEntries == 0) {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sui pagamenti selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:org.etudes.mneme.impl.SubmissionServiceImpl.java

/**
 * {@inheritDoc}//from w  ww  .j  a va  2  s. c  o  m
 */
public void zipSubmissionsQuestion(ZipOutputStream zip, Assessment assessment, Question question) {
    // the index.html file
    StringBuilder indexHtml = new StringBuilder();
    indexHtml.append("<html><head></head><body>\n");

    // add the assessment information to the index
    String assessmentTitle = assessment.getTitle();
    if (assessmentTitle != null) {
        indexHtml.append("<div><strong>" + assessment.getType().toString() + " &quot;" + assessmentTitle
                + "&quot;</strong></div>\n");
    }

    // the question (if it has presentation)
    String questionText = HtmlHelper.clean(question.getPresentation().getText(), false);
    String questionFile = null;
    if (questionText != null) {
        try {
            // "question.html"
            questionFile = this.messages.getFormattedMessage("download_submissions_question_file_name", null);
            zip.putNextEntry(new ZipEntry(questionFile));
            zip.write(questionText.getBytes("UTF-8"));
            zip.closeEntry();
        } catch (IOException e) {
            M_log.warn("zipSubmissionsQuestion: zipping question: " + e.toString());
        }
    }

    // add the question information to the index
    String questionDescription = question.getDescription();
    if (questionDescription != null) {
        // shorten
        questionDescription = questionDescription.replace("\n", " ");
        if (questionDescription.length() > 60) {
            questionDescription = questionDescription.substring(0, 60) + "...";
        }
        questionDescription = Validator.escapeHtml(questionDescription);

        // "Submissions for question:"
        String header = this.messages.getFormattedMessage("download_submissions_header", null);
        indexHtml.append("<p>" + header + " &quot;");
        if (questionFile != null) {
            indexHtml.append("<a href=\"" + questionFile + "\">");
        }
        indexHtml.append(questionDescription);
        if (questionFile != null) {
            indexHtml.append("</a>");
        }
        indexHtml.append("&quot;</p>\n");
    }

    indexHtml.append("<hr>\n");

    Map<String, Integer> usersSeen = new HashMap<String, Integer>();

    // get all the submissions
    List<Answer> answers = findSubmissionAnswers(assessment, question, FindAssessmentSubmissionsSort.userName_a,
            null, null);
    for (Answer answer : answers) {
        try {
            User user = this.userDirectoryService.getUser(answer.getSubmission().getUserId());

            // keep track of how many submissions for each user
            int uCount = 1;
            Integer userCount = usersSeen.get(answer.getSubmission().getUserId());
            if (userCount != null) {
                uCount = userCount.intValue();
                uCount++;
            }
            usersSeen.put(answer.getSubmission().getUserId(), Integer.valueOf(uCount));

            String key = user.getSortName() + " (" + user.getEid() + ") " + Integer.toString(uCount) + " ";

            TypeSpecificAnswer a = answer.getTypeSpecificAnswer();
            if (a instanceof EssayAnswerImpl) {
                String dateDisplay = DateHelper.formatDate(answer.getSubmission().getSubmittedDate(), null);

                indexHtml.append(
                        "<div>" + user.getSortName() + " (" + user.getEid() + ") " + dateDisplay + "\n<ul>\n");

                EssayAnswerImpl essay = (EssayAnswerImpl) a;

                // answer - inline
                String inline = HtmlHelper.clean(essay.getAnswerData(), false);
                if (inline != null) {
                    // "inline.html"
                    zip.putNextEntry(new ZipEntry(key + " " + this.messages
                            .getFormattedMessage("download_submissions_inline_file_name", null)));
                    zip.write(inline.getBytes("UTF-8"));
                    zip.closeEntry();

                    indexHtml.append("<li><a href=\"" + key + " "
                            + this.messages.getFormattedMessage("download_submissions_inline_file_name", null)
                            + "\">" + this.messages.getFormattedMessage("download_submissions_inline", null)
                            + "</a></li>\n");
                }

                // attachments
                List<Reference> attachments = essay.getUploaded();
                int count = 1;
                for (Reference attachment : attachments) {
                    zipAttachment(zip, key, attachment, count++, indexHtml);
                }
                indexHtml.append("</ul>\n");
            }
        } catch (UserNotDefinedException e) {
            M_log.warn("zipSubmissionsQuestion: zipping answers: " + e.toString());
        } catch (IOException e) {
            M_log.warn("zipSubmissionsQuestion: zipping answers: " + e.toString());
        }
    }

    try {
        // "index.html"
        zip.putNextEntry(new ZipEntry(this.messages.getFormattedMessage("download_submissions_index", null)));
        zip.write(indexHtml.toString().getBytes("UTF-8"));
        zip.closeEntry();
    } catch (IOException e) {
        M_log.warn("zipSubmissionsQuestion: zipping index: " + e.toString());
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.incassi.IncassiHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }/*from w  ww .j  av  a2  s  . c o  m*/

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    int numeroZipEntries = 0;
    String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();

    //      if(idsToExport.size() == 1) {
    //         return this.esporta(idsToExport.get(0), uriInfo, bd, zout);
    //      } 

    String fileName = "Export.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);
        int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport();
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        IncassiBD incassiBD = new IncassiBD(bd);
        IncassoFilter filter = incassiBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdIncasso(idsToExport);

        boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, bd, simpleSearch, filter);

        if (!eseguiRicerca) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.operazioneNonPermessa"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        long count = incassiBD.count(filter);

        if (count < 1) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        if (count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        filter.setOffset(0);
        filter.setLimit(limit);
        FilterSortWrapper fsw = new FilterSortWrapper();
        fsw.setField(it.govpay.orm.Incasso.model().DATA_ORA_INCASSO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Incasso> findAll = incassiBD.findAll(filter);

        for (Incasso incasso : findAll) {
            Applicazione applicazione = incasso.getApplicazione(incassiBD);
            List<Pagamento> pagamenti = incasso.getPagamenti(incassiBD);
            List<it.govpay.model.Pagamento> pagamentiList = new ArrayList<it.govpay.model.Pagamento>();
            pagamentiList.addAll(pagamenti);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IncassoPdf.getPdfIncasso(pathLoghi, incasso, pagamentiList, applicazione, baos, this.log);
            String incassoPdfEntryName = incasso.getTrn() + ".pdf";
            numeroZipEntries++;
            ZipEntry rtPdf = new ZipEntry(incassoPdfEntryName);
            zout.putNextEntry(rtPdf);
            zout.write(baos.toByteArray());
            zout.closeEntry();
        }

        // se non ho inserito nessuna entry
        if (numeroZipEntries == 0) {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sugli incassi selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:de.innovationgate.wga.model.WGADesignConfigurationModel.java

private ZipOutputStream createZIP(File zipFile, boolean obfuscate, String javaSourceFolder)
        throws FileNotFoundException, PersistentKeyException, GeneralSecurityException, IOException {
    if (!zipFile.exists()) {
        zipFile.createNewFile();/* ww w. j av a2 s .  c  o m*/
    }

    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
    zipOutputStream.setLevel(0);

    DirZipper zipper = new DirZipper();
    zipper.setInputStreamProvider(new PluginISProvider(_designDirectory, obfuscate));
    zipper.addFilePatternToIgnore("^\\..*$");

    // Zip all folders and files that belong into an exported plugin
    List<File> filesToZip = new ArrayList<File>();
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_TML));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_SCRIPT));
    filesToZip.add(new File(_designDirectory, DesignDirectory.FOLDERNAME_FILES));
    filesToZip.add(new File(_designDirectory, DesignDirectory.SYNCINFO_FILE));
    filesToZip.add(new File(_designDirectory, DesignDirectory.DESIGN_DEFINITION_FILE));
    Iterator<File> files = filesToZip.iterator();
    while (files.hasNext()) {
        File file = (File) files.next();
        if (file.exists()) {
            if (file.isDirectory()) {
                zipper.zipDirectory(file, zipOutputStream, file.getName() + "/");
            } else {
                zipper.zipFile(file, zipOutputStream);
            }

        }
    }

    // If the design directory has a java classes folder we put those into a jar and zip them to "files/system"
    File javaClassesDir = new File(_designDirectory, DesignDirectory.FOLDERNAME_JAVA);
    if (javaClassesDir.exists() && javaClassesDir.isDirectory()) {
        TemporaryFile jar = new TemporaryFile("plugin-classes.jar", null, null);
        ZipOutputStream jarStream = new ZipOutputStream(new FileOutputStream(jar.getFile()));
        jarStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaClassesDir, jarStream);

        jarStream.close();

        zipper.zipNormalFile(jar.getFile(), zipOutputStream, "files/system/");

        jar.delete();
    }

    // If we were given a java source folder we put its contents into plugin-sources.zip and put that into "files/system" (for OSS plugins)
    if (javaSourceFolder != null) {
        File javaSourceDir = new File(javaSourceFolder);
        TemporaryFile zip = new TemporaryFile("plugin-sources.zip", null, null);
        ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(zip.getFile()));
        zipStream.setLevel(0);
        DirZipper jarZipper = new DirZipper();
        jarZipper.addFilePatternToIgnore("^\\..*$");
        jarZipper.zipDirectory(javaSourceDir, zipStream);

        zipStream.close();

        zipper.zipNormalFile(zip.getFile(), zipOutputStream, "files/system/");

        zip.delete();
    }

    if (obfuscate) {
        ZipEntry anEntry = new ZipEntry(DesignDirectory.OBFUSCATE_FLAGFILE);
        zipOutputStream.putNextEntry(anEntry);
        zipOutputStream.write("Obfuscation flagfile".getBytes());
    }

    return zipOutputStream;
}

From source file:it.govpay.web.rs.dars.monitoraggio.pagamenti.ReportisticaPagamentiHandler.java

@Override
public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]";
    Printer printer = null;/* ww w  . j  av  a2s  .  c om*/
    int numeroZipEntries = 0;
    try {
        String fileName = "Pagamenti.zip";
        this.log.info("Esecuzione " + methodName + " in corso...");
        //         Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); 

        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);
        EstrattiContoBD pagamentiBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = pagamentiBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = new ArrayList<Long>();
        ids.add(idToExport);
        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);

        //         if(!isAdmin){
        //
        //            AclBD aclBD = new AclBD(bd);
        //            List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId());
        //
        //            boolean vediTuttiDomini = false;
        //            List<Long> idDomini = new ArrayList<Long>();
        //            for(Acl acl: aclOperatore) {
        //               if(Tipo.DOMINIO.equals(acl.getTipo())) {
        //                  if(acl.getIdDominio() == null) {
        //                     vediTuttiDomini = true;
        //                     break;
        //                  } else {
        //                     idDomini.add(acl.getIdDominio());
        //                  }
        //               }
        //            }
        //            if(!vediTuttiDomini) {
        //               if(idDomini.isEmpty()) {
        //                  eseguiRicerca = false;
        //               } else {
        //                  filter.setIdDomini(toListCodDomini(idDomini, bd));
        //               }
        //            }
        //
        //            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
        //            if(eseguiRicerca){
        //               filter.setIdSingoloVersamento(ids);
        //               eseguiRicerca = eseguiRicerca && pagamentiBD.count(filter) > 0;
        //            }
        //         }

        if (eseguiRicerca) {
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? pagamentiBD.estrattoContoFromIdSingoliVersamenti(filter)
                    : new ArrayList<EstrattoConto>();

            if (findAll != null && findAll.size() > 0) {
                numeroZipEntries++;
                //ordinamento record
                Collections.sort(findAll, new EstrattoContoComparator());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv");
                    zout.putNextEntry(pagamentoCsv);
                    printer = new Printer(this.getFormat(), baos);
                    printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                    for (EstrattoConto pagamento : findAll) {
                        printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                    }
                } finally {
                    try {
                        if (printer != null) {
                            printer.close();
                        }
                    } catch (Exception e) {
                        throw new Exception("Errore durante la chiusura dello stream ", e);
                    }
                }
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }

            SingoloVersamento singoloVersamento = singoliVersamentiBD.getSingoloVersamento(idToExport);
            Versamento versamento = singoloVersamento.getVersamento(bd);
            UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
            Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());
            // Estratto conto per iban e codiceversamento.
            List<Long> idSingoliVersamentiDominio = new ArrayList<Long>();
            idSingoliVersamentiDominio.add(idToExport);

            it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                    .creaEstrattoContoPagamentiPDF(dominio, idSingoliVersamentiDominio);
            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            listInputEstrattoConto.add(input);
            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                    .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi);

            for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
                Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
                for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                    numeroZipEntries++;
                    ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                    ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry);
                    zout.putNextEntry(estrattoContoEntry);
                    zout.write(baos.toByteArray());
                    zout.closeEntry();
                }
            }

        }
        // se non ho inserito nessuna entry
        if (numeroZipEntries == 0) {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sui pagamenti selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.java

@Override
public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]";
    Printer printer = null;/*from ww  w  . j  a v  a2s  . c  om*/

    try {
        int numeroZipEntries = 0;
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita);
        boolean eseguiRicerca = !setDomini.isEmpty();

        VersamentiBD versamentiBD = new VersamentiBD(bd);
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);
        VersamentoFilter filter = versamentiBD.newFilter();

        List<Long> ids = new ArrayList<Long>();
        ids.add(idToExport);

        if (!setDomini.contains(-1L)) {
            List<Long> lstCodDomini = new ArrayList<Long>();
            lstCodDomini.addAll(setDomini);
            filter.setIdDomini(lstCodDomini);

            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
            if (eseguiRicerca) {
                filter.setIdVersamento(ids);
                eseguiRicerca = eseguiRicerca && versamentiBD.count(filter) > 0;
            }
        }

        Versamento versamento = eseguiRicerca ? versamentiBD.getVersamento(idToExport) : null;
        String fileName = "Export.zip";

        if (versamento != null) {
            // Prelevo il dominio

            UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
            Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());

            // Estratto conto per iban e codiceversamento.
            List<Long> idVersamentiDominio = new ArrayList<Long>();
            idVersamentiDominio.add(idToExport);
            it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                    .creaEstrattoContoVersamentiPDF(dominio, idVersamentiDominio);
            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            listInputEstrattoConto.add(input);
            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                    .getEstrattoContoVersamenti(listInputEstrattoConto, pathLoghi);

            for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
                Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
                for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                    numeroZipEntries++;
                    ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                    ZipEntry estrattoContoEntry = new ZipEntry(
                            estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                    zout.putNextEntry(estrattoContoEntry);
                    zout.write(baos.toByteArray());
                    zout.closeEntry();
                }
            }

            //Estratto conto in formato CSV
            EstrattoContoFilter ecFilter = estrattiContoBD.newFilter(true);
            ecFilter.setIdVersamento(ids);
            List<EstrattoConto> findAll = estrattiContoBD.estrattoContoFromIdVersamenti(ecFilter);

            if (findAll != null && findAll.size() > 0) {
                //ordinamento record
                Collections.sort(findAll, new EstrattoContoComparator());
                numeroZipEntries++;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ZipEntry pagamentoCsv = new ZipEntry("estrattoConto.csv");
                    zout.putNextEntry(pagamentoCsv);
                    printer = new Printer(this.getFormat(), baos);
                    printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                    for (EstrattoConto pagamento : findAll) {
                        printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                    }
                } finally {
                    try {
                        if (printer != null) {
                            printer.close();
                        }
                    } catch (Exception e) {
                        throw new Exception("Errore durante la chiusura dello stream ", e);
                    }
                }
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }
        }

        // se non ho inserito nessuna entry
        if (numeroZipEntries == 0) {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sui versamenti selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (ExportException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}