Example usage for org.apache.commons.compress.archivers.zip ZipFile getEntries

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getEntries

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile getEntries.

Prototype

public Enumeration getEntries() 

Source Link

Document

Returns all entries.

Usage

From source file:com.naryx.tagfusion.expression.function.file.ZipList.java

private cfQueryResultData performZiplist(cfSession session, File zipfile, String charset) throws IOException {
    ZipFile zFile = null;
    try {// w  ww  . j av  a 2  s.  com
        cfQueryResultData filesQuery = new cfQueryResultData(new String[] { "name", "type", "compressedsize",
                "size", "compressedpercent", "datelastmodified", "comment" }, "CFZIP");
        zFile = new ZipFile(zipfile, charset);

        List<Map<String, cfData>> allResultRows = new ArrayList<Map<String, cfData>>();
        Map<String, cfData> resultRow;
        Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries();
        ZipArchiveEntry nextEntry = null;
        long size;
        double compressed;

        while (files.hasMoreElements()) {
            nextEntry = (ZipArchiveEntry) files.nextElement();
            resultRow = new FastMap<String, cfData>(8);
            resultRow.put("name", new cfStringData(nextEntry.getName()));
            resultRow.put("comment", new cfStringData(nextEntry.getComment()));
            resultRow.put("datelastmodified", new cfDateData(nextEntry.getTime()));

            if (nextEntry.isDirectory()) {
                resultRow.put("compressedsize", new cfNumberData(0));
                resultRow.put("size", new cfNumberData(0));
                resultRow.put("type", new cfStringData("Dir"));
                resultRow.put("compressedpercent", new cfNumberData(0));

            } else {
                size = nextEntry.getSize();
                resultRow.put("compressedsize",
                        new cfStringData(String.valueOf(nextEntry.getCompressedSize())));
                resultRow.put("size", new cfStringData(String.valueOf(size)));
                resultRow.put("type", new cfStringData("File"));
                if (size != 0) {
                    compressed = ((float) nextEntry.getCompressedSize() / (float) size);
                    resultRow.put("compressedpercent",
                            new cfStringData(String.valueOf(100 - (int) (compressed * 100))));
                } else {
                    resultRow.put("compressedpercent", new cfStringData("0"));
                }
            }

            allResultRows.add(resultRow);
        }
        filesQuery.populateQuery(allResultRows);
        return filesQuery;
    } finally {
        try {
            zFile.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:com.fujitsu.dc.core.bar.BarFileInstaller.java

/**
 * bar?????.//from w  w w  .j  av a  2s  .c om
 * <ul>
 * <li>bar????</li>
 * <li>bar???????</li>
 * <li>TODO bar??????</li>
 * </ul>.
 * @param barFile ????bar?File
 * @returns bar?
 */
private long checkBarFileContents(File barFile) {

    // bar?
    checkBarFileSize(barFile);

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(barFile, "UTF-8");
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        ZipArchiveEntry zae = null;
        long entryCount = 0;
        String entryName = null;
        try {
            long maxBarEntryFileSize = getMaxBarEntryFileSize();
            // ??
            Map<String, String> requiredBarFiles = setupBarFileOrder();
            while (entries.hasMoreElements()) {
                zae = entries.nextElement();
                entryName = zae.getName();
                log.info("read: " + entryName);
                if (!zae.isDirectory()) {
                    // ??????bar?
                    entryCount++;

                    // bar??
                    checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize);

                    // Box?????
                    if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) {
                        checkAndReadManifest(entryName, zae, zipFile);
                    }
                }
                // bar???????
                if (!checkBarFileStructures(zae, requiredBarFiles)) {
                    throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName);
                }
            }
            if (!requiredBarFiles.isEmpty()) {
                StringBuilder entryNames = new StringBuilder();
                Object[] requiredFileNames = requiredBarFiles.keySet().toArray();
                for (int i = 0; i < requiredFileNames.length; i++) {
                    if (i > 0) {
                        entryNames.append(" " + requiredFileNames[i]);
                    } else {
                        entryNames.append(requiredFileNames[i]);
                    }
                }
                throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryNames.toString());
            }
            return entryCount;
        } catch (DcCoreException e) {
            throw e;
        } catch (Exception e) {
            log.info(e.getMessage(), e.fillInStackTrace());
            throw DcCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName);
        }
    } catch (FileNotFoundException e) {
        throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile");
    } catch (ZipException e) {
        throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage());
    } catch (IOException e) {
        throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage());
    } catch (DcCoreException e) {
        throw e;
    } catch (RuntimeException e) {
        throw DcCoreException.Server.UNKNOWN_ERROR;
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:io.personium.core.bar.BarFileInstaller.java

/**
 * bar?????./*from  w ww .j ava  2 s. c om*/
 * <ul>
 * <li>bar????</li>
 * <li>bar???????</li>
 * <li>TODO bar??????</li>
 * </ul>.
 * @param barFile ????bar?File
 * @returns bar?
 */
private long checkBarFileContents(File barFile) {

    // bar?
    checkBarFileSize(barFile);

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(barFile, "UTF-8");
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        ZipArchiveEntry zae = null;
        long entryCount = 0;
        String entryName = null;
        try {
            long maxBarEntryFileSize = getMaxBarEntryFileSize();
            // ??
            Map<String, String> requiredBarFiles = setupBarFileOrder();
            while (entries.hasMoreElements()) {
                zae = entries.nextElement();
                entryName = zae.getName();
                log.info("read: " + entryName);
                if (!zae.isDirectory()) {
                    // ??????bar?
                    entryCount++;

                    // bar??
                    checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize);

                    // Box?????
                    if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) {
                        checkAndReadManifest(entryName, zae, zipFile);
                    }
                }
                // bar???????
                if (!checkBarFileStructures(zae, requiredBarFiles)) {
                    throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName);
                }
            }
            if (!requiredBarFiles.isEmpty()) {
                StringBuilder entryNames = new StringBuilder();
                Object[] requiredFileNames = requiredBarFiles.keySet().toArray();
                for (int i = 0; i < requiredFileNames.length; i++) {
                    if (i > 0) {
                        entryNames.append(" " + requiredFileNames[i]);
                    } else {
                        entryNames.append(requiredFileNames[i]);
                    }
                }
                throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES
                        .params(entryNames.toString());
            }
            return entryCount;
        } catch (PersoniumCoreException e) {
            throw e;
        } catch (Exception e) {
            log.info(e.getMessage(), e.fillInStackTrace());
            throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName);
        }
    } catch (FileNotFoundException e) {
        throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile");
    } catch (ZipException e) {
        throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage());
    } catch (IOException e) {
        throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage());
    } catch (PersoniumCoreException e) {
        throw e;
    } catch (RuntimeException e) {
        throw PersoniumCoreException.Server.UNKNOWN_ERROR;
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Writes a modified version of zip_Source into target.
 *
 * @author S3460/*from  w w w  . ja  v  a  2 s . c om*/
 * @param zipSource the zip source
 * @param target the target
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception {
    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target));
    for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
        ZipArchiveEntry sourceEntry = enumer.nextElement();
        out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName()));
        byte[] oldBytes = toBytes(zipSource, sourceEntry);
        byte[] newBytes = getRandomBytes();
        byte[] mixedBytes = mixBytes(oldBytes, newBytes);
        out.write(mixedBytes, 0, mixedBytes.length);
        out.flush();
        out.closeArchiveEntry();
    }
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1));
    byte[] bytes = getRandomBytes();
    out.write(bytes, 0, bytes.length);
    out.flush();
    out.closeArchiveEntry();
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2)));
    out.closeArchiveEntry();
    out.flush();
    out.finish();
    out.close();
    return new ZipFile(targetFile);
}

