Example usage for java.util.zip ZipOutputStream write

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.liferay.ide.server.remote.AbstractRemoteServerPublisher.java

public IPath publishModuleDelta(String archiveName, IModuleResourceDelta[] deltas, String deletePrefix,
        boolean adjustGMTOffset) throws CoreException {
    IPath path = LiferayServerCore.getTempLocation("partial-war", archiveName); //$NON-NLS-1$

    FileOutputStream outputStream = null;
    ZipOutputStream zip = null;
    File warfile = path.toFile();

    warfile.getParentFile().mkdirs();// ww  w .  ja va2  s .c om

    try {
        outputStream = new FileOutputStream(warfile);
        zip = new ZipOutputStream(outputStream);

        Map<ZipEntry, String> deleteEntries = new HashMap<ZipEntry, String>();

        processResourceDeltas(deltas, zip, deleteEntries, deletePrefix, StringPool.EMPTY, adjustGMTOffset);

        for (ZipEntry entry : deleteEntries.keySet()) {
            zip.putNextEntry(entry);
            zip.write(deleteEntries.get(entry).getBytes());
        }

        // if ((removedResources != null) && (removedResources.size() > 0)) {
        // writeRemovedResources(removedResources, zip);
        // }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException localIOException1) {

            }
        }
    }

    return new Path(warfile.getAbsolutePath());
}

From source file:org.dhatim.archive.Archive.java

private void writeEntry(String entryName, byte[] entryValue, ZipOutputStream archiveStream) throws IOException {
    try {// www.j  a  v  a2  s  . com
        archiveStream.putNextEntry(new ZipEntry(entryName));
        if (entryValue != null) {
            archiveStream.write(entryValue);
        }
        archiveStream.closeEntry();
    } catch (Exception e) {
        throw (IOException) new IOException("Unable to create archive entry '" + entryName + "'.").initCause(e);
    }
}

From source file:com.genericworkflownodes.knime.workflowexporter.export.impl.GuseKnimeWorkflowExporter.java

@Override
public void export(final Workflow workflow, final File destination) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(/*from   www .j  a v a  2s  .  c o m*/
                "exporting using " + getShortDescription() + " to [" + destination.getAbsolutePath() + "]");
    }
    final StringBuilder builder = new StringBuilder();
    generateWorkflowXml(workflow, builder);

    final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destination));
    zipOutputStream.putNextEntry(new ZipEntry("workflow.xml"));

    zipOutputStream.write(formatXml(builder.toString()).getBytes());

    zipOutputStream.closeEntry();
    zipOutputStream.close();
}

From source file:hudson.FilePathTest.java

