Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:freenet.client.async.ContainerInserter.java

private String createZipBucket(OutputStream os) throws IOException {
    if (logMINOR)
        Logger.minor(this, "Create a ZIP Bucket");

    ZipOutputStream zos = new ZipOutputStream(os);
    try {//from  w ww. ja  v  a  2 s.c o m
        ZipEntry ze;

        for (ContainerElement ph : containerItems) {
            ze = new ZipEntry(ph.targetInArchive);
            ze.setTime(0);
            zos.putNextEntry(ze);
            BucketTools.copyTo(ph.data, zos, ph.data.size());
            zos.closeEntry();
        }
    } finally {
        zos.close();
    }

    return ARCHIVE_TYPE.ZIP.mimeTypes[0];
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromStream() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {//from   w w  w  .  j a  v  a2  s.com
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        FileInputStream fis = new FileInputStream(file);
        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(fis, name);
        assertNotNull(actual);
        assertEquals(new String(contents), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePlugin.java

/**
 * Streams the contents of the log directory as a zip file.
 *///from  www .  j  a va2  s .  co m
private void download(HttpServletResponse res, HttpServletRequest req) throws IOException {
    final String selectedLogfile = req.getParameter("file");
    final String filenameSuffix = isEmpty(selectedLogfile) ? ""
            : "-" + substringAfterLast(selectedLogfile, File.separator);

    res.setContentType("application/zip");
    res.setHeader("Content-Disposition",
            "attachment;filename=logfiles-" + req.getServerName() + filenameSuffix + ".zip");
    ZipOutputStream zos = new ZipOutputStream(res.getOutputStream());
    try {
        for (File file : this.logFiles.resolveLogFiles()) {
            if (selectedLogfile != null && !file.getAbsolutePath().equals(selectedLogfile)) {
                continue;
            }

            ZipEntry ze = new ZipEntry(toZipFileEntryName(file));
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(file);
            try {
                copy(in, zos);
                zos.closeEntry();
            } finally {
                closeQuietly(in);
            }
        }
        zos.finish();
    } finally {
        closeQuietly(zos);
    }
}

From source file:dk.itst.oiosaml.sp.configuration.ConfigurationHandler.java

protected File generateZipFile(final String contextPath, final String password, byte[] idpMetadata,
        byte[] keystore, EntityDescriptor descriptor) throws IOException {
    File zipFile = File.createTempFile("oiosaml-", ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    zos.putNextEntry(new ZipEntry("oiosaml-sp.properties"));
    zos.write(renderTemplate("defaultproperties.vm", new HashMap<String, Object>() {
        {/*from  w  w  w.j a  v a 2 s. c  om*/
            put("homename", Constants.PROP_HOME);

            put("servletPath", contextPath);
            put("password", password);
        }
    }, false).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/SP/SPMetadata.xml"));
    zos.write(SAMLUtil.getSAMLObjectAsPrettyPrintXML(descriptor).getBytes());
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("metadata/IdP/IdPMetadata.xml"));
    zos.write(idpMetadata);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("certificate/keystore"));
    zos.write(keystore);
    zos.closeEntry();

    zos.putNextEntry(new ZipEntry("oiosaml-sp.log4j.xml"));
    IOUtils.copy(getClass().getResourceAsStream("oiosaml-sp.log4j.xml"), zos);
    zos.closeEntry();

    zos.close();
    return zipFile;
}

From source file:com.polyvi.xface.extension.zip.XZipExt.java

/**
 * ?/*w  w  w. j a  v a 2s. c  o  m*/
 *
 * @param srcFileUri
 * @param zos
 * @param zipEntryPath
 * @throws IOException
 */
private void zipFile(Uri srcFileUri, ZipOutputStream zos, String zipEntryPath) throws IOException {
    InputStream srcIs = mResourceApi.openForRead(srcFileUri).inputStream;
    ZipEntry zipEntry = new ZipEntry(zipEntryPath);
    zos.putNextEntry(zipEntry);
    writeToZip(srcIs, zos);
}

From source file:fr.cirad.mgdb.exporting.markeroriented.HapMapExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*  ww w  . j a v  a  2 s  .c o  m*/
        }

    List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);
    ArrayList<String> individualList = new ArrayList<String>();
    for (int i = 0; i < sampleIDs.size(); i++) {
        Individual individual = individuals.get(i);
        if (!individualList.contains(individual.getId())) {
            individualList.add(individual.getId());
        }
    }

    String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".hapmap"));
    String header = "rs#" + "\t" + "alleles" + "\t" + "chrom" + "\t" + "pos" + "\t" + "strand" + "\t"
            + "assembly#" + "\t" + "center" + "\t" + "protLSID" + "\t" + "assayLSID" + "\t" + "panelLSID" + "\t"
            + "QCcode";
    zos.write(header.getBytes());
    for (int i = 0; i < individualList.size(); i++) {
        zos.write(("\t" + individualList.get(i)).getBytes());
    }
    zos.write((LINE_SEPARATOR).getBytes());

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    short nProgress = 0, nPreviousProgress = 0;
    long nLoadedMarkerCount = 0;

    while (markerCursor == null || markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
        LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                mongoTemplate, sampleIDs, currentMarkers, true,
                null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
        for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
        {
            Comparable variantId = variant.getId();
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(variantId);
                if (syn != null)
                    variantId = syn;
            }

            boolean fIsSNP = variant.getType().equals(Type.SNP.toString());
            byte[] missingGenotype = ("\t" + "NN").getBytes();

            String[] chromAndPos = markerChromosomalPositions.get(variant.getId()).split(":");
            zos.write(((variantId == null ? variant.getId() : variantId) + "\t"
                    + StringUtils.join(variant.getKnownAlleleList(), "/") + "\t" + chromAndPos[0] + "\t"
                    + Long.parseLong(chromAndPos[1]) + "\t" + "+").getBytes());
            for (int j = 0; j < 6; j++)
                zos.write(("\t" + "NA").getBytes());

            Map<String, Integer> gqValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, Integer> dpValueForSampleId = new LinkedHashMap<String, Integer>();
            Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
            Collection<VariantRunData> runs = variantsAndRuns.get(variant);
            if (runs != null)
                for (VariantRunData run : runs)
                    for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                        SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                        String gtCode = run.getSampleGenotypes().get(sampleIndex).getCode();
                        String individualId = individuals
                                .get(sampleIDs.indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                .getId();
                        List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                        if (storedIndividualGenotypes == null) {
                            storedIndividualGenotypes = new ArrayList<String>();
                            individualGenotypes.put(individualId, storedIndividualGenotypes);
                        }
                        storedIndividualGenotypes.add(gtCode);
                        gqValueForSampleId.put(individualId,
                                (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ));
                        dpValueForSampleId.put(individualId,
                                (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP));
                    }

            int writtenGenotypeCount = 0;
            for (String individualId : individualList /* we use this list because it has the proper ordering */) {
                int individualIndex = individualList.indexOf(individualId);
                while (writtenGenotypeCount < individualIndex - 1) {
                    zos.write(missingGenotype);
                    writtenGenotypeCount++;
                }

                List<String> genotypes = individualGenotypes.get(individualId);
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                int highestGenotypeCount = 0;
                String mostFrequentGenotype = null;
                if (genotypes != null)
                    for (String genotype : genotypes) {
                        if (genotype.length() == 0)
                            continue; /* skip missing genotypes */

                        Integer gqValue = gqValueForSampleId.get(individualId);
                        if (gqValue != null && gqValue < nMinimumGenotypeQuality)
                            continue; /* skip this sample because its GQ is under the threshold */

                        Integer dpValue = dpValueForSampleId.get(individualId);
                        if (dpValue != null && dpValue < nMinimumReadDepth)
                            continue; /* skip this sample because its DP is under the threshold */

                        int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                        if (gtCount > highestGenotypeCount) {
                            highestGenotypeCount = gtCount;
                            mostFrequentGenotype = genotype;
                        }
                        genotypeCounts.put(genotype, gtCount);
                    }

                byte[] exportedGT = mostFrequentGenotype == null ? missingGenotype
                        : ("\t" + StringUtils.join(variant.getAllelesFromGenotypeCode(mostFrequentGenotype),
                                fIsSNP ? "" : "/")).getBytes();
                zos.write(exportedGT);
                writtenGenotypeCount++;

                if (genotypeCounts.size() > 1)
                    warningFileWriter.write("- Dissimilar genotypes found for variant "
                            + (variantId == null ? variant.getId() : variantId) + ", individual " + individualId
                            + ". Exporting most frequent: " + new String(exportedGT) + "\n");
            }

            while (writtenGenotypeCount < individualList.size()) {
                zos.write(missingGenotype);
                writtenGenotypeCount++;
            }
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            //            if (nProgress%5 == 0)
            //               LOG.info("========================= exportData: " + nProgress + "% =========================" + (System.currentTimeMillis() - before)/1000 + "s");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:com.thoughtworks.go.util.ZipUtil.java

void addToZip(ZipPath path, File srcFile, ZipOutputStream zip, boolean excludeRootDir) throws IOException {
    if (srcFile.isDirectory()) {
        addFolderToZip(path, srcFile, zip, excludeRootDir);
    } else {//from   w w w .j av  a 2  s  .  c  o  m
        byte[] buff = new byte[4096];
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(srcFile))) {
            ZipEntry zipEntry = path.with(srcFile).asZipEntry();
            zipEntry.setTime(srcFile.lastModified());
            zip.putNextEntry(zipEntry);
            int len;
            while ((len = inputStream.read(buff)) > 0) {
                zip.write(buff, 0, len);
            }
        }
    }
}