From source file:com.naryx.tagfusion.expression.function.file.Unzip.java

private void performUnzip(cfSession _session, File _zipfile, File _destination, String charset,
        boolean _flatten, boolean overwrite) throws cfmRunTimeException {
    ZipFile zFile = null;
    try {/*from   w ww. j  av  a2  s.  c  o  m*/
        zFile = new ZipFile(_zipfile, charset);
    } catch (IOException ze) {
        throwException(_session, "Failed to extract zip file. Check the file is a valid zip file.");
    }

    BufferedInputStream in = null;
    InputStream zIn = null;
    FileOutputStream fout = null;
    File nextFile = null;
    String destinationFilename;
    byte[] buffer = new byte[4096];
    int read;

    try {
        Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries();

        if (files == null) {
            throwException(_session, "Failed to extract zip file. Check the file is a valid zip file.");
        }

        ZipArchiveEntry nextEntry;

        // while unzip stuff goes here
        while (files.hasMoreElements()) {
            nextEntry = files.nextElement();
            destinationFilename = nextEntry.getName();
            File checkFile = new File(
                    _destination.getAbsolutePath() + File.separatorChar + destinationFilename);

            if (checkFile.exists() && !overwrite) {
                throwException(_session, "File already exist");

            } else {
                if (!nextEntry.isDirectory()) {

                    if (_flatten) {
                        int pathEnd = destinationFilename.lastIndexOf('/');
                        if (pathEnd != -1)
                            destinationFilename = destinationFilename.substring(pathEnd + 1);
                    }

                    nextFile = new File(
                            _destination.getAbsolutePath() + File.separatorChar + destinationFilename);
                    try {
                        nextFile = nextFile.getCanonicalFile();
                    } catch (IOException ignore) {
                    } // use original nextFile if getCanonicalFile() fails

                    File parent = nextFile.getParentFile();
                    if (parent != null) {
                        parent.mkdirs(); // create the parent directory structure if needed
                    }

                    try {
                        zIn = zFile.getInputStream(nextEntry);
                        in = new BufferedInputStream(zIn);
                        fout = new FileOutputStream(nextFile, false);
                        while ((read = in.read(buffer)) != -1) {
                            fout.write(buffer, 0, read);
                        }

                        fout.flush();
                    } catch (IOException ioe) {
                        throwException(_session, "Failed to extract entry [" + nextEntry.getName()
                                + "] from zip file to " + nextFile.getAbsolutePath()
                                + ". Check the permissions are suitable to allow this file to be written.");
                    } finally {
                        StreamUtil.closeStream(in);
                        StreamUtil.closeStream(zIn);
                        StreamUtil.closeStream(fout);
                    }

                } else if (!_flatten) {
                    destinationFilename = nextEntry.getName();
                    nextFile = new File(
                            _destination.getAbsolutePath() + File.separatorChar + destinationFilename);
                    try {
                        nextFile = nextFile.getCanonicalFile();
                    } catch (IOException ignore) {
                        // use original nextFile if getCanonicalFile() fails
                    }
                    nextFile.mkdirs();
                }
            }
        }
    } finally {
        try {
            zFile.close();
        } catch (IOException ignored) {
        }
    }

}

