Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getUnixMode

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getUnixMode

Introduction

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

Prototype

public int getUnixMode() 

Source Link

Document

Unix permission.

Usage

From source file:com.android.repository.util.InstallerUtil.java

/**
 * Unzips the given zipped input stream into the given directory.
 *
 * @param in           The (zipped) input stream.
 * @param out          The directory into which to expand the files. Must exist.
 * @param fop          The {@link FileOp} to use for file operations.
 * @param expectedSize Compressed size of the stream.
 * @param progress     Currently only used for logging.
 * @throws IOException If we're unable to read or write.
 *//* ww  w  .  j a va  2s . com*/
public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize,
        @NonNull ProgressIndicator progress) throws IOException {
    if (!fop.exists(out) || !fop.isDirectory(out)) {
        throw new IllegalArgumentException("out must exist and be a directory.");
    }
    // ZipFile requires an actual (not mock) file, so make sure we have a real one.
    in = fop.ensureRealFile(in);

    progress.setText("Unzipping...");
    ZipFile zipFile = new ZipFile(in);
    try {
        Enumeration entries = zipFile.getEntries();
        progress.setFraction(0);
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
            String name = entry.getName();
            File entryFile = new File(out, name);
            progress.setSecondaryText(name);
            if (entry.isUnixSymlink()) {
                ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream();
                readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress);
                Path linkPath = fop.toPath(entryFile);
                Path linkTarget = fop.toPath(new File(targetByteStream.toString()));
                Files.createSymbolicLink(linkPath, linkTarget);
            } else if (entry.isDirectory()) {
                if (!fop.exists(entryFile)) {
                    if (!fop.mkdirs(entryFile)) {
                        progress.logWarning("failed to mkdirs " + entryFile);
                    }
                }
            } else {
                if (!fop.exists(entryFile)) {
                    File parent = entryFile.getParentFile();
                    if (parent != null && !fop.exists(parent)) {
                        fop.mkdirs(parent);
                    }
                    if (!fop.createNewFile(entryFile)) {
                        throw new IOException("Failed to create file " + entryFile);
                    }
                }

                OutputStream unzippedOutput = fop.newFileOutputStream(entryFile);
                if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) {
                    return;
                }
                if (!fop.isWindows()) {
                    // get the mode and test if it contains the executable bit
                    int mode = entry.getUnixMode();
                    //noinspection OctalInteger
                    if ((mode & 0111) != 0) {
                        try {
                            fop.setExecutablePermission(entryFile);
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
    // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
    // all the zip file data and will return "0" for any call to getUnixMode().
    try (ZipFile zipFile = new ZipFile(archive.toFile())) {
        // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }/* w ww. ja  va2s  .  c o  m*/

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        IOUtils.copy(in, out);
                        PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                                PosixFileAttributeView.class);
                        if (attributeView != null) {
                            attributeView
                                    .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
                        }
                    }
                }
            }
        }
    }
    progressListener.done();
}

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.
 *//*from   ww w .  j av  a 2s .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.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  .  j av a2  s  .c om
@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;
}

From source file:net.sourceforge.pmd.it.ZipFileExtractor.java

/**
 * Extracts the given zip file into the tempDir.
 * @param zipPath the zip file to extract
 * @param tempDir the target directory//from w  w  w. ja  va 2s.  c o  m
 * @throws Exception if any error happens during extraction
 */
