Example usage for java.util.zip ZipOutputStream write

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.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 + "]";

    try {// w  w w  . jav  a  2s. c  om
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        DominiBD dominiBD = new DominiBD(bd);

        Dominio dominio = dominiBD.getDominio(idToExport);
        String fileName = "Dominio_" + dominio.getCodDominio() + ".zip";

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

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

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

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

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

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

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

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

/**
 * ??/*from   w  ww.j av  a 2  s. co m*/
 * 
 * @param sep "\t" / ","
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 * @param chaset "UTF-8" / "MS932"
 * @param enc "utf8" / "sjis"
 * @param ext "txt" / "csv"
 */
void storeText(String sep, String name, String suffix, String chaset, String enc, String ext) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_" + enc + "." + ext);
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = sep.getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

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

                Zip zip = Zip.fromJson(json);
                zos.write(zip.getCode().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getX0402().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorp().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd1Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getAdd2Yomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getCorpYomi().getBytes(chaset));
                zos.write(tab);
                zos.write(zip.getNote().getBytes(chaset));
                zos.write(crlf);
                ++cnt;
            }
        }

        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_" + enc + "_" + ext + ".zip");
        log.info("count: " + cnt);

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

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

public void storeX0401Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<Pref> prefs = getPrefs();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml");

    tsv.setTime(timestamp);/*  w  w w  . ja  va2s .  c  o m*/
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF)
                    .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (Pref pref : prefs) {

            out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF)
                    .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (Pref pref : prefs) {

            jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi")
                    .value(pref.getYomi()).endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0401s");

        for (Pref pref : prefs) {

            xwriter.writeStartElement("x0401");
            xwriter.writeAttribute("code", pref.getCode());
            xwriter.writeAttribute("name", pref.getName());
            xwriter.writeAttribute("yomi", pref.getYomi());
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0401.zip");
        log.info("prefs: " + prefs.size());

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

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

public void storeX0402Zip() {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ZipOutputStream out = new ZipOutputStream(baos);
    Collection<City> cities = getCities();
    ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt");
    ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv");
    ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json");
    ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml");

    tsv.setTime(timestamp);//from w  w w  .  j av a 2 s  .  c om
    csv.setTime(timestamp);
    json.setTime(timestamp);
    xml.setTime(timestamp);

    try {

        out.putNextEntry(tsv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t"
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("UTF-8"));
        }

        out.closeEntry();
        out.putNextEntry(csv);

        for (City city : cities) {

            out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + ","
                    + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF)
                            .getBytes("MS932"));
        }

        out.closeEntry();
        out.putNextEntry(json);

        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
        JSONWriter jwriter = new JSONWriter(writer);

        jwriter.array();

        for (City city : cities) {

            jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi")
                    .value(city.getYomi()).key("expired")
                    .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false")
                    .endObject();
        }

        jwriter.endArray();
        writer.flush();
        out.closeEntry();
        out.putNextEntry(xml);

        XMLStreamWriter xwriter = XMLOutputFactory.newInstance()
                .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8"));

        xwriter.writeStartDocument("UTF-8", "1.0");
        xwriter.writeStartElement("x0402s");

        for (City city : cities) {

            xwriter.writeStartElement("x0402");
            xwriter.writeAttribute("code", city.getCode());
            xwriter.writeAttribute("name", city.getName());
            xwriter.writeAttribute("yomi", city.getYomi());
            xwriter.writeAttribute("expired",
                    (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false");
            xwriter.writeEndElement();
        }

        xwriter.writeEndElement();
        xwriter.writeEndDocument();
        xwriter.flush();
        out.closeEntry();
        out.finish();
        baos.flush();
        getRawDao().store(baos.toByteArray(), "x0402.zip");
        log.info("cities: " + cities.size());

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

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//w  ww  . j  av  a  2 s .  c  o m
 * 
 * @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());
    }

}

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

/**
 * IME??/*from  ww  w  .j a  v a2s.  c o m*/
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeIme(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    SortedMap<String, Pref> prefs = getPrefMap();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(
            FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_ime_dic.txt");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        byte[] tab = "\t".getBytes("MS932");
        byte[] sonota = "\t?????".getBytes("MS932");
        byte[] crlf = CRLF.getBytes("MS932");

        zos.putNextEntry(entry);

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            String prefName = prefs.get(city.getCode().substring(0, 2)).getName();
            String cityName = city.getName();

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

                Zip zip = Zip.fromJson(json);
                zos.write(ZenHanHelper.convertZipHankakuZenkaku(zip.getCode()).getBytes("MS932"));
                zos.write(tab);
                zos.write(prefName.getBytes("MS932"));
                zos.write(cityName.getBytes("MS932"));
                zos.write(zip.getAdd1().getBytes("MS932"));
                zos.write(zip.getAdd2().getBytes("MS932"));
                zos.write(zip.getCorp().getBytes("MS932"));
                zos.write(sonota);
                zos.write(crlf);
                ++cnt;
            }
        }

        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_ime_dic.zip");
        log.info("count: " + cnt);

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