From source file:info.magnolia.ui.framework.command.ImportZipCommand.java

@Override
public boolean execute(Context context) throws Exception {
    this.context = context;
    File tmpFile = null;/* w  w  w  .j  av a  2s  . c  o  m*/
    FileOutputStream tmpStream = null;
    try {
        tmpFile = File.createTempFile(ZIP_TMP_FILE_PREFIX, ZIP_TMP_FILE_SUFFIX);
        tmpStream = new FileOutputStream(tmpFile);
        IOUtils.copy(inputStream, tmpStream);
    } catch (IOException e) {
        log.error("Failed to dump zip file to temp file: ", e);
        throw e;
    } finally {
        IOUtils.closeQuietly(tmpStream);
        IOUtils.closeQuietly(inputStream);
    }

    if (isValid(tmpFile)) {
        ZipFile zip = new ZipFile(tmpFile, getEncoding());
        // We use the ant-1.6.5 zip package to workaround encoding issues of the sun implementation (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499)
        // For some reason, entries are not in the opposite order as how they appear in most tools - reversing here.
        // Note that java.util.zip does not show this behaviour, and ant-1.7.1 seems to enumerate entries in alphabetical or random order.
        // Another alternative might be http://truezip.dev.java.net
        final List zipEntries = EnumerationUtils.toList(zip.getEntries());
        Collections.sort(zipEntries, new Comparator() {
            @Override
            public int compare(Object first, Object second) {
                ZipArchiveEntry firstEntry = ((ZipArchiveEntry) first);
                ZipArchiveEntry secondEntry = ((ZipArchiveEntry) second);
                if (firstEntry.isDirectory() != secondEntry.isDirectory()) {
                    // order folders first
                    return Boolean.compare(secondEntry.isDirectory(), firstEntry.isDirectory());
                }
                // order alphabetically
                return firstEntry.getName().compareTo(secondEntry.getName());
            }
        });

        final Iterator it = zipEntries.iterator();
        while (it.hasNext()) {
            ZipArchiveEntry entry = (ZipArchiveEntry) it.next();
            processEntry(zip, entry);
        }
        context.getJCRSession(getRepository()).save();
    }
    return false;
}