From source file:at.alladin.rmbt.statisticServer.export.ExportResource.java

@Get
public Representation request(final String entity) {
    //Before doing anything => check if a cached file already exists and is new enough
    String property = System.getProperty("java.io.tmpdir");

    final String filename_zip;
    final String filename_csv;

    //allow filtering by month/year
    int year = -1;
    int month = -1;
    int hours = -1;
    boolean hoursExport = false;
    boolean dateExport = false;

    if (getRequest().getAttributes().containsKey("hours")) { // export by hours
        try {/*w w  w  .j  a  v  a  2  s  .com*/
            hours = Integer.parseInt(getRequest().getAttributes().get("hours").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (hours <= 7 * 24 && hours >= 1) { //limit to 1 week (avoid DoS)
            hoursExport = true;
        }
    } else if (!hoursExport && getRequest().getAttributes().containsKey("year")) { // export by month/year 
        try {
            year = Integer.parseInt(getRequest().getAttributes().get("year").toString());
            month = Integer.parseInt(getRequest().getAttributes().get("month").toString());
        } catch (NumberFormatException ex) {
            //Nothing -> just fall back
        }
        if (year < 2099 && month > 0 && month <= 12 && year > 2000) {
            dateExport = true;
        }
    }

    if (hoursExport) {
        filename_zip = FILENAME_ZIP_HOURS.replace("%HOURS%", String.format("%03d", hours));
        filename_csv = FILENAME_CSV_HOURS.replace("%HOURS%", String.format("%03d", hours));
        cacheThresholdMs = 5 * 60 * 1000; //5 minutes
    } else if (dateExport) {
        filename_zip = FILENAME_ZIP.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        filename_csv = FILENAME_CSV.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%",
                String.format("%02d", month));
        cacheThresholdMs = 23 * 60 * 60 * 1000; //23 hours
    } else {
        filename_zip = FILENAME_ZIP_CURRENT;
        filename_csv = FILENAME_CSV_CURRENT;
        cacheThresholdMs = 3 * 60 * 60 * 1000; //3 hours
    }

    final File cachedFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv));
    final File generatingFile = new File(
            property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp");
    if (cachedFile.exists()) {

        //check if file has been recently created OR a file is currently being created
        if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())
                || (generatingFile.exists()
                        && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) {

            //if so, return the cached file instead of a cost-intensive new one
            final OutputRepresentation result = new OutputRepresentation(
                    zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) {

                @Override
                public void write(OutputStream out) throws IOException {
                    InputStream is = new FileInputStream(cachedFile);
                    IOUtils.copy(is, out);
                    out.close();
                }

            };
            if (zip) {
                final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
                disposition.setFilename(filename_zip);
                result.setDisposition(disposition);
            }
            return result;

        }
    }

    final String timeClause;

    if (dateExport)
        timeClause = " AND (EXTRACT (month FROM t.time AT TIME ZONE 'UTC') = " + month
                + ") AND (EXTRACT (year FROM t.time AT TIME ZONE 'UTC') = " + year + ") ";
    else if (hoursExport)
        timeClause = " AND time > now() - interval '" + hours + " hours' ";
    else
        timeClause = " AND time > current_date - interval '31 days' ";

    final String sql = "SELECT" + " ('P' || t.open_uuid) open_uuid,"
            + " ('O' || t.open_test_uuid) open_test_uuid,"
            + " to_char(t.time AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') time_utc,"
            + " nt.group_name cat_technology," + " nt.name network_type,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_lat" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_lat*1111)/1111" + " ELSE null"
            + " END) lat,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN"
            + " t.geo_long" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_long*741)/741 " + " ELSE null"
            + " END) long," + " (CASE WHEN ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN"
            + " 'rastered'" + //make raster transparent
            " ELSE t.geo_provider" + " END) loc_src,"
            + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') "
            + " THEN round(t.geo_accuracy::float * 10)/10 "
            + " WHEN (t.geo_accuracy < 100) AND ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN 100"
            + // limit accuracy to 100m
            " WHEN (t.geo_accuracy < ?) THEN round(t.geo_accuracy::float * 10)/10"
            + " ELSE null END) loc_accuracy, "
            + " (CASE WHEN (t.zip_code < 1000 OR t.zip_code > 9999) THEN null ELSE t.zip_code END) zip_code,"
            + " t.gkz gkz," + " t.country_location country_location," + " t.speed_download download_kbit,"
            + " t.speed_upload upload_kbit," + " round(t.ping_median::float / 100000)/10 ping_ms,"
            + " t.lte_rsrp," + " t.lte_rsrq," + " ts.name server_name," + " duration test_duration,"
            + " num_threads," + " t.plattform platform," + " COALESCE(adm.fullname, t.model) model,"
            + " client_software_version client_version," + " network_operator network_mcc_mnc,"
            + " network_operator_name network_name," + " network_sim_operator sim_mcc_mnc," + " nat_type,"
            + " public_ip_asn asn," + " client_public_ip_anonymized ip_anonym,"
            + " (ndt.s2cspd*1000)::int ndt_download_kbit," + " (ndt.c2sspd*1000)::int ndt_upload_kbit,"
            + " COALESCE(t.implausible, false) implausible," + " t.signal_strength" + " FROM test t"
            + " LEFT JOIN network_type nt ON nt.uid=t.network_type"
            + " LEFT JOIN device_map adm ON adm.codename=t.model"
            + " LEFT JOIN test_server ts ON ts.uid=t.server_id" + " LEFT JOIN test_ndt ndt ON t.uid=ndt.test_id"
            + " WHERE " + " t.deleted = false" + timeClause + " AND status = 'FINISHED'" + " ORDER BY t.uid";

    final String[] columns;
    final List<String[]> data = new ArrayList<>();
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(sql);

        //insert filter for accuracy
        double accuracy = Double.parseDouble(settings.getString("RMBT_GEO_ACCURACY_DETAIL_LIMIT"));
        ps.setDouble(1, accuracy);
        ps.setDouble(2, accuracy);
        ps.setDouble(3, accuracy);
        ps.setDouble(4, accuracy);
        ps.setDouble(5, accuracy);
        ps.setDouble(6, accuracy);

        if (!ps.execute())
            return null;
        rs = ps.getResultSet();

        final ResultSetMetaData meta = rs.getMetaData();
        final int colCnt = meta.getColumnCount();
        columns = new String[colCnt];
        for (int i = 0; i < colCnt; i++)
            columns[i] = meta.getColumnName(i + 1);

        while (rs.next()) {
            final String[] line = new String[colCnt];

            for (int i = 0; i < colCnt; i++) {
                final Object obj = rs.getObject(i + 1);
                line[i] = obj == null ? null : obj.toString();
            }

            data.add(line);
        }
    } catch (final SQLException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }

    final OutputRepresentation result = new OutputRepresentation(
            zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) {
        @Override
        public void write(OutputStream out) throws IOException {
            //cache in file => create temporary temporary file (to 
            // handle errors while fulfilling a request)
            String property = System.getProperty("java.io.tmpdir");
            final File cachedFile = new File(
                    property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp");
            OutputStream outf = new FileOutputStream(cachedFile);

            if (zip) {
                final ZipOutputStream zos = new ZipOutputStream(outf);
                final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt");
                zos.putNextEntry(zeLicense);
                final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt");
                IOUtils.copy(licenseIS, zos);
                licenseIS.close();

                final ZipEntry zeCsv = new ZipEntry(filename_csv);
                zos.putNextEntry(zeCsv);
                outf = zos;
            }

            final OutputStreamWriter osw = new OutputStreamWriter(outf);
            final CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat);

            for (final String c : columns)
                csvPrinter.print(c);
            csvPrinter.println();

            for (final String[] line : data) {
                for (final String f : line)
                    csvPrinter.print(f);
                csvPrinter.println();
            }
            csvPrinter.flush();

            if (zip)
                outf.close();

            //if we reach this code, the data is now cached in a temporary tmp-file
            //so, rename the file for "production use2
            //concurrency issues should be solved by the operating system
            File newCacheFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv));
            Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE,
                    StandardCopyOption.REPLACE_EXISTING);

            FileInputStream fis = new FileInputStream(newCacheFile);
            IOUtils.copy(fis, out);
            fis.close();
            out.close();
        }
    };
    if (zip) {
        final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(filename_zip);
        result.setDisposition(disposition);
    }

    return result;
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromStreamToFile() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {//from   w w w  . ja  v a2s .co  m
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        FileInputStream fis = new FileInputStream(file);

        File outputFile = File.createTempFile("temp-output", null);

        boolean result = ZipUtil.unpackEntry(fis, name, outputFile);
        assertTrue(result);

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(outputFile));
        byte[] actual = new byte[1024];
        int read = bis.read(actual);
        bis.close();

        assertEquals(new String(contents), new String(actual, 0, read));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java

private static void addOriginSigsRels(final String signatureZipEntryName, final ZipOutputStream zipOutputStream)
        throws ParserConfigurationException, IOException, TransformerException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    final Document originSignRelsDocument = documentBuilderFactory.newDocumentBuilder().newDocument();

    final Element relationshipsElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationships"); //$NON-NLS-1$
    relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$
    originSignRelsDocument.appendChild(relationshipsElement);

    final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA,
            "Relationship"); //$NON-NLS-1$
    final String relationshipId = "rel-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    relationshipElement.setAttribute("Id", relationshipId); //$NON-NLS-1$
    relationshipElement.setAttribute("Type", //$NON-NLS-1$
            "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$

    relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$
    relationshipsElement.appendChild(relationshipElement);

    zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); //$NON-NLS-1$
    writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false);
}