From source file:it.govpay.web.rs.dars.monitoraggio.incassi.IncassiHandler.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 + "]";

    try {/*ww  w . j  a v  a 2  s  .co  m*/
        int numeroZipEntries = 0;
        this.log.info("Esecuzione " + methodName + " in corso...");
        Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita);
        boolean eseguiRicerca = !setDomini.isEmpty();
        List<String> idDomini = new ArrayList<String>();
        IncassiBD incassiBD = new IncassiBD(bd);
        IncassoFilter filter = incassiBD.newFilter();

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

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

        if (eseguiRicerca) {
            filter.setIdIncasso(ids);
            eseguiRicerca = eseguiRicerca && incassiBD.count(filter) > 0;
        }

        Incasso incasso = eseguiRicerca ? incassiBD.getIncasso(idToExport) : null;
        String fileName = "Export.zip";

        if (incasso != null) {
            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            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);
            IncassoPdf.getPdfIncasso(pathLoghi, incasso, pagamentiList, applicazione, baos, this.log);
            String incassoPdfEntryName = incasso.getTrn() + ".pdf";
            numeroZipEntries++;
            ZipEntry rtPdf = new ZipEntry(incassoPdfEntryName);
            zout.putNextEntry(rtPdf);
            zout.write(baos.toByteArray());
            zout.closeEntry();
        }

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

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

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

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

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Operation for fetching data of type FILE.
 * /*from w w  w . j av a2 s  .  co m*/
 * @param importSource
 * @param identifier
 * @param listOfFormats
 * @return byte[] of the fetched file, zip file if more than one record was
 *         fetched
 * @throws RuntimeException
 * @throws SourceNotAvailableException
 */
