Example usage for java.util.zip ZipEntry getCompressedSize

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

Introduction

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

Prototype

public long getCompressedSize() 

Source Link

Document

Returns the size of the compressed entry data.

Usage

From source file:org.springframework.integration.zip.transformer.UnZipTransformer.java

@Override
protected Object doZipTransform(final Message<?> message) throws Exception {

    try {//  w  w w  . j a  v  a2  s. c  om
        final Object payload = message.getPayload();
        final Object unzippedData;

        InputStream inputStream = null;

        try {
            if (payload instanceof File) {
                final File filePayload = (File) payload;

                if (filePayload.isDirectory()) {
                    throw new UnsupportedOperationException(
                            String.format("Cannot unzip a directory: '%s'", filePayload.getAbsolutePath()));
                }

                if (!SpringZipUtils.isValid(filePayload)) {
                    throw new IllegalStateException(
                            String.format("Not a zip file: '%s'.", filePayload.getAbsolutePath()));
                }

                inputStream = new FileInputStream(filePayload);
            } else if (payload instanceof InputStream) {
                inputStream = (InputStream) payload;
            } else if (payload instanceof byte[]) {
                inputStream = new ByteArrayInputStream((byte[]) payload);
            } else {
                throw new IllegalArgumentException(String.format("Unsupported payload type '%s'. "
                        + "The only supported payload types are java.io.File, byte[] and java.io.InputStream",
                        payload.getClass().getSimpleName()));
            }

            final SortedMap<String, Object> uncompressedData = new TreeMap<String, Object>();

            ZipUtil.iterate(inputStream, new ZipEntryCallback() {

                @Override
                public void process(InputStream zipEntryInputStream, ZipEntry zipEntry) throws IOException {

                    final String zipEntryName = zipEntry.getName();
                    final long zipEntryTime = zipEntry.getTime();
                    final long zipEntryCompressedSize = zipEntry.getCompressedSize();
                    final String type = zipEntry.isDirectory() ? "directory" : "file";

                    if (logger.isInfoEnabled()) {
                        logger.info(String.format(
                                "Unpacking Zip Entry - Name: '%s',Time: '%s', "
                                        + "Compressed Size: '%s', Type: '%s'",
                                zipEntryName, zipEntryTime, zipEntryCompressedSize, type));
                    }

                    if (ZipResultType.FILE.equals(zipResultType)) {
                        final File destinationFile = checkPath(message, zipEntryName);

                        if (zipEntry.isDirectory()) {
                            destinationFile.mkdirs(); //NOSONAR false positive
                        } else {
                            SpringZipUtils.copy(zipEntryInputStream, destinationFile);
                            uncompressedData.put(zipEntryName, destinationFile);
                        }
                    } else if (ZipResultType.BYTE_ARRAY.equals(zipResultType)) {
                        if (!zipEntry.isDirectory()) {
                            checkPath(message, zipEntryName);
                            byte[] data = IOUtils.toByteArray(zipEntryInputStream);
                            uncompressedData.put(zipEntryName, data);
                        }
                    } else {
                        throw new IllegalStateException("Unsupported zipResultType " + zipResultType);
                    }
                }

                public File checkPath(final Message<?> message, final String zipEntryName) throws IOException {
                    final File tempDir = new File(workDirectory, message.getHeaders().getId().toString());
                    tempDir.mkdirs(); //NOSONAR false positive
                    final File destinationFile = new File(tempDir, zipEntryName);

                    /* If we see the relative traversal string of ".." we need to make sure
                     * that the outputdir + name doesn't leave the outputdir.
                     */
                    if (!destinationFile.getCanonicalPath().startsWith(workDirectory.getCanonicalPath())) {
                        throw new ZipException("The file " + zipEntryName
                                + " is trying to leave the target output directory of " + workDirectory);
                    }
                    return destinationFile;
                }
            });

            if (uncompressedData.isEmpty()) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "No data unzipped from payload with message Id " + message.getHeaders().getId());
                }
                unzippedData = null;
            } else {

                if (this.expectSingleResult) {
                    if (uncompressedData.size() == 1) {
                        unzippedData = uncompressedData.values().iterator().next();
                    } else {
                        throw new MessagingException(message,
                                String.format(
                                        "The UnZip operation extracted %s "
                                                + "result objects but expectSingleResult was 'true'.",
                                        uncompressedData.size()));
                    }
                } else {
                    unzippedData = uncompressedData;
                }

            }
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (payload instanceof File && this.deleteFiles) {
                final File filePayload = (File) payload;
                if (!filePayload.delete() && logger.isWarnEnabled()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("failed to delete File '" + filePayload + "'");
                    }
                }
            }
        }
        return unzippedData;
    } catch (Exception e) {
        throw new MessageHandlingException(message, "Failed to apply Zip transformation.", e);
    }
}