From source file:com.android.sdklib.internal.repository.ArchiveInstaller.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder.
 * This root folder is skipped when unarchiving.
 *//* w w w .  j  a va  2 s  .c  o  m*/
@SuppressWarnings("unchecked")
private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description,
        ITaskMonitor monitor) {

    description += " (%1$d%%)";

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);

        // figure if we'll need to set the unix permissions
        boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN
                || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX;

        // To advance the percent and the progress bar, we don't know the number of
        // items left to unzip. However we know the size of the archive and the size of
        // each uncompressed item. The zip file format overhead is negligible so that's
        // a good approximation.
        long incStep = compressedSize / NUM_MONITOR_INC;
        long incTotal = 0;
        long incCurr = 0;
        int lastPercent = 0;

        byte[] buf = new byte[65536];

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String name = entry.getName();

            // ZipFile entries should have forward slashes, but not all Zip
            // implementations can be expected to do that.
            name = name.replace('\\', '/');

            // Zip entries are always packages in a top-level directory
            // (e.g. docs/index.html). However we want to use our top-level
            // directory so we drop the first segment of the path name.
            int pos = name.indexOf('/');
            if (pos < 0 || pos == name.length() - 1) {
                continue;
            } else {
                name = name.substring(pos + 1);
            }

            File destFile = new File(unzipDestFolder, name);

            if (name.endsWith("/")) { //$NON-NLS-1$
                // Create directory if it doesn't exist yet. This allows us to create
                // empty directories.
                if (!destFile.isDirectory() && !destFile.mkdirs()) {
                    monitor.setResult("Failed to create temp directory %1$s", destFile.getPath());
                    return false;
                }
                continue;
            } else if (name.indexOf('/') != -1) {
                // Otherwise it's a file in a sub-directory.
                // Make sure the parent directory has been created.
                File parentDir = destFile.getParentFile();
                if (!parentDir.isDirectory()) {
                    if (!parentDir.mkdirs()) {
                        monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath());
                        return false;
                    }
                }
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(destFile);
                int n;
                InputStream entryContent = zipFile.getInputStream(entry);
                while ((n = entryContent.read(buf)) != -1) {
                    if (n > 0) {
                        fos.write(buf, 0, n);
                    }
                }
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }

            // if needed set the permissions.
            if (usingUnixPerm && destFile.isFile()) {
                // get the mode and test if it contains the executable bit
                int mode = entry.getUnixMode();
                if ((mode & 0111) != 0) {
                    OsHelper.setExecutablePermission(destFile);
                }
            }

            // Increment progress bar to match. We update only between files.
            for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) {
                monitor.incProgress(1);
            }

            int percent = (int) (100 * incTotal / compressedSize);
            if (percent != lastPercent) {
                monitor.setDescription(description, percent);
                lastPercent = percent;
            }

            if (monitor.isCancelRequested()) {
                return false;
            }
        }

        return true;

    } catch (IOException e) {
        monitor.setResult("Unzip failed: %1$s", e.getMessage());

    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // pass
            }
        }
    }

    return false;
}

From source file:com.android.tools.idea.sdk.remote.internal.archives.ArchiveInstaller.java

