Example usage for java.util.zip ZipEntry ZipEntry

List of usage examples for java.util.zip ZipEntry ZipEntry

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

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  ww  w .j a  v  a  2  s. c  o  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:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationZip64Times() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < 2 * Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);/*from  w ww .ja v  a  2s.c  o  m*/
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:jobhunter.persistence.Persistence.java

private void zip(final File file) {

    try (ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file))) {
        l.debug("Generating JHF file");
        zout.setMethod(ZipOutputStream.DEFLATED);
        zout.setLevel(9);//w ww  . j  ava2 s.com

        l.debug("Inserting profile XML");
        zout.putNextEntry(new ZipEntry("profile.xml"));
        xstream.toXML(ProfileRepository.getProfile(), zout);

        l.debug("Inserting subscriptions XML");
        zout.putNextEntry(new ZipEntry("subscriptions.xml"));
        xstream.toXML(SubscriptionRepository.getSubscriptions(), zout);

        updateLastMod(file);
    } catch (IOException e) {
        l.error("Failed to generate file", e);
    }

}

From source file:net.sf.jabref.exporter.OpenOfficeDocumentCreator.java

private static void addResourceFile(String name, String resource, ZipOutputStream out) throws IOException {
    ZipEntry zipEntry = new ZipEntry(name);
    out.putNextEntry(zipEntry);/*from  w ww .j  av  a2s .com*/
    OpenOfficeDocumentCreator.addFromResource(resource, out);
    out.closeEntry();
}

From source file:com.solidmaps.webapp.service.ApostilamentosServiceImpl.java

private void addToZip(ZipOutputStream zos, String file) {

    if (StringUtils.isBlank(file)) {
        return;//w w w. j  a  v  a2s. c o  m
    }

    byte[] buffer = new byte[1024];

    try {
        ZipEntry ze = new ZipEntry(file);
        zos.putNextEntry(ze);

        FileInputStream in = new FileInputStream(FILE_PATH + file);

        int len;
        while ((len = in.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }

        in.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:com.thoughtworks.go.plugin.infra.commons.PluginsZip.java

public void create() {
    checkFilesAccessibility(bundledPlugins, externalPlugins);
    reset();/*from   w  ww.jav  a2  s .  com*/

    MessageDigest md5Digest = DigestUtils.getMd5Digest();
    try (ZipOutputStream zos = new ZipOutputStream(
            new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
        for (GoPluginDescriptor agentPlugins : agentPlugins()) {
            String zipEntryPrefix = "external/";

            if (agentPlugins.isBundledPlugin()) {
                zipEntryPrefix = "bundled/";
            }

            zos.putNextEntry(
                    new ZipEntry(zipEntryPrefix + new File(agentPlugins.pluginFileLocation()).getName()));
            Files.copy(new File(agentPlugins.pluginFileLocation()).toPath(), zos);
            zos.closeEntry();
        }
    } catch (Exception e) {
        LOG.error("Could not create zip of plugins for agent to download.", e);
    }

    md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}

From source file:org.fenixedu.start.controller.StartController.java

private ResponseEntity<byte[]> build(Map<String, byte[]> project, ProjectRequest request) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ZipOutputStream zip = new ZipOutputStream(stream);

    for (Map.Entry<String, byte[]> mapEntry : project.entrySet()) {
        ZipEntry entry = new ZipEntry(request.getArtifactId() + "/" + mapEntry.getKey());
        zip.putNextEntry(entry);/*from  w  w w  .jav  a  2s .  c o  m*/
        zip.write(mapEntry.getValue());
        zip.closeEntry();
    }

    zip.close();

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/zip");
    headers.add("Content-Disposition", "attachment; filename=\"" + request.getArtifactId() + ".zip\"");
    return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
}

From source file:com.compomics.pladipus.core.control.util.ZipUtils.java

static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
        throws UnspecifiedPladipusException, FileNotFoundException, IOException {
    File folder = new File(srcFile);
    if (folder.isDirectory()) {
        addFolderToZip(path, srcFile, zip);
    } else {/*from   w  ww .j  av  a  2  s  . c om*/
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.action.DownloadSignedPdf.java

/**
 * @param sf//from   www  . j a  v  a  2  s.c  o m
 * @param response
 * @throws IOException 
 */
private void writeZip(SignedForm sf, HttpServletResponse response, String fileName) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    ZipEntry ze = new ZipEntry(fileName);
    zos.putNextEntry(ze);
    zos.write(sf.getDocument());
    ze = new ZipEntry(fileName + ".xml");
    zos.putNextEntry(ze);
    zos.write(sf.getDetachedSignature());
    zos.closeEntry();
    zos.close();
}

From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java

/**
 * This method starts the actual archiving of the passed on context containers.
 *
 * @param   lccContainers  The containers to archive.
 * @param   spqmManager    The QueryManager to use.
 *
 * @throws  ArchiverException  In case of any exceptions.
 *
 * @see     com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager)
 *//*  w  w w  . j ava 2s  .c o  m*/
@Override
public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager)
        throws ArchiverException {
    File fArchive = getArchiveFolder();

    for (ContextContainer ccContainer : lccContainers) {
        int iWrapperXML = 0;
        ZipOutputStream zosZip = null;
        File fZipFile = null;
        List<EmailMessage> lEmails = null;

        try {
            lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID());

            // Create the ZipFile
            fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip");
            zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false));
            zosZip.setLevel(m_iZipLevel);

            // Now we have both the container and the emails. We will create an XML
            // to hold all data.
            int iObjectData = ccContainer._getObjectData();

            // Create the zip entry for it.
            ZipEntry zeContainer = new ZipEntry("container.xml");
            zosZip.putNextEntry(zeContainer);

            String sXML = Node.writeToString(iObjectData, true);
            zosZip.write(sXML.getBytes());
            zosZip.closeEntry();

            // Add the email messages to the zip file.
            int iCount = 0;

            for (EmailMessage emMessage : lEmails) {
                iObjectData = emMessage._getObjectData();

                ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml");
                zosZip.putNextEntry(zeEmail);

                sXML = Node.writeToString(iObjectData, true);
                zosZip.write(sXML.getBytes());
                zosZip.closeEntry();
            }

            // Now all files are written into a single Zip file, so we can close it.
        } catch (Exception e) {
            throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0,
                    ccContainer.getID());
        } finally {
            if (iWrapperXML != 0) {
                Node.delete(iWrapperXML);
            }

            if (zosZip != null) {
                try {
                    zosZip.close();
                } catch (IOException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e);
                    }
                }
            }
        }

        // If we get here the zipfile was successfully created. So now we need to remove the
        // mails and the container from the current storage provider.
        try {
            spqmManager.removeContextContainer(ccContainer);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Archived the container with id " + ccContainer.getID());
            }
        } catch (StorageProviderException e) {
            throw new ArchiverException(e,
                    ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE,
                    ccContainer.getID());
        }
    }

    // Now all containers have been archived, we will create a single zip file.
    try {
        File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file "
                    + fFinalArchive.getCanonicalPath());
        }

        new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath());
    } catch (Exception e) {
        throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES);
    }
}