private byte[] fetchData(String identifier, Format[] formats)
        throws SourceNotAvailableException, RuntimeException, FormatNotAvailableException {
    byte[] in = null;
    FullTextVO fulltext = new FullTextVO();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {
        // Call fetch file for every given format
        for (int i = 0; i < formats.length; i++) {
            Format format = formats[i];
            fulltext = this.util.getFtObjectToFetch(this.currentSource, format.getName(), format.getType(),
                    format.getEncoding());
            // Replace regex with identifier
            String decoded = java.net.URLDecoder.decode(fulltext.getFtUrl().toString(),
                    this.currentSource.getEncoding());
            fulltext.setFtUrl(new URL(decoded));
            fulltext.setFtUrl(
                    new URL(fulltext.getFtUrl().toString().replaceAll(this.regex, identifier.trim())));
            this.logger.debug("Fetch file from URL: " + fulltext.getFtUrl());

            // escidoc file
            if (this.currentSource.getHarvestProtocol().equalsIgnoreCase("ejb")) {
                in = this.fetchEjbFile(fulltext, identifier);
            }
            // other file
            else {
                in = this.fetchFile(fulltext);
            }

            this.setFileProperties(fulltext);
            // If only one file => return it in fetched format
            if (formats.length == 1) {
                return in;
            }
            // If more than one file => add it to zip
            else {
                // If cone service is not available (we do not get a
                // fileEnding) we have
                // to make sure that the zip entries differ in name.
                String fileName = identifier;
                if (this.getFileEnding().equals("")) {
                    fileName = fileName + "_" + i;
                }
                ZipEntry ze = new ZipEntry(fileName + this.getFileEnding());
                ze.setSize(in.length);
                ze.setTime(this.currentDate());
                CRC32 crc321 = new CRC32();
                crc321.update(in);
                ze.setCrc(crc321.getValue());
                zos.putNextEntry(ze);
                zos.write(in);
                zos.flush();
                zos.closeEntry();
            }
        }
        this.setContentType("application/zip");
        this.setFileEnding(".zip");
        zos.close();

    } catch (SourceNotAvailableException e) {
        this.logger.error("Import Source " + this.currentSource + " not available.", e);
        throw new SourceNotAvailableException(e);
    } catch (FormatNotAvailableException e) {
        throw new FormatNotAvailableException(e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:it.govpay.web.rs.dars.monitoraggio.eventi.EventiHandler.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 2  s .  c  o m

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";
    String fileName = "Eventi.zip";
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Map<String, String> params = new HashMap<String, String>();
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        EventiBD eventiBD = new EventiBD(bd);

        EventiFilter filter = eventiBD.newFilter(simpleSearch);

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

        boolean checkCount = this.popolaFiltroRicerca(rawValues, uriInfo, params, simpleSearch, filter);

        long count = eventiBD.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 (checkCount && 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);
        if (checkCount)
            filter.setLimit(ConsoleProperties.getInstance().getNumeroMassimoElementiExport());

        List<Evento> list = eventiBD.findAll(filter);

        if (list != null && list.size() > 0) {
            this.scriviCSVEventi(baos, list);

            ZipEntry datiEvento = new ZipEntry("eventi.csv");
            zout.putNextEntry(datiEvento);
            zout.write(baos.toByteArray());
            zout.closeEntry();
        } else {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sugli eventi 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:nl.nn.adapterframework.webcontrol.action.BrowseExecute.java

private void exportMessage(IMessageBrowser mb, String id, ReceiverBase receiver,
        ZipOutputStream zipOutputStream) {
    IListener listener = null;/*  w w  w.j  a  v  a 2  s  .  co  m*/
    if (receiver != null) {
        listener = receiver.getListener();
    }
    try {
        Object rawmsg = mb.browseMessage(id);
        IMessageBrowsingIteratorItem msgcontext = mb.getContext(id);
        try {
            String msg = null;
            String msgId = msgcontext.getId();
            String msgMid = msgcontext.getOriginalId();
            String msgCid = msgcontext.getCorrelationId();
            HashMap context = new HashMap();
            if (listener != null) {
                msg = listener.getStringFromRawMessage(rawmsg, context);
            } else {
                msg = (String) rawmsg;
            }
            if (StringUtils.isEmpty(msg)) {
                msg = "<no message found>";
            }
            if (msgId == null) {
                msgId = "";
            }
            if (msgMid == null) {
                msgMid = "";
            }
            if (msgCid == null) {
                msgCid = "";
            }
            String filename = "msg_" + id + "_id[" + msgId.replace(':', '-') + "]" + "_mid["
                    + msgMid.replace(':', '-') + "]" + "_cid[" + msgCid.replace(':', '-') + "]";
            ZipEntry zipEntry = new ZipEntry(filename + ".txt");

            String sentDateString = (String) context.get(IPipeLineSession.tsSentKey);
            if (StringUtils.isNotEmpty(sentDateString)) {
                try {
                    Date sentDate = DateUtils.parseToDate(sentDateString, DateUtils.FORMAT_FULL_GENERIC);
                    zipEntry.setTime(sentDate.getTime());
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not set date for message [" + id + "]", e);
                }
            } else {
                Date insertDate = msgcontext.getInsertDate();
                if (insertDate != null) {
                    zipEntry.setTime(insertDate.getTime());
                }
            }
            //            String comment=msgcontext.getCommentString();
            //            if (StringUtils.isNotEmpty(comment)) {
            //               zipEntry.setComment(comment);
            //            }

            zipOutputStream.putNextEntry(zipEntry);
            String encoding = Misc.DEFAULT_INPUT_STREAM_ENCODING;
            if (msg.startsWith("<?xml")) {
                int lastpos = msg.indexOf("?>");
                if (lastpos > 0) {
                    String prefix = msg.substring(6, lastpos);
                    int encodingStartPos = prefix.indexOf("encoding=\"");
                    if (encodingStartPos > 0) {
                        int encodingEndPos = prefix.indexOf('"', encodingStartPos + 10);
                        if (encodingEndPos > 0) {
                            encoding = prefix.substring(encodingStartPos + 10, encodingEndPos);
                            log.debug("parsed encoding [" + encoding + "] from prefix [" + prefix + "]");
                        }
                    }
                }
            }
            zipOutputStream.write(msg.getBytes(encoding));

            if (listener != null && listener instanceof IBulkDataListener) {
                IBulkDataListener bdl = (IBulkDataListener) listener;
                String bulkfilename = bdl.retrieveBulkData(rawmsg, msg, context);

                zipOutputStream.closeEntry();

                File bulkfile = new File(bulkfilename);

                zipEntry = new ZipEntry(filename + "_" + bulkfile.getName());
                zipEntry.setTime(bulkfile.lastModified());
                zipOutputStream.putNextEntry(zipEntry);
                StreamUtil.copyStream(new FileInputStream(bulkfile), zipOutputStream, 32000);
                bulkfile.delete();
            }
            zipOutputStream.closeEntry();
        } finally {
            msgcontext.release();
        }
    } catch (Throwable e) {
        error(", ", "errors.generic", "Could not export message with id [" + id + "]", e);
    }
}