/**
 * Unzips a zip file into the given destination directory.
 * <p/>/*from  w ww .  ja v  a  2s  .  c  om*/
 * The archive file MUST have a unique "root" folder.
 * This root folder is skipped when unarchiving.
 */
@SuppressWarnings("unchecked")
@VisibleForTesting(visibility = Visibility.PRIVATE)
protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder,
        ITaskMonitor monitor) {

    Archive newArchive = archiveInfo.getNewArchive();
    RemotePkgInfo pkg = newArchive.getParentPackage();
    String pkgName = pkg.getShortDescription();
    long compressedSize = newArchive.getSize();

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);

        // To advance the percent and the progress bar, we don't know the number of
        // items left to unzip. However we know the size of the archive and the size of
        // each uncompressed item. The zip file format overhead is negligible so that's
        // a good approximation.
        long incStep = compressedSize / NUM_MONITOR_INC;
        long incTotal = 0;
        long incCurr = 0;
        int lastPercent = 0;

        byte[] buf = new byte[65536];

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String name = entry.getName();

            // ZipFile entries should have forward slashes, but not all Zip
            // implementations can be expected to do that.
            name = name.replace('\\', '/');

            // Zip entries are always packages in a top-level directory (e.g. docs/index.html).
            int pos = name.indexOf('/');
            if (pos == -1) {
                // All zip entries should have a root folder.
                // This zip entry seems located at the root of the zip.
                // Rather than ignore the file, just place it at the root.
            } else if (pos == name.length() - 1) {
                // This is a zip *directory* entry in the form dir/, so essentially
                // it's the root directory of the SDK. It's safe to ignore that one
                // since we want to use our own root directory and we'll recreate
                // root directories as needed.
                // A direct consequence is that if a malformed archive has multiple
                // root directories, their content will all be merged together.
                continue;
            } else {
                // This is the expected behavior: the zip entry is in the form root/file
                // or root/dir/. We want to use our top-level directory so we drop the
                // first segment of the path name.
                name = name.substring(pos + 1);
            }

            File destFile = new File(unzipDestFolder, name);

            if (name.endsWith("/")) { //$NON-NLS-1$
                // Create directory if it doesn't exist yet. This allows us to create
                // empty directories.
                if (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) {
                    monitor.logError("Failed to create directory %1$s", destFile.getPath());
                    return false;
                }
                continue;
            } else if (name.indexOf('/') != -1) {
                // Otherwise it's a file in a sub-directory.

                // Sanity check: since we're always unzipping in a fresh temp folder
                // the destination file shouldn't already exist.
                if (mFileOp.exists(destFile)) {
                    monitor.logVerbose("Duplicate file found:  %1$s", name);
                }

                // Make sure the parent directory has been created.
                File parentDir = destFile.getParentFile();
                if (!mFileOp.isDirectory(parentDir)) {
                    if (!mFileOp.mkdirs(parentDir)) {
                        monitor.logError("Failed to create directory %1$s", parentDir.getPath());
                        return false;
                    }
                }
            }

            FileOutputStream fos = null;
            long remains = entry.getSize();
            try {
                fos = new FileOutputStream(destFile);

                // Java bug 4040920: do not rely on the input stream EOF and don't
                // try to read more than the entry's size.
                InputStream entryContent = zipFile.getInputStream(entry);
                int n;
                while (remains > 0
                        && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) {
                    remains -= n;
                    if (n > 0) {
                        fos.write(buf, 0, n);
                    }
                }
            } catch (EOFException e) {
                monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.",
                        entry.getName(), entry.getSize(), remains);
                throw e;
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }

            pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry);

            // Increment progress bar to match. We update only between files.
            for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) {
                monitor.incProgress(1);
            }

            int percent = (int) (100 * incTotal / compressedSize);
            if (percent != lastPercent) {
                monitor.setDescription("Unzipping %1$s (%2$d%%)", pkgName, percent);
                lastPercent = percent;
            }

            if (monitor.isCancelRequested()) {
                return false;
            }
        }

        return true;

    } catch (IOException e) {
        monitor.logError("Unzip failed: %1$s", e.getMessage());

    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // pass
            }
        }
    }

    return false;
}