public static void extractZipFile(Path zipPath, Path tempDir) throws Exception {
    ZipFile zip = new ZipFile(zipPath.toFile());
    try {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File file = tempDir.resolve(entry.getName()).toFile();
            if (entry.isDirectory()) {
                assertTrue(file.mkdirs());
            } else {
                try (InputStream data = zip.getInputStream(entry);
                        OutputStream fileOut = new FileOutputStream(file);) {
                    IOUtils.copy(data, fileOut);
                }
                if ((entry.getUnixMode() & OWNER_EXECUTABLE) == OWNER_EXECUTABLE) {
                    file.setExecutable(true);
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:org.abysm.onionzip.ZipFileExtractHelper.java

void listZipArchiveEntries() throws IOException {
    ZipFile zipFile = new ZipFile(zipFilename, encoding);
    try {/*from w  w w . j a v a  2  s  . c o  m*/
        System.out.println("Length\tDatetime\tName\tEFS\tUnix Mode");
        for (Enumeration<ZipArchiveEntry> zipArchiveEntryEnumeration = zipFile
                .getEntries(); zipArchiveEntryEnumeration.hasMoreElements();) {
            ZipArchiveEntry entry = zipArchiveEntryEnumeration.nextElement();
            System.out.format("%d\t%s\t%s\t%b\t%o\n", entry.getSize(), entry.getLastModifiedDate().toString(),
                    entry.getName(), entry.getGeneralPurposeBit().usesUTF8ForNames(), entry.getUnixMode());
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.cloudfoundry.util.ResourceMatchingUtils.java

private static Flux<ArtifactMetadata> getArtifactMetadataFromZip(Path application) {
    List<ArtifactMetadata> artifactMetadatas = new ArrayList<>();

    try (ZipFile zipFile = new ZipFile(application.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            if (!entry.isDirectory()) {
                try (InputStream in = zipFile.getInputStream(entry)) {
                    String hash = FileUtils.hash(in);
                    String path = entry.getName();
                    String permissions = FileUtils.permissions(entry.getUnixMode());
                    int size = (int) entry.getSize();

                    artifactMetadatas.add(new ArtifactMetadata(hash, path, permissions, size));
                }//from w w w  .j  a  v  a2 s.co  m

            }
        }
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }

    return Flux.fromIterable(artifactMetadatas);
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipPackageTest.java

private void assertFile(ZipFile file, ZipArchiveEntry entry, String name, int size, LocalDateTime time,
        String content, UnixFileMode mode) throws IOException {
    InputStream in = file.getInputStream(entry);

    assertFalse(name + " should be file", entry.isDirectory());
    assertEquals(name + ", name", name, entry.getName());
    assertEquals(name + ", timestamp", time, new LocalDateTime(entry.getTime()));
    // wtf: http://vimalathithen.blogspot.no/2006/06/using-zipentrygetsize.html
    // assertEquals( name + ", size", size, entry.getSize() );

    byte[] bytes = new byte[1000];
    assertEquals(size, in.read(bytes, 0, bytes.length));
    assertEquals(content, new String(bytes, 0, size, charset));

    assertEquals(ZipArchiveEntry.PLATFORM_UNIX, entry.getPlatform());
    assertEquals(name + ", mode", mode.toString(), UnixFileMode.fromInt(entry.getUnixMode()).toString());
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipUnArchiver.java

protected void execute() throws ArchiverException {
    getLogger().debug("Expanding: " + getSourceFile() + " into " + getDestDirectory());
    org.apache.commons.compress.archivers.zip.ZipFile zf = null;
    try {/*  ww w  . jav  a  2s  .c om*/
        zf = new org.apache.commons.compress.archivers.zip.ZipFile(getSourceFile(), encoding);
        final Enumeration e = zf.getEntries();
        while (e.hasMoreElements()) {
            final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
            final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zf, ze);
            if (isSelected(ze.getName(), fileInfo)) {
                InputStream in = zf.getInputStream(ze);
                extractFileIfIncluded(getSourceFile(), getDestDirectory(), in, ze.getName(),
                        new Date(ze.getTime()), ze.isDirectory(),
                        ze.getUnixMode() != 0 ? ze.getUnixMode() : null, resolveSymlink(zf, ze));
                IOUtil.close(in);
            }

        }

        getLogger().debug("expand complete");
    } catch (final IOException ioe) {
        throw new ArchiverException("Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
        IOUtils.closeQuietly(zf);
    }
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipUnArchiver.java

protected void execute(final String path, final File outputDirectory) throws ArchiverException {
    org.apache.commons.compress.archivers.zip.ZipFile zipFile = null;

    try {/* w  w w  .j a  va 2s. co m*/
        zipFile = new org.apache.commons.compress.archivers.zip.ZipFile(getSourceFile(), encoding);

        final Enumeration e = zipFile.getEntries();

        while (e.hasMoreElements()) {
            final ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement();
            final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zipFile, ze);
            if (!isSelected(ze.getName(), fileInfo)) {
                continue;
            }

            if (ze.getName().startsWith(path)) {
                final InputStream inputStream = zipFile.getInputStream(ze);
                extractFileIfIncluded(getSourceFile(), outputDirectory, inputStream, ze.getName(),
                        new Date(ze.getTime()), ze.isDirectory(),
                        ze.getUnixMode() != 0 ? ze.getUnixMode() : null, resolveSymlink(zipFile, ze));
                IOUtil.close(inputStream);
            }
        }
    } catch (final IOException ioe) {
        throw new ArchiverException("Error while expanding " + getSourceFile().getAbsolutePath(), ioe);
    } finally {
        IOUtils.closeQuietly(zipFile);
    }
}