From source file:ZipUtilTest.java

public void testKeepEntriesState() throws IOException {
    File src = new File(getClass().getResource("demo-keep-entries-state.zip").getPath());
    final String existingEntryName = "TestFile.txt";
    final String fileNameToAdd = "TestFile-II.txt";
    assertFalse(ZipUtil.containsEntry(src, fileNameToAdd));
    File newEntry = new File(getClass().getResource(fileNameToAdd).getPath());
    File dest = File.createTempFile("temp.zip", null);
    ZipUtil.addEntry(src, fileNameToAdd, newEntry, dest);

    ZipEntry srcEntry = new ZipFile(src).getEntry(existingEntryName);
    ZipEntry destEntry = new ZipFile(dest).getEntry(existingEntryName);
    assertTrue(srcEntry.getCompressedSize() == destEntry.getCompressedSize());
}

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests downloading the content of a download node(a zip) using the /nodes API:
 *
 * <p>GET:</p>//from   www  .  ja  v a  2 s  . c om
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>/content}
 * 
 */
@Test
public void test004GetDownloadContent() throws Exception {

    //test downloading the content of a 1 file zip
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    HttpResponse response = downloadContent(download);

    ZipInputStream zipStream = getZipStreamFromResponse(response);

    ZipEntry zipEntry = zipStream.getNextEntry();

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipEntry.getName());

    assertTrue("Zip entry size is not correct", zipEntry.getCompressedSize() <= 13);

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    Map<String, String> responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
            ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION, ZIPPABLE_DOC1_NAME + DEFAULT_ARCHIVE_EXTENSION),
            responseHeaders.get("Content-Disposition"));

    //test downloading the content of a multiple file zip
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableFolderId1, zippableDocId3_InFolder1);

    assertDoneDownload(download, 3, 39);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + DOC3_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/",
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER1_NAME + "/" + SUB_FOLDER1_NAME + "/" + DOC4_NAME,
            zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", DOC3_NAME, zipStream.getNextEntry().getName());

    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
    zipStream.close();

    responseHeaders = response.getHeaders();

    assertNotNull(responseHeaders);

    assertEquals(format("attachment; filename=\"%s\"; filename*=UTF-8''%s", DEFAULT_ARCHIVE_NAME,
            DEFAULT_ARCHIVE_NAME), responseHeaders.get("Content-Disposition"));

    //test download the content of a zip which has a secondary child
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1, zippableFolderId3);
    assertDoneDownload(download, 2, 26);

    response = downloadContent(download);

    zipStream = getZipStreamFromResponse(response);

    assertEquals("Zip entry name is not correct", ZIPPABLE_DOC1_NAME, zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/", zipStream.getNextEntry().getName());
    assertEquals("Zip entry name is not correct", FOLDER3_NAME + "/" + ZIPPABLE_DOC1_NAME,
            zipStream.getNextEntry().getName());
    assertTrue("No more entries should be in this zip", zipStream.getNextEntry() == null);
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Ignore("Broken in OpenJDK8 zipfs")
@Test/*w w w  .  j a va  2s.  c o  m*/
public void mimeTypePosition() throws Exception {
    Bundle bundle = Bundles.createBundle();
    String mimetype = "application/x-test";
    Bundles.setMimeType(bundle, mimetype);
    assertEquals(mimetype, Bundles.getMimeType(bundle));
    Path zip = Bundles.closeBundle(bundle);

    assertTrue(Files.exists(zip));
    try (ZipFile zipFile = new ZipFile(zip.toFile())) {
        // Must be first entry
        ZipEntry mimeEntry = zipFile.entries().nextElement();
        assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
        assertEquals("mimetype should be uncompressed, but compressed size mismatch",
                mimeEntry.getCompressedSize(), mimeEntry.getSize());
        assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
        assertEquals("Wrong mimetype", mimetype, IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));
    }

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + mimetype + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(zip.toFile());
    byte[] actual = new byte[expected.length];

    try {

        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}

From source file:com.amazonaws.eclipse.sdk.ui.AbstractSdkManager.java

private void unzipSDK(File zipFile, File unzipDestination, IProgressMonitor monitor, int totalUnitsOfWork)
        throws IOException {

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));

    monitor.subTask("Extracting SDK to workspace metadata directory");

    int worked = 0;
    long totalSize = zipFile.length();
    long totalUnzipped = 0;
    int unitWorkInBytes = (int) (totalSize / (double) totalUnitsOfWork);

    ZipEntry zipEntry = null;

    try {// w  w  w. ja  v a  2 s . c  o  m
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            IPath path = new Path(zipEntry.getName());

            File destinationFile = new File(unzipDestination, path.toOSString());
            if (zipEntry.isDirectory()) {
                destinationFile.mkdirs();
            } else {
                long compressedSize = zipEntry.getCompressedSize();

                FileOutputStream outputStream = new FileOutputStream(destinationFile);
                try {
                    IOUtils.copy(zipInputStream, outputStream);
                } catch (EOFException eof) {
                    /*
                     * There is a bug in ZipInputStream, where it might
                     * incorrectly throw EOFException if the read exceeds
                     * the current zip-entry size.
                     *
                     * http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6519463
                     */
                    JavaSdkPlugin.getDefault().getLog().log(new Status(Status.WARNING, JavaSdkPlugin.PLUGIN_ID,
                            "Ignore EOFException when unpacking zip-entry " + zipEntry.getName(), eof));
                }
                outputStream.close();

                totalUnzipped += compressedSize;
                if (totalUnzipped / unitWorkInBytes > worked) {
                    int newWork = (int) (totalUnzipped / (double) unitWorkInBytes) - worked;
                    monitor.worked(newWork);
                    worked += newWork;
                }
            }
        }

    } finally {
        zipInputStream.close();
    }
}

