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:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private void zipMultipleFiles(HttpServletRequest req, HttpServletResponse res, VDCUser user, VDC vdc,
        UserGroup ipUserGroup) {//  ww w . ja  v a  2  s  .  com
    // a request for a zip-packaged multiple file archive.

    String fileId = req.getParameter("fileId");
    String studyId = req.getParameter("studyId");
    String versionNumber = req.getParameter("versionNumber");
    System.out.print("zip multiple files version number" + versionNumber);
    Study study = null;
    Collection files = new ArrayList();
    boolean createDirectoriesForCategories = false;

    String fileManifest = "";

    String sessionId = null;
    javax.servlet.http.Cookie cookies[] = req.getCookies();

    for (int i = 0; i < cookies.length; i++) {
        if ("JSESSIONID".equals(cookies[i].getName())) {
            sessionId = cookies[i].getValue();
        }
    }

    if (sessionId == null || "".equals(sessionId)) {
        // if there's no JSESSIONID, we'll use the vdcSession id, for 
        // logging the download counts: 
        String[] stringArray = vdcSession.toString().toString().split("@");
        sessionId = stringArray[1];
    }

    if (fileId != null) {
        String[] idTokens = fileId.split(",");

        for (String tok : idTokens) {
            StudyFile sf;
            try {
                sf = studyFileService.getStudyFile(new Long(tok));
                files.add(sf);
            } catch (Exception ex) {
                fileManifest = fileManifest + tok + " DOES NOT APPEAR TO BE A VALID FILE ID;\r\n";
            }
        }
    } else if (studyId != null) {
        try {
            study = studyService.getStudy(new Long(studyId));
            files = study.getStudyFiles();
            createDirectoriesForCategories = true;
        } catch (Exception ex) {
            if (ex.getCause() instanceof IllegalArgumentException) {
                createErrorResponse404(res);
                return;
            }
        }
    } else {
        createErrorResponse404(res);
        return;
    }

    // check for restricted files
    Iterator iter = files.iterator();
    while (iter.hasNext()) {
        StudyFile file = (StudyFile) iter.next();
        if (file.isFileRestrictedForUser(user, ipUserGroup)) {
            fileManifest = fileManifest + file.getFileName() + " IS RESTRICTED AND CANNOT BE DOWNLOADED\r\n";
            iter.remove();
        }
    }

    if (files.size() == 0) {
        createErrorResponse403(res);
        return;
    }

    Long sizeLimit = Long.valueOf(104857600);
    // that's the default of 100 MB.

    Long sizeTotal = Long.valueOf(0);

    // this is the total limit of the size of all the files we
    // are packaging. if exceeded, we stop packaging files and add
    // a note to the manifest explaining what happened.
    // the value above is the default. a different value can
    // be set with a JVM option.

    String sizeLimitOption = System.getProperty("dvn.batchdownload.limit");

    if (sizeLimitOption != null) {
        Long sizeOptionValue = new Long(sizeLimitOption);
        if (sizeOptionValue > 0) {
            sizeLimit = sizeOptionValue;
        }
    }

    FileDownloadObject remoteDownload = null;

    // now create zip stream
    try {
        // set content type:
        res.setContentType("application/zip");

        // create zipped output stream:

        OutputStream out = res.getOutputStream();
        ZipOutputStream zout = new ZipOutputStream(out);

        List nameList = new ArrayList(); // used to check for duplicates
        List successList = new ArrayList();

        iter = files.iterator();

        while (iter.hasNext()) {
            int fileSize = 0;
            StudyFile file = (StudyFile) iter.next();

            if (sizeTotal < sizeLimit) {
                InputStream in = null;

                String varHeaderLine = null;
                String dbContentType = file.getFileType();

                if (dbContentType != null && dbContentType.equals("text/tab-separated-values")
                        && file.isSubsettable()) {
                    List datavariables = ((TabularDataFile) file).getDataTable().getDataVariables();
                    varHeaderLine = generateVariableHeader(datavariables);
                }

                if (dbContentType == null) {
                    dbContentType = "unknown filetype;";
                }

                Boolean Success = true;

                if (file.isRemote()) {

                    // do the http magic;
                    // remote files may be subject to complex authentication and
                    // authorization.
                    // And for that we have a special method...

                    remoteDownload = initiateRemoteDownload(file, req);

                    if (remoteDownload.getStatus() != 200) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        if (remoteDownload.getInputStream() != null) {
                            remoteDownload.getInputStream().close();
                        }

                        remoteDownload.releaseConnection();

                        Success = false;
                    } else {
                        in = remoteDownload.getInputStream();
                    }
                } else {
                    in = getLocalFileAsStream(file);
                    if (in == null) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        Success = false;
                    }
                }

                if (Success) {
                    // String zipEntryName = file.getFileName();

                    // get file name and category according to study version number chosen by user 

                    Long versionNum = null;
                    if (versionNumber != null)
                        versionNum = Long.valueOf(versionNumber).longValue();
                    String zipEntryName = file.getFileName(versionNum);

                    zipEntryName = checkZipEntryName(zipEntryName, nameList);

                    // ZipEntry e = new ZipEntry(zipEntryName);

                    String zipEntryDirectoryName = file.getCategory(versionNum);
                    ZipEntry e = new ZipEntry(zipEntryDirectoryName + "/" + zipEntryName);

                    zout.putNextEntry(e);

                    if (varHeaderLine != null) {
                        byte[] headerBuffer = varHeaderLine.getBytes();
                        zout.write(headerBuffer);
                        fileSize += (headerBuffer.length);
                    }

                    byte[] dataBuffer = new byte[8192];

                    int i = 0;
                    while ((i = in.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, i);
                        fileSize += i;
                        out.flush();
                    }
                    in.close();
                    zout.closeEntry();

                    if (dbContentType == null) {
                        dbContentType = "unknown filetype;";
                    }

                    fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") " + fileSize
                            + " bytes.\r\n";

                    if (fileSize > 0) {
                        successList.add(file.getId());
                        sizeTotal += Long.valueOf(fileSize);
                    }

                    // if this was a remote stream, let's close
                    // the connection properly:

                    if (remoteDownload != null) {
                        remoteDownload.releaseConnection();
                    }
                }
            } else {
                fileManifest = fileManifest + file.getFileName()
                        + " skipped because the total size of the download bundle exceeded the limit of "
                        + sizeLimit + " bytes.\r\n";
            }
        }

        // finally, let's create the manifest entry:

        ZipEntry e = new ZipEntry("MANIFEST.TXT");

        zout.putNextEntry(e);
        zout.write(fileManifest.getBytes());
        zout.closeEntry();

        zout.close();

        // and finally finally, we can now increment the download
        // counts on all the files successfully zipped:

        Iterator it = successList.iterator();
        while (it.hasNext()) {
            Long fid = (Long) it.next();
            StudyFile file = studyFileService.getStudyFile(new Long(fid));
            Long versionNum = null;
            if (versionNumber != null)
                versionNum = Long.valueOf(versionNumber).longValue();
            System.out.print("versionNumber " + versionNumber);
            StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNum);
            GuestBookResponse guestbookResponse = (GuestBookResponse) vdcSession.getGuestbookResponseMap()
                    .get("guestBookResponse_" + file.getStudy().getId());
            if (guestbookResponse == null) {
                //need to set up dummy network response
                guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(file.getStudy(),
                        file, vdcSession.getLoginBean());
            }
            guestbookResponse.setStudyVersion(sv);
            guestbookResponse.setSessionId(sessionId);

            String friendlyFormatType = FileUtil.getUserFriendlyTypeForMime(file.getFileType());

            guestbookResponse.setDownloadtype("File Download (as Zip archive) - " + friendlyFormatType);

            if (vdc != null) {
                studyService.incrementNumberOfDownloads(fid, vdc.getId(),
                        (GuestBookResponse) guestbookResponse);
            } else {
                studyService.incrementNumberOfDownloads(fid, (Long) null,
                        (GuestBookResponse) guestbookResponse);
            }
        }

    } catch (IOException ex) {
        // if we caught an exception *here*, it means something
        // catastrophic has happened while packaging the zip archive
        // itself (I/O errors on individual files would be caught
        // above); so there's not much we can do except print a
        // generic error message:

        String errorMessage = "An unknown I/O error has occured while generating a Zip archive of multiple data files. Unfortunately, no further diagnostic information on the nature of the problem is avaiable to the Application at this point. It is possible that the problem was caused by a temporary network error. Please try again later and if the problem persists, report it to your DVN technical support contact.";
        createErrorResponse403(res);

        if (remoteDownload != null) {
            remoteDownload.releaseConnection();
        }
    }
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