private InputStream someZippedContent() throws IOException {
    final ByteArrayOutputStream buf = new ByteArrayOutputStream();
    final ZipOutputStream zip = new ZipOutputStream(buf);

    zip.putNextEntry(new ZipEntry("abc"));
    zip.write("abc".getBytes());
    zip.close();//from  w ww .  jav  a2 s  . c  om

    return new ByteArrayInputStream(buf.toByteArray());
}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private void zipWriteBytes(final ZipOutputStream outZip, final byte[] bytes) throws DSSException {
    try {/*from   w  w  w.ja va 2s  .com*/
        outZip.write(bytes);
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:es.urjc.mctwp.bbeans.research.image.DownloadBean.java

private void addFileToZos(ZipOutputStream zos, File file, String path) throws IOException {

    //Prepare entry path
    String entry = null;/*from w ww . ja  v a2 s .  c  o  m*/
    if (path != null && !path.isEmpty())
        entry = path + "/" + file.getName();
    else
        entry = file.getName();

    //Create zip entry
    ZipEntry ze = new ZipEntry(entry);
    zos.putNextEntry(ze);

    //Write zip entry
    FileInputStream fileIS = new FileInputStream(file);
    while (fileIS.available() > 0) {
        byte bytes[] = new byte[fileIS.available()];
        fileIS.read(bytes);
        zos.write(bytes);
    }

    zos.flush();
    fileIS.close();
}

From source file:au.org.ala.layers.web.UserDataService.java

@RequestMapping(value = WS_USERDATA_SAMPLE, method = { RequestMethod.POST, RequestMethod.GET })
public @ResponseBody void samplezip(HttpServletRequest req, HttpServletResponse resp) {
    RecordsLookup.setUserDataDao(userDataDao);

    String id = req.getParameter("q");
    String fields = req.getParameter("fl");

    String sample = userDataDao.getSampleZip(id, fields);

    try {/*from ww w . ja v  a 2s.  co  m*/
        // Create the ZIP file
        ZipOutputStream out = new ZipOutputStream(resp.getOutputStream());

        //put entry
        out.putNextEntry(new ZipEntry("sample.csv"));
        out.write(sample.getBytes());
        out.closeEntry();

        resp.setContentType("application/zip");
        resp.setHeader("Content-Disposition", "attachment; filename=\"sample.zip\"");

        // Complete the ZIP file
        out.close();
    } catch (Exception e) {
        logger.error("failed to zip sampling", e);
    }

}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void marshalScheme(Project proj, ZipOutputStream zos) throws IOException {
    final Scheme schemeOrig = proj.getScheme();
    final de.unisaarland.swan.export.model.xml.scheme.Scheme schemeExport = (de.unisaarland.swan.export.model.xml.scheme.Scheme) mapperFacade
            .map(schemeOrig, SCHEME_EXPORT_CLASS);

    String fileName = schemeExport.getName() + ".xml";
    File schemefile = new File(fileName);

    marshalXMLToSingleFile(schemeExport, schemefile);

    zos.putNextEntry(new ZipEntry(fileName));
    zos.write(FileUtils.readFileToByteArray(schemefile));
    zos.closeEntry();//from   w  w w. ja  v a2  s.c  o m
}

From source file:cascading.tap.hadoop.ZipInputFormatTest.java

public void testSplits() throws Exception {
    JobConf job = new JobConf();
    FileSystem currentFs = FileSystem.get(job);

    Path file = new Path(workDir, "test.zip");

    Reporter reporter = Reporter.NULL;//from   w w  w  .  j a  va  2 s  .  co  m

    int seed = new Random().nextInt();
    LOG.info("seed = " + seed);
    Random random = new Random(seed);
    FileInputFormat.setInputPaths(job, file);

    for (int entries = 1; entries < MAX_ENTRIES; entries += random.nextInt(MAX_ENTRIES / 10) + 1) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
        long length = 0;

        LOG.debug("creating; zip file with entries = " + entries);

        // for each entry in the zip file
        for (int entryCounter = 0; entryCounter < entries; entryCounter++) {
            // construct zip entries splitting MAX_LENGTH between entries
            long entryLength = MAX_LENGTH / entries;
            ZipEntry zipEntry = new ZipEntry("/entry" + entryCounter + ".txt");
            zipEntry.setMethod(ZipEntry.DEFLATED);
            zos.putNextEntry(zipEntry);

            for (length = entryCounter * entryLength; length < (entryCounter + 1) * entryLength; length++) {
                zos.write(Long.toString(length).getBytes());
                zos.write("\n".getBytes());
            }

            zos.flush();
            zos.closeEntry();
        }

        zos.flush();
        zos.close();

        currentFs.delete(file, true);

        OutputStream outputStream = currentFs.create(file);

        byteArrayOutputStream.writeTo(outputStream);
        outputStream.close();

        ZipInputFormat format = new ZipInputFormat();
        format.configure(job);
        LongWritable key = new LongWritable();
        Text value = new Text();
        InputSplit[] splits = format.getSplits(job, 100);

        BitSet bits = new BitSet((int) length);
        for (int j = 0; j < splits.length; j++) {
            LOG.debug("split[" + j + "]= " + splits[j]);
            RecordReader<LongWritable, Text> reader = format.getRecordReader(splits[j], job, reporter);

            try {
                int count = 0;

                while (reader.next(key, value)) {
                    int v = Integer.parseInt(value.toString());
                    LOG.debug("read " + v);

                    if (bits.get(v))
                        LOG.warn("conflict with " + v + " in split " + j + " at position " + reader.getPos());

                    assertFalse("key in multiple partitions.", bits.get(v));
                    bits.set(v);
                    count++;
                }

                LOG.debug("splits[" + j + "]=" + splits[j] + " count=" + count);
            } finally {
                reader.close();
            }
        }

        assertEquals("some keys in no partition.", length, bits.cardinality());
    }
}

From source file:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@GET
@Path("/zip")
public Response getResourcesAsZip(@QueryParam("directory") String directory, @QueryParam("files") String files,
        @QueryParam("type") String type) {
    try {//from  w w w. j  a va2s  . c  o m
        if (StringUtils.isBlank(directory))
            return Response.ok().build();

        final String fileType = type;
        IUserContentAccess access = contentAccessFactory.getUserContentAccess(null);

        if (!access.fileExists(directory) && access.hasAccess(directory, FileAccess.READ)) {
            throw new SaikuServiceException(
                    "Access to Repository has failed File does not exist or no read right: " + directory);
        }

        IBasicFileFilter txtFilter = StringUtils.isBlank(type) ? null : new IBasicFileFilter() {
            public boolean accept(IBasicFile file) {
                return file.isDirectory() || file.getExtension().equals(fileType);
            }
        };

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(bos);

        List<IBasicFile> basicFiles = access.listFiles(directory, txtFilter);

        for (IBasicFile basicFile : basicFiles) {
            if (!basicFile.isDirectory()) {
                String entry = basicFile.getName();
                byte[] doc = IOUtils.toByteArray(basicFile.getContents());
                ZipEntry ze = new ZipEntry(entry);
                zos.putNextEntry(ze);
                zos.write(doc);

            }
        }

        zos.closeEntry();
        zos.close();
        byte[] zipDoc = bos.toByteArray();

        return Response.ok(zipDoc, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = " + directory + ".zip")
                .header("content-length", zipDoc.length).build();

    } catch (Exception e) {
        log.error("Cannot zip resources " + files, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(error).build();
    }

}