From source file:fr.inria.atlanmod.neo4emf.neo4jresolver.runtimes.internal.Neo4jZippedInstaller.java

@Override
public void performInstall(IProgressMonitor monitor, IPath dirPath) throws IOException {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/* w  ww .j a v a 2s.co  m*/

    InputStream urlStream = null;
    try {
        URL url = getUrl();
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);

        int length = connection.getContentLength();
        monitor.beginTask(NLS.bind("Reading from {1}", getVersion(), getUrl().toString()),
                length >= 0 ? length : IProgressMonitor.UNKNOWN);

        urlStream = connection.getInputStream();
        ZipInputStream zipStream = new ZipInputStream(urlStream);
        byte[] buffer = new byte[1024 * 8];
        long start = System.currentTimeMillis();
        int total = length;
        int totalRead = 0;
        ZipEntry entry;
        float kBps = -1;
        while ((entry = zipStream.getNextEntry()) != null) {
            if (monitor.isCanceled())
                break;
            String fullFilename = entry.getName();
            IPath fullFilenamePath = new Path(fullFilename);
            int secsRemaining = (int) ((total - totalRead) / 1024 / kBps);
            String textRemaining = secsToText(secsRemaining);
            monitor.subTask(NLS.bind("{0} remaining. Reading {1}",
                    textRemaining.length() > 0 ? textRemaining : "unknown time", StringUtils
                            .abbreviateMiddle(fullFilenamePath.removeFirstSegments(1).toString(), "...", 45)));
            int entrySize = (int) entry.getCompressedSize();
            OutputStream output = null;
            try {
                int len = 0;
                int read = 0;
                String action = null;
                if (jarFiles.contains(fullFilename)) {
                    action = "Copying";
                    String filename = FilenameUtils.getName(fullFilename);
                    output = new FileOutputStream(dirPath.append(filename).toOSString());
                } else {
                    action = "Skipping";
                    output = new NullOutputStream();
                }
                int secs = (int) ((System.currentTimeMillis() - start) / 1000);
                kBps = (float) totalRead / 1024 / secs;

                while ((len = zipStream.read(buffer)) > 0) {
                    if (monitor.isCanceled())
                        break;
                    read += len;
                    monitor.subTask(NLS.bind("{0} remaining. {1} {2} at {3}KB/s ({4}KB / {5}KB)",
                            new Object[] {
                                    String.format("%s",
                                            textRemaining.length() > 0 ? textRemaining : "unknown time"),
                                    action,
                                    StringUtils.abbreviateMiddle(
                                            fullFilenamePath.removeFirstSegments(1).toString(), "...", 45),
                                    String.format("%,.1f", kBps), String.format("%,.1f", (float) read / 1024),
                                    String.format("%,.1f", (float) entry.getSize() / 1024) }));
                    output.write(buffer, 0, len);
                }
                totalRead += entrySize;
                monitor.worked(entrySize);
            } finally {
                IOUtils.closeQuietly(output);
            }
        }
    } finally {
        IOUtils.closeQuietly(urlStream);
        monitor.done();
    }
}

From source file:InstallJars.java