/**
 * Serialize the document into a new entry of an ZipOutputStream in XML format. All XObjects and attachments are
 * included. Rendered content is excluded.
 * //w  w  w  .j av a2  s  .  c  o m
 * @param zos the ZipOutputStream to write to
 * @param zipname the name of the new entry to create
 * @param withVersions if true, also include archived version of the document
 * @param context current XWikiContext
 * @throws XWikiException when an error occurs during xwiki operations
 * @throws IOException when an error occurs during streaming operations
 * @since 2.3M2
 */
public void addToZip(ZipOutputStream zos, String zipname, boolean withVersions, XWikiContext context)
        throws XWikiException, IOException {
    ZipEntry zipentry = new ZipEntry(zipname);
    zos.putNextEntry(zipentry);
    toXML(zos, true, false, true, withVersions, context);
    zos.closeEntry();
}

From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.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 w w. jav a 2s  .co  m*/

            sb.append(long1);
        }
    }

    Printer printer = null;
    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);
        VersamentiBD versamentiBD = new VersamentiBD(bd);
        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);

        Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
        Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();

        VersamentoFilter filter = versamentiBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdVersamento(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 = versamentiBD.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.Versamento.model().DATA_ORA_ULTIMO_AGGIORNAMENTO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Versamento> findAll = versamentiBD.findAll(filter);

        for (Versamento versamento : findAll) {

            // 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> idVersamentiDominio = null;
            if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                idVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
            } else {
                idVersamentiDominio = new ArrayList<Long>();
                mappaInputEstrattoConto.put(dominio.getCodDominio(), idVersamentiDominio);
                mappaInputDomini.put(dominio.getCodDominio(), dominio);
            }
            idVersamentiDominio.add(versamento.getId());
        }

        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
                    .creaEstrattoContoVersamentiPDF(mappaInputDomini.get(codDominio),
                            mappaInputEstrattoConto.get(codDominio));
            listInputEstrattoConto.add(input);
        }

        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
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter ecFilter = estrattiContoBD.newFilter();
        ecFilter.setIdVersamento(idsToExport);
        List<EstrattoConto> findAllEstrattoConto = estrattiContoBD.estrattoContoFromIdVersamenti(ecFilter);

        if (findAllEstrattoConto != null && findAllEstrattoConto.size() > 0) {
            //ordinamento record
            Collections.sort(findAllEstrattoConto, 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 : findAllEstrattoConto) {
                    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:it.govpay.web.rs.dars.monitoraggio.pagamenti.PagamentiHandler.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   w  w w .j  a  v  a2s. c o  m*/
    int numeroZipEntries = 0;
    boolean esportaCsv = false, esportaPdf = false, esportaRtPdf = false, esportaRtBase64 = false;

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

        String esportaCsvId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaCsv.id");
        String esportaCsvS = Utils.getValue(rawValues, esportaCsvId);
        if (StringUtils.isNotEmpty(esportaCsvS)) {
            esportaCsv = Boolean.parseBoolean(esportaCsvS);
        }

        String esportaPdfId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaPdf.id");
        String esportaPdfS = Utils.getValue(rawValues, esportaPdfId);
        if (StringUtils.isNotEmpty(esportaPdfS)) {
            esportaPdf = Boolean.parseBoolean(esportaPdfS);
        }

        String esportaRtPdfId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtPdf.id");
        String esportaRtPdfS = Utils.getValue(rawValues, esportaRtPdfId);
        if (StringUtils.isNotEmpty(esportaRtPdfS)) {
            esportaRtPdf = Boolean.parseBoolean(esportaRtPdfS);
        }

        String esportaRtBase64Id = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtBase64.id");
        String esportaRtBase64S = Utils.getValue(rawValues, esportaRtBase64Id);
        if (StringUtils.isNotEmpty(esportaRtBase64S)) {
            esportaRtBase64 = Boolean.parseBoolean(esportaRtBase64S);
        }

        // almeno una voce deve essere selezionata
        if (!(esportaCsv || esportaPdf || esportaRtPdf || esportaRtBase64)) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.tipiExportObbligatori"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

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

        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);
        PagamentiBD pagamentiBD = new PagamentiBD(bd);
        PagamentoFilter filter = pagamentiBD.newFilter();
        filter.setSogliaRitardo(ConsoleProperties.getInstance().getSogliaGiorniRitardoPagamenti());

        List<String> idDomini = new ArrayList<String>();
        List<Long> idsToExport = new ArrayList<Long>();
        idsToExport.add(idToExport);

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

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

        if (eseguiRicerca) {
            Pagamento pagamento = pagamentiBD.getPagamento(idToExport);

            if (esportaRtPdf || esportaRtBase64) {
                // ricevuta pagamento
                try {
                    Rpt rpt = pagamento.getRpt(bd);
                    Dominio dominio = pagamento.getDominio(bd);

                    if (rpt.getXmlRt() != null) {
                        String ricevutaFileName = dominio.getCodDominio() + "_" + pagamento.getIuv() + "_"
                                + pagamento.getIur();

                        if (esportaRtPdf) {
                            Versamento versamento = rpt.getVersamento(bd);
                            // RT in formato pdf
                            String tipoFirma = rpt.getFirmaRichiesta().getCodifica();
                            byte[] rtByteValidato = RtUtils.validaFirma(tipoFirma, rpt.getXmlRt(),
                                    dominio.getCodDominio());
                            CtRicevutaTelematica rt = JaxbUtils.toRT(rtByteValidato);
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            String auxDigit = dominio.getAuxDigit() + "";
                            String applicationCode = String.format("%02d",
                                    dominio.getStazione(bd).getApplicationCode());
                            RicevutaPagamentoUtils.getPdfRicevutaPagamento(dominio.getLogo(),
                                    versamento.getCausaleVersamento(), rt, pagamento, auxDigit, applicationCode,
                                    baos, this.log);
                            String rtPdfEntryName = ricevutaFileName + ".pdf";
                            numeroZipEntries++;
                            ZipEntry rtPdf = new ZipEntry(rtPdfEntryName);
                            zout.putNextEntry(rtPdf);
                            zout.write(baos.toByteArray());
                            zout.closeEntry();
                        }

                        if (esportaRtBase64) {
                            // RT in formato Base 64
                            String rtBase64EntryName = ricevutaFileName + ".txt";
                            numeroZipEntries++;
                            ZipEntry rtPdf = new ZipEntry(rtBase64EntryName);
                            zout.putNextEntry(rtPdf);
                            zout.write(rpt.getXmlRt());
                            zout.closeEntry();
                        }
                    }
                } catch (Exception e) {
                }
            }

            List<Long> ids = new ArrayList<Long>();
            if (pagamento.getIdSingoloVersamento() != null)
                ids.add(pagamento.getIdSingoloVersamento());

            SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
            EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
            EstrattoContoFilter ecFilter = estrattiContoBD.newFilter();

            if (esportaCsv) {
                // recupero oggetto
                ecFilter.setIdSingoloVersamento(ids);
                List<EstrattoConto> findAll = eseguiRicerca
                        ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(ecFilter)
                        : 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 eConto : findAll) {
                            printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(eConto, 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();
                }
            }
            if (esportaPdf) {
                SingoloVersamento singoloVersamento = singoliVersamentiBD
                        .getSingoloVersamento(pagamento.getIdSingoloVersamento());
                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);
                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:lu.fisch.unimozer.Diagram.java

private void addToZip(ZipOutputStream zo, String baseDir, File directory)
        throws FileNotFoundException, IOException {
    // get all files
    File[] files = directory.listFiles();
    for (int f = 0; f < files.length; f++) {
        if (files[f].isDirectory()) {
            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            addToZip(zo, baseDir + entry + "/", files[f]);
        } else {/*  w  w w .  j av a 2s .  com*/
            //System.out.println("File = "+files[f].getAbsolutePath());
            //System.out.println("List = "+Arraysv.deepToString(excludeExtention));
            //System.out.println("We got = "+getExtension(files[f]));
            FileInputStream bi = new FileInputStream(files[f]);

            String entry = files[f].getAbsolutePath();
            entry = entry.substring(directory.getAbsolutePath().length() + 1);
            entry = baseDir + entry;
            ZipEntry ze = new ZipEntry(entry);
            zo.putNextEntry(ze);
            byte[] buf = new byte[1024];
            int anz;
            while ((anz = bi.read(buf)) != -1) {
                zo.write(buf, 0, anz);
            }
            zo.closeEntry();
            bi.close();
        }
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public InputStream dumpContentStore(WGDatabase dbSource, String filterExpression, boolean autoCorrect,
        Logger log, boolean includeACL, boolean includeSystemAreas, boolean includeArchived)
        throws WGAPIException, IOException {

    log.info("Creating dump database");

    // Create working folder for dump database
    File dir = File.createTempFile("csd", ".tmp", WGFactory.getTempDir());
    dir.delete();//from  ww  w  .  j  av  a  2s  .  co  m
    dir.mkdir();

    // Create dump database
    Map<String, String> options = new HashMap<String, String>();
    options.put(WGDatabase.COPTION_MONITORLASTCHANGE, "false");
    options.put(WGDatabaseImpl.COPTION_DISTINCTFILECONTENTS, "false");
    WGDatabase dbTarget = WGFactory.getInstance().openDatabase(null,
            de.innovationgate.webgate.api.hsql.WGDatabaseImpl.class.getName(), dir.getAbsolutePath() + "/wgacs",
            "sa", null, options);
    dbTarget.setDbReference("Temporary WGACS dump target");

    // Replicate
    log.info("Synchronizing data to dump database");
    dbSource.lock();
    try {
        ContentStoreDumpManager importer = new ContentStoreDumpManager(dbSource, dbTarget, log);
        importer.exportDump(includeACL, includeSystemAreas, includeArchived);
    } finally {
        dbSource.unlock();
    }

    // Close database and zip up its contents
    log.info("Creating dump file");
    dbTarget.close();
    File zipFile = File.createTempFile("csz", ".tmp", WGFactory.getTempDir());
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    out.setLevel(9);
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        out.putNextEntry(new ZipEntry(file.getName()));
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        WGUtils.inToOut(in, out, 2048);
        in.close();
        out.closeEntry();
    }
    out.close();

    // Delete temp dir
    WGUtils.delTree(dir);

    // Return input stream for zip file
    return new TempFileInputStream(zipFile);

}

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

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {

    Printer printer = null;//ww w.j a v  a2  s .c o m
    String methodName = "exportMassivo " + this.titoloServizio;

    int numeroZipEntries = 0;

    boolean esportaCsv = false, esportaPdf = false, esportaRtPdf = false, esportaRtBase64 = false;

    String fileName = "Pagamenti.zip";
    try {
        String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
        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);

        PagamentiBD pagamentiBD = new PagamentiBD(bd);
        PagamentoFilter filter = pagamentiBD.newFilter(simpleSearch);
        Map<String, String> params = new HashMap<String, String>();

        String esportaCsvId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaCsv.id");
        String esportaCsvS = Utils.getValue(rawValues, esportaCsvId);
        if (StringUtils.isNotEmpty(esportaCsvS)) {
            esportaCsv = Boolean.parseBoolean(esportaCsvS);
        }

        String esportaPdfId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaPdf.id");
        String esportaPdfS = Utils.getValue(rawValues, esportaPdfId);
        if (StringUtils.isNotEmpty(esportaPdfS)) {
            esportaPdf = Boolean.parseBoolean(esportaPdfS);
        }

        String esportaRtPdfId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtPdf.id");
        String esportaRtPdfS = Utils.getValue(rawValues, esportaRtPdfId);
        if (StringUtils.isNotEmpty(esportaRtPdfS)) {
            esportaRtPdf = Boolean.parseBoolean(esportaRtPdfS);
        }

        String esportaRtBase64Id = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esportaRtBase64.id");
        String esportaRtBase64S = Utils.getValue(rawValues, esportaRtBase64Id);
        if (StringUtils.isNotEmpty(esportaRtBase64S)) {
            esportaRtBase64 = Boolean.parseBoolean(esportaRtBase64S);
        }

        // almeno una voce deve essere selezionata
        if (!(esportaCsv || esportaPdf || esportaRtPdf || esportaRtBase64)) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.tipiExportObbligatori"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

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

        //1. eseguo una count per verificare che il numero dei risultati da esportare sia <= sogliamassimaexport massivo
        boolean eseguiRicerca = this.popolaFiltroPagamenti(rawValues, uriInfo, pagamentiBD, params,
                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 = pagamentiBD.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 (esportaRtPdf && 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);
        }

        FilterSortWrapper fsw = new FilterSortWrapper();
        fsw.setField(it.govpay.orm.Pagamento.model().DATA_PAGAMENTO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);
        List<Pagamento> findAllPag = new ArrayList<Pagamento>();

        int countIterazione = -1;
        int offset = 0;

        // esecuzione della ricerca di tutti i pagamenti paginata per problemi di performance, nel caso di esporta rt pdf c'e' il limit impostato e si fa solo un ciclo
        do {
            filter.setOffset(offset);
            filter.setLimit(limit);
            List<Pagamento> findAllPagTmp = pagamentiBD.findAll(filter);
            countIterazione = findAllPagTmp != null ? findAllPagTmp.size() : 0;
            offset += countIterazione;

            if (findAllPagTmp != null && findAllPagTmp.size() > 0)
                findAllPag.addAll(findAllPagTmp);

        } while (countIterazione > 0 && !esportaRtPdf);

        List<Long> ids = new ArrayList<Long>();
        for (Pagamento pagamento : findAllPag) {
            if (pagamento.getIdSingoloVersamento() != null)
                ids.add(pagamento.getIdSingoloVersamento());

            if (esportaRtPdf || esportaRtBase64) {
                // ricevuta pagamento
                try {
                    Rpt rpt = pagamento.getRpt(bd);
                    Dominio dominio = pagamento.getDominio(bd);

                    if (rpt.getXmlRt() != null) {
                        numeroZipEntries++;
                        String ricevutaFileName = dominio.getCodDominio() + "_" + pagamento.getIuv() + "_"
                                + pagamento.getIur();
                        if (esportaRtPdf) {
                            Versamento versamento = rpt.getVersamento(bd);
                            // RT in formato pdf
                            String tipoFirma = rpt.getFirmaRichiesta().getCodifica();
                            byte[] rtByteValidato = RtUtils.validaFirma(tipoFirma, rpt.getXmlRt(),
                                    dominio.getCodDominio());
                            CtRicevutaTelematica rt = JaxbUtils.toRT(rtByteValidato);
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            String auxDigit = dominio.getAuxDigit() + "";
                            String applicationCode = String.format("%02d",
                                    dominio.getStazione(bd).getApplicationCode());
                            RicevutaPagamentoUtils.getPdfRicevutaPagamento(dominio.getLogo(),
                                    versamento.getCausaleVersamento(), rt, pagamento, auxDigit, applicationCode,
                                    baos, this.log);
                            String rtPdfEntryName = ricevutaFileName + ".pdf";
                            numeroZipEntries++;
                            ZipEntry rtPdf = new ZipEntry(rtPdfEntryName);
                            zout.putNextEntry(rtPdf);
                            zout.write(baos.toByteArray());
                            zout.closeEntry();
                        }

                        if (esportaRtBase64) {
                            // RT in formato Base 64
                            String rtBase64EntryName = ricevutaFileName + ".txt";
                            numeroZipEntries++;
                            ZipEntry rtPdf = new ZipEntry(rtBase64EntryName);
                            zout.putNextEntry(rtPdf);
                            zout.write(rpt.getXmlRt());
                            zout.closeEntry();
                        }
                    }
                } catch (Exception e) {
                }
            }
        }

        if (esportaCsv) {
            EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
            EstrattoContoFilter ecFilter = estrattiContoBD.newFilter();

            // recupero oggetto
            ecFilter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(ecFilter)
                    : 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();
            }
        }

        if (esportaPdf) {
            Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();
            Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
            SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
            for (Long idSingoloVersamento : ids) {
                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);
            }

            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 (ExportException e) {
        throw e;
    } catch (Exception e) {
        this.log.error(e.getMessage(), e);
        throw new ConsoleException(e);
    }

}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {/*from   w w  w  .  ja  va2 s.  co m*/
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }//from   ww  w  .j  a  v a  2  s  . co m

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}