Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

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  .j  a va 2s .  c  o 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: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(", ");
            }//  www . j a va  2  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: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;/* w w w .  j a  v a  2s .  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;//w ww  .j a  v a 2 s. 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);
    }
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET//from  ww  w .  j a v  a 2 s .  c  o m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}

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

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

            if (sb.length() > 0) {
                sb.append(", ");
            }/*  w  ww. jav  a2s  .c o m*/

            sb.append(long1);
        }
    }
    Printer printer = null;
    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";
    int numeroZipEntries = 0;

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

    String fileName = "Pagamenti.zip";

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        Operatore operatore = this.darsService.getOperatoreByPrincipal(bd);
        ProfiloOperatore profilo = operatore.getProfilo();
        boolean isAdmin = profilo.equals(ProfiloOperatore.ADMIN);

        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = estrattiContoBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = idsToExport;

        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 && estrattiContoBD.count(filter) > 0;
            }
        }

        if (eseguiRicerca) {
            Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
            Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? estrattiContoBD.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();
            }

            for (Long idSingoloVersamento : idsToExport) {
                SingoloVersamento singoloVersamento = singoliVersamentiBD
                        .getSingoloVersamento(idSingoloVersamento);
                Versamento versamento = singoloVersamento.getVersamento(bd);

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

                // Aggrego i versamenti per dominio per generare gli estratti conto
                List<Long> idSingoliVersamentiDominio = null;
                if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                    idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
                } else {
                    idSingoliVersamentiDominio = new ArrayList<Long>();
                    mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio);
                    mappaInputDomini.put(dominio.getCodDominio(), dominio);
                }
                idSingoliVersamentiDominio.add(idSingoloVersamento);
            }

            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            for (String codDominio : mappaInputEstrattoConto.keySet()) {
                it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                        .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio),
                                mappaInputEstrattoConto.get(codDominio));
                listInputEstrattoConto.add(input);
            }

            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(
                    bd);
            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(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + 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:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download.//  w  w  w  .jav a 2s .  c o m
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.pagamenti.ReportisticaPagamentiHandler.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.j a v  a 2 s.co  m

            sb.append(long1);
        }
    }
    Printer printer = null;
    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);
    }

    int numeroZipEntries = 0;

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

    String fileName = "Pagamenti.zip";

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        //         Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); 

        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = estrattiContoBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = idsToExport;

        //         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 && estrattiContoBD.count(filter) > 0;
        //            }
        //         }

        if (eseguiRicerca) {
            Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
            Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? estrattiContoBD.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();
            }

            for (Long idSingoloVersamento : idsToExport) {
                SingoloVersamento singoloVersamento = singoliVersamentiBD
                        .getSingoloVersamento(idSingoloVersamento);
                Versamento versamento = singoloVersamento.getVersamento(bd);

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

                // Aggrego i versamenti per dominio per generare gli estratti conto
                List<Long> idSingoliVersamentiDominio = null;
                if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                    idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
                } else {
                    idSingoliVersamentiDominio = new ArrayList<Long>();
                    mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio);
                    mappaInputDomini.put(dominio.getCodDominio(), dominio);
                }
                idSingoliVersamentiDominio.add(idSingoloVersamento);
            }

            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            for (String codDominio : mappaInputEstrattoConto.keySet()) {
                it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                        .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio),
                                mappaInputEstrattoConto.get(codDominio));
                listInputEstrattoConto.add(input);
            }

            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(
                    bd);
            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(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + 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:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * /*from   w ww . ja v a2  s  . c  o  m*/
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:com.smartbear.collaborator.issue.IssueRest.java

/**
 * Downloads raw files from Fisheye, calculates checksum for each file and
 * puts them to zip file/*from   w  w  w .  j  a  v a 2  s  .  c  om*/
 * 
 * @param changesetList 
 * @return
 * @throws Exception
 */
private java.io.File downloadRawFilesFromFisheye(List<Changeset> changesetList) throws Exception {
    // Create temp zip file where versions will be put
    java.io.File targetZipFile = java.io.File.createTempFile("store-", ".zip");
    String urlGetRawFileContent = null;
    byte[] fileBytes = null;
    try {

        FileOutputStream fileOutputStream = new FileOutputStream(targetZipFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
        HashSet<String> zipEntryNames = new HashSet<String>();

        Client client;
        WebResource service;
        ClientResponse response;
        InputStream fileInputStream;

        ZipEntry zipEntry;
        Action action;

        // Go through repositories->commits->files to put versions in temp
        // zip file
        for (Changeset changeset : changesetList) {

            for (File file : changeset.getFiles()) {

                // Get raw file content from Fisheye server
                // Example
                // http://nb-kpl:8060/browse/~raw,r=HEAD/svn_test/test/log.txt

                action = Util.getVersionAction(file.getChangeType());
                if (action == null) {
                    continue;
                }

                if (action == Action.DELETED) {
                    fileBytes = new byte[0];
                } else {
                    urlGetRawFileContent = Util.encodeURL(configModel.getFisheyeUrl() + file.getContentLink());
                    response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false);

                    fileInputStream = response.getEntity(InputStream.class);
                    fileBytes = IOUtils.toByteArray(fileInputStream);

                    LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent);
                    LOGGER.debug("Response from Fisheye" + new String(fileBytes));

                    //Check that we really received file content
                    checkRawFileResponse(response);
                }
                // Set calculated md5 for raw version
                file.setMd5(calculateMd5(fileBytes));

                if (!zipEntryNames.contains(file.getMd5())) {
                    zipEntry = new ZipEntry(file.getMd5());
                    zipOutputStream.putNextEntry(zipEntry);

                    // write version to temp zip file
                    zipOutputStream.write(fileBytes);

                    zipEntryNames.add(file.getMd5());
                }

                // Check if file was modified/deleted then download also
                // previous version
                if (action == Action.MODIFIED || action == Action.DELETED) {

                    if (!Util.isEmpty(file.getAncestor())) {

                        ClientResponse ancestorChangesetResp = getFisheyeClientResponse(
                                Util.encodeURL(configModel.getFisheyeUrl() + FISHEYE_CHANGESET_API
                                        + changeset.getRepositoryName() + "/" + file.getAncestor()),
                                configModel, true);
                        String ancestorChangesetRespString = ancestorChangesetResp.getEntity(String.class);
                        ObjectNode ancestorChangesetNode = (ObjectNode) mapper
                                .readTree(ancestorChangesetRespString);
                        file.setPreviousCommitAuthor(ancestorChangesetNode.get("author").asText());
                        file.setPreviousCommitDate(new Date(ancestorChangesetNode.get("date").asLong()));
                        file.setPreviousCommitComment(ancestorChangesetNode.get("comment").asText());

                        urlGetRawFileContent = Util
                                .encodeURL(configModel.getFisheyeUrl() + "/browse/~raw,r=" + file.getAncestor()
                                        + "/" + changeset.getRepositoryName() + "/" + file.getPath());
                        response = getFisheyeClientResponse(urlGetRawFileContent, configModel, false);

                        fileInputStream = response.getEntity(InputStream.class);
                        fileBytes = IOUtils.toByteArray(fileInputStream);

                        LOGGER.debug("Request to Fisheye: " + urlGetRawFileContent);
                        LOGGER.debug("Response from Fisheye" + new String(fileBytes));

                        //Check that we really received file content
                        checkRawFileResponse(response);

                        // Set calculated md5 for raw version
                        file.setPreviousMd5(calculateMd5(fileBytes));

                        if (!zipEntryNames.contains(file.getPreviousMd5())) {
                            zipEntry = new ZipEntry(file.getPreviousMd5());
                            zipOutputStream.putNextEntry(zipEntry);

                            // write version to temp zip file
                            zipOutputStream.write(fileBytes);

                            zipEntryNames.add(file.getPreviousMd5());
                        }

                    } else {
                        String errorMsg = "Please, try to \"Create/Update Review\" a little bit later. FishEye server hasn't been refreshed commit info yet.";
                        LOGGER.error(errorMsg);
                        throw new Exception(errorMsg);
                    }
                }
            }
        }

        // close ZipEntry to store the stream to the file
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileOutputStream.close();
        return targetZipFile;

    } catch (Exception e) {
        LOGGER.error("Request URL to Fisheye: " + urlGetRawFileContent, e);
        LOGGER.error("Response from Fisheye: " + (fileBytes != null ? new String(fileBytes) : ""), e);
        throw new Exception(
                "Can't download raw versions from FishEye server. Check that FishEye server is running. \n "
                        + "Request URL to Fisheye: " + urlGetRawFileContent + "\n" + e.getMessage());
    }

}