/** Copy a zip entry. */
protected void copyEntry(String target, ZipInputStream zis, ZipEntry ze) throws IOException {
    String name = ze.getName();/*from w w w .jav  a2s.c  o  m*/
    boolean isDir = false;
    if (name.endsWith("/")) {
        name = name.substring(0, name.length() - 1);
        isDir = true;
    }
    String path = target + File.separator + name;
    path = path.replace('\\', '/');
    String mod = ze.getSize() > 0 ? ("[" + ze.getCompressedSize() + ":" + ze.getSize() + "]") : "";
    print("Expanding " + ze + mod + " to " + path);
    prepDirs(path, isDir);
    if (!isDir) {
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(path),
                BLOCK_SIZE * BLOCK_COUNT);
        try {
            byte[] buf = new byte[bufferSize];
            for (int size = zis.read(buf, 0, buf.length), count = 0; size >= 0; size = zis.read(buf, 0,
                    buf.length), count++) {
                // if (count % 4 == 0) print(".");
                os.write(buf, 0, size);
            }
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException ioe) {
            }
        }
    }
    println();
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void mimeTypePosition() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_EPUB);
    assertEquals(UCFPackage.MIME_EPUB, container.getPackageMediaType());
    container.save(tmpFile);//w w w .  j  a  va  2  s  .c  o m
    assertTrue(tmpFile.exists());
    ZipFile zipFile = new ZipFile(tmpFile);
    // Must be first entry
    ZipEntry mimeEntry = zipFile.entries().nextElement();
    assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
    assertEquals("mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(),
            mimeEntry.getSize());
    assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
    assertEquals("Wrong mimetype", UCFPackage.MIME_EPUB,
            IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + UCFPackage.MIME_EPUB + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(tmpFile);
    byte[] actual = new byte[expected.length];
    try {
        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}

From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java

private Document getDeploymentStructureFromArchive(File zipFile) throws Exception {
    getLog().debug("Read deployment-informations from archive <" + zipFile + ">");
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry entry;
    Document doc = null;//from w  ww .ja  v  a 2  s . c  om
    boolean done = false;
    while (!done && (entry = zis.getNextEntry()) != null) {
        String entryName = entry.getName().toLowerCase();
        if (entryName.endsWith("meta-inf/" + JBOSS_SUBDEPLOYMENT)
                || entryName.endsWith("web-inf/" + JBOSS_SUBDEPLOYMENT)) {
            byte[] buf = IOUtils.toByteArray(zis);
            if (verbose) {
                getLog().debug(new String(buf, encoding));
            }
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            // doc=factory.newDocumentBuilder().parse(new ByteArrayInputStream(buf),encoding);
            doc = factory.newDocumentBuilder().parse(
                    new org.xml.sax.InputSource(new java.io.StringReader(new String(buf, encoding).trim())));
            done = true;
        } else {
            if (entry.getCompressedSize() >= 0) {
                if (verbose) {
                    getLog().debug("Skipping entry <" + entryName + "> to next entry for bytes:"
                            + entry.getCompressedSize());
                }
                zis.skip(entry.getCompressedSize());
            }
        }
    }
    zis.close();
    return doc;
}

From source file:me.piebridge.bible.Bible.java

private boolean unpackZip(File path) throws IOException {
    if (path == null || !path.isFile()) {
        return false;
    }/*ww w  . jav a2s . c om*/

    File dirpath = getExternalFilesDirWrapper();

    // bibledata-zh-cn-version.zip
    String filename = path.getAbsolutePath();
    int sep = filename.lastIndexOf("-");
    if (sep != -1) {
        filename = filename.substring(sep + 1, filename.length() - 4);
    }
    filename += ".sqlite3";

    InputStream is = new FileInputStream(path);
    long fileSize = path.length();
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    try {
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            long zeSize = ze.getCompressedSize();
            // zip is incomplete
            if (fileSize < zeSize) {
                break;
            }
            String zename = ze.getName();
            if (zename == null || !zename.endsWith((".sqlite3"))) {
                continue;
            }
            sep = zename.lastIndexOf(File.separator);
            if (sep != -1) {
                zename = zename.substring(sep + 1);
            }
            File file;
            String version = zename.toLowerCase(Locale.US).replace(".sqlite3", "");
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(dirpath, zename);
            }
            if (file.exists() && file.lastModified() > ze.getTime()
                    && file.lastModified() > path.lastModified()) {
                continue;
            }
            Log.d(TAG, "unpacking " + file.getAbsoluteFile());
            int length;
            File tmpfile = new File(dirpath, zename + ".tmp");
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpfile));
            byte[] buffer = new byte[8192];
            int zero = 0;
            while ((length = zis.read(buffer)) != -1) {
                if (length == 0) {
                    ++zero;
                    if (zero > 3) {
                        break;
                    }
                } else {
                    zero = 0;
                }
                os.write(buffer, 0, length);
            }
            os.close();
            if (zero > 3) {
                return false;
            } else {
                tmpfile.renameTo(file);
                path.delete();
                return true;
            }
        }
    } finally {
        is.close();
        zis.close();
    }
    return false;
}