From source file:com.android.sdklib.internal.repository.archives.ArchiveInstaller.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder.
 * This root folder is skipped when unarchiving.
 *//*from  w w  w  .  jav a  2  s .  c  o  m*/
@SuppressWarnings("unchecked")
@VisibleForTesting(visibility = Visibility.PRIVATE)
protected boolean unzipFolder(ArchiveReplacement archiveInfo, File archiveFile, File unzipDestFolder,
        ITaskMonitor monitor) {

    Archive newArchive = archiveInfo.getNewArchive();
    Package pkg = newArchive.getParentPackage();
    String pkgName = pkg.getShortDescription();
    long compressedSize = newArchive.getSize();

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);

        // To advance the percent and the progress bar, we don't know the number of
        // items left to unzip. However we know the size of the archive and the size of
        // each uncompressed item. The zip file format overhead is negligible so that's
        // a good approximation.
        long incStep = compressedSize / NUM_MONITOR_INC;
        long incTotal = 0;
        long incCurr = 0;
        int lastPercent = 0;

        byte[] buf = new byte[65536];

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String name = entry.getName();

            // ZipFile entries should have forward slashes, but not all Zip
            // implementations can be expected to do that.
            name = name.replace('\\', '/');

            // Zip entries are always packages in a top-level directory (e.g. docs/index.html).
            int pos = name.indexOf('/');
            if (pos == -1) {
                // All zip entries should have a root folder.
                // This zip entry seems located at the root of the zip.
                // Rather than ignore the file, just place it at the root.
            } else if (pos == name.length() - 1) {
                // This is a zip *directory* entry in the form dir/, so essentially
                // it's the root directory of the SDK. It's safe to ignore that one
                // since we want to use our own root directory and we'll recreate
                // root directories as needed.
                // A direct consequence is that if a malformed archive has multiple
                // root directories, their content will all be merged together.
                continue;
            } else {
                // This is the expected behavior: the zip entry is in the form root/file
                // or root/dir/. We want to use our top-level directory so we drop the
                // first segment of the path name.
                name = name.substring(pos + 1);
            }

            File destFile = new File(unzipDestFolder, name);

            if (name.endsWith("/")) { //$NON-NLS-1$
                // Create directory if it doesn't exist yet. This allows us to create
                // empty directories.
                if (!mFileOp.isDirectory(destFile) && !mFileOp.mkdirs(destFile)) {
                    monitor.logError("Failed to create directory %1$s", destFile.getPath());
                    return false;
                }
                continue;
            } else if (name.indexOf('/') != -1) {
                // Otherwise it's a file in a sub-directory.

                // Sanity check: since we're always unzipping in a fresh temp folder
                // the destination file shouldn't already exist.
                if (mFileOp.exists(destFile)) {
                    monitor.logVerbose("Duplicate file found:  %1$s", name);
                }

                // Make sure the parent directory has been created.
                File parentDir = destFile.getParentFile();
                if (!mFileOp.isDirectory(parentDir)) {
                    if (!mFileOp.mkdirs(parentDir)) {
                        monitor.logError("Failed to create directory %1$s", parentDir.getPath());
                        return false;
                    }
                }
            }

            FileOutputStream fos = null;
            long remains = entry.getSize();
            try {
                fos = new FileOutputStream(destFile);

                // Java bug 4040920: do not rely on the input stream EOF and don't
                // try to read more than the entry's size.
                InputStream entryContent = zipFile.getInputStream(entry);
                int n;
                while (remains > 0
                        && (n = entryContent.read(buf, 0, (int) Math.min(remains, buf.length))) != -1) {
                    remains -= n;
                    if (n > 0) {
                        fos.write(buf, 0, n);
                    }
                }
            } catch (EOFException e) {
                monitor.logError("Error uncompressing file %s. Size: %d bytes, Unwritten: %d bytes.",
                        entry.getName(), entry.getSize(), remains);
                throw e;
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }

            pkg.postUnzipFileHook(newArchive, monitor, mFileOp, destFile, entry);

            // Increment progress bar to match. We update only between files.
            for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) {
                monitor.incProgress(1);
            }

            int percent = (int) (100 * incTotal / compressedSize);
            if (percent != lastPercent) {
                monitor.setDescription("Unzipping %1$s (%2$d%%)", pkgName, percent);
                lastPercent = percent;
            }

            if (monitor.isCancelRequested()) {
                return false;
            }
        }

        return true;

    } catch (IOException e) {
        monitor.logError("Unzip failed: %1$s", e.getMessage());

    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // pass
            }
        }
    }

    return false;
}

From source file:com.android.sdklib.internal.repository.Archive.java

/**
 * Unzips a zip file into the given destination directory.
 *
 * The archive file MUST have a unique "root" folder. This root folder is skipped when
 * unarchiving. However we return that root folder name to the caller, as it can be used
 * as a template to know what destination directory to use in the Add-on case.
 *//*from   ww  w .  ja  va2  s  . com*/
@SuppressWarnings("unchecked")
private boolean unzipFolder(File archiveFile, long compressedSize, File unzipDestFolder, String description,
        String[] outZipRootFolder, ITaskMonitor monitor) {

    description += " (%1$d%%)";

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);

        // figure if we'll need to set the unix permission
        boolean usingUnixPerm = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN
                || SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX;

        // To advance the percent and the progress bar, we don't know the number of
        // items left to unzip. However we know the size of the archive and the size of
        // each uncompressed item. The zip file format overhead is negligible so that's
        // a good approximation.
        long incStep = compressedSize / NUM_MONITOR_INC;
        long incTotal = 0;
        long incCurr = 0;
        int lastPercent = 0;

        byte[] buf = new byte[65536];

        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String name = entry.getName();

            // ZipFile entries should have forward slashes, but not all Zip
            // implementations can be expected to do that.
            name = name.replace('\\', '/');

            // Zip entries are always packages in a top-level directory
            // (e.g. docs/index.html). However we want to use our top-level
            // directory so we drop the first segment of the path name.
            int pos = name.indexOf('/');
            if (pos < 0 || pos == name.length() - 1) {
                continue;
            } else {
                if (outZipRootFolder[0] == null && pos > 0) {
                    outZipRootFolder[0] = name.substring(0, pos);
                }
                name = name.substring(pos + 1);
            }

            File destFile = new File(unzipDestFolder, name);

            if (name.endsWith("/")) { //$NON-NLS-1$
                // Create directory if it doesn't exist yet. This allows us to create
                // empty directories.
                if (!destFile.isDirectory() && !destFile.mkdirs()) {
                    monitor.setResult("Failed to create temp directory %1$s", destFile.getPath());
                    return false;
                }
                continue;
            } else if (name.indexOf('/') != -1) {
                // Otherwise it's a file in a sub-directory.
                // Make sure the parent directory has been created.
                File parentDir = destFile.getParentFile();
                if (!parentDir.isDirectory()) {
                    if (!parentDir.mkdirs()) {
                        monitor.setResult("Failed to create temp directory %1$s", parentDir.getPath());
                        return false;
                    }
                }
            }

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(destFile);
                int n;
                InputStream entryContent = zipFile.getInputStream(entry);
                while ((n = entryContent.read(buf)) != -1) {
                    if (n > 0) {
                        fos.write(buf, 0, n);
                    }
                }
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }

            // if needed set the permissions.
            if (usingUnixPerm && destFile.isFile()) {
                // get the mode and test if it contains the executable bit
                int mode = entry.getUnixMode();
                if ((mode & 0111) != 0) {
                    setExecutablePermission(destFile);
                }
            }

            // Increment progress bar to match. We update only between files.
            for (incTotal += entry.getCompressedSize(); incCurr < incTotal; incCurr += incStep) {
                monitor.incProgress(1);
            }

            int percent = (int) (100 * incTotal / compressedSize);
            if (percent != lastPercent) {
                monitor.setDescription(description, percent);
                lastPercent = percent;
            }

            if (monitor.isCancelRequested()) {
                return false;
            }
        }

        return true;

    } catch (IOException e) {
        monitor.setResult("Unzip failed: %1$s", e.getMessage());

    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // pass
            }
        }
    }

    return false;
}