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

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

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Is this entry a directory?

Usage

From source file:adams.core.io.ZipUtils.java

/**
 * Unzips the files in a ZIP file. Files can be filtered based on their
 * filename, using a regular expression (the matching sense can be inverted).
 *
 * @param input   the ZIP file to unzip/* ww  w .  java 2 s  .  co  m*/
 * @param outputDir   the directory where to store the extracted files
 * @param createDirs   whether to re-create the directory structure from the
 *          ZIP file
 * @param match   the regular expression that the files are matched against
 * @param invertMatch   whether to invert the matching sense
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      the successfully extracted files
 */
@MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html")
public static List<File> decompress(File input, File outputDir, boolean createDirs, BaseRegExp match,
        boolean invertMatch, int bufferSize, StringBuilder errors) {
    List<File> result;
    ZipFile archive;
    Enumeration<ZipArchiveEntry> enm;
    ZipArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    BufferedInputStream in;
    BufferedOutputStream out;
    FileOutputStream fos;
    int len;
    String error;
    long read;

    result = new ArrayList<>();
    archive = null;
    try {
        // unzip archive
        buffer = new byte[bufferSize];
        archive = new ZipFile(input.getAbsoluteFile());
        enm = archive.getEntries();
        while (enm.hasMoreElements()) {
            entry = enm.nextElement();

            if (entry.isDirectory() && !createDirs)
                continue;

            // does name match?
            if (!match.isMatchAll() && !match.isEmpty()) {
                if (invertMatch && match.isMatch(entry.getName()))
                    continue;
                else if (!invertMatch && !match.isMatch(entry.getName()))
                    continue;
            }

            // extract
            if (entry.isDirectory() && createDirs) {
                outFile = new File(outputDir.getAbsolutePath() + File.separator + entry.getName());
                if (!outFile.mkdirs()) {
                    error = "Failed to create directory '" + outFile.getAbsolutePath() + "'!";
                    System.err.println(error);
                    errors.append(error + "\n");
                }
            } else {
                in = null;
                out = null;
                fos = null;
                outName = null;
                try {
                    // assemble output name
                    outName = outputDir.getAbsolutePath() + File.separator;
                    if (createDirs)
                        outName += entry.getName();
                    else
                        outName += new File(entry.getName()).getName();

                    // create directory, if necessary
                    outFile = new File(outName).getParentFile();
                    if (!outFile.exists()) {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            continue;
                        }
                    }

                    // extract data
                    in = new BufferedInputStream(archive.getInputStream(entry));
                    fos = new FileOutputStream(outName);
                    out = new BufferedOutputStream(fos, bufferSize);
                    read = 0;
                    while (read < entry.getSize()) {
                        len = in.read(buffer);
                        read += len;
                        out.write(buffer, 0, len);
                    }
                    result.add(new File(outName));
                } catch (Exception e) {
                    error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                    System.err.println(error);
                    errors.append(error + "\n");
                } finally {
                    FileUtils.closeQuietly(in);
                    FileUtils.closeQuietly(out);
                    FileUtils.closeQuietly(fos);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

From source file:com.nabla.wapp.report.server.ReportZipFile.java

public ZipArchiveEntry getReportDesign() {
    for (Enumeration<ZipArchiveEntry> iter = impl.getEntries(); iter.hasMoreElements();) {
        final ZipArchiveEntry entry = iter.nextElement();
        if (!entry.isDirectory() && impl.canReadEntryData(entry)
                && FilenameUtils.isExtension(entry.getName(), ReportManager.REPORT_FILE_EXTENSION))
            return entry;
    }//w w w. j a  va 2 s.c om
    return null;
}

From source file:hudson.util.io.ZipArchiver.java

public void visit(final File f, final String relativePath) throws IOException {
    int mode = IOUtils.mode(f);

    // ZipArchiveEntry already covers all the specialities we used to handle here:
    // - Converts backslashes to slashes
    // - Handles trailing slash of directories
    // - Sets entry's time from file
    // - Sets bitmask from setUnixMode() argument.

    ZipArchiveEntry zae = new ZipArchiveEntry(f, relativePath);
    if (mode != -1) {
        zae.setUnixMode(mode);//from   w  w  w.  j  a v a  2s .c  o  m
    }
    zip.putArchiveEntry(zae);
    if (!zae.isDirectory()) {
        FileInputStream in = new FileInputStream(f);
        try {
            int len;
            while ((len = in.read(buf)) >= 0) {
                zip.write(buf, 0, len);
            }
        } finally {
            in.close();
        }
    }
    zip.closeArchiveEntry();
    entriesWritten++;
}

From source file:io.wcm.maven.plugins.contentpackage.unpacker.ContentUnpacker.java

private void unpackEntry(ZipFile zipFile, ZipArchiveEntry entry, File outputDirectory)
        throws IOException, MojoExecutionException {
    if (entry.isDirectory()) {
        File directory = FileUtils.getFile(outputDirectory, entry.getName());
        directory.mkdirs();//from   w ww.  j a v a 2 s  .c  om
    } else {
        InputStream entryStream = null;
        FileOutputStream fos = null;
        try {
            entryStream = zipFile.getInputStream(entry);
            File outputFile = FileUtils.getFile(outputDirectory, entry.getName());
            if (outputFile.exists()) {
                outputFile.delete();
            }
            File directory = outputFile.getParentFile();
            directory.mkdirs();
            fos = new FileOutputStream(outputFile);
            if (applyXmlExcludes(entry.getName())) {
                // write file with XML filtering
                try {
                    writeXmlWithExcludes(entryStream, fos);
                } catch (JDOMException ex) {
                    throw new MojoExecutionException("Unable to parse XML file: " + entry.getName(), ex);
                }
            } else {
                // write file directly without XML filtering
                IOUtils.copy(entryStream, fos);
            }
        } finally {
            IOUtils.closeQuietly(entryStream);
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:net.orpiske.ssps.common.archive.zip.ZipArchive.java

/**
 * Decompress a file//from  w  ww. ja v  a 2s  .co m
 * @param source the source file to be uncompressed
 * @param destination the destination directory
 * @return the number of bytes read
 * @throws IOException for lower level I/O errors
 */
public long unpack(File source, File destination) throws IOException {
    ZipFile zipFile = null;
    long ret = 0;

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

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

            File outFile = new File(destination.getPath() + File.separator + entry.getName());

            CompressedArchiveUtils.prepareDestination(outFile);

            if (!entry.isDirectory()) {
                ret += extractFile(zipFile, entry, outFile);
            }

            int mode = entry.getUnixMode();
            PermissionsUtils.setPermissions(mode, outFile);
        }
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }

    return ret;
}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

public ArrayList<String> list(File source) throws IOException {
    assertIsZip(source);//from  ww  w  .  j a va  2  s  .  c o  m

    ArrayList<String> paths = new ArrayList<String>();
    try (ZipFile zf = new ZipFile(source)) {
        Enumeration entries = zf.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry e = (ZipArchiveEntry) entries.nextElement();

            String name = FileUtils.toCanonicalPath(e.getName());
            if (e.isDirectory()) {
                continue;
            }

            paths.add(name);
        }
    }
    return paths;
}

From source file:com.facebook.buck.util.unarchive.Unzip.java

/** Unzips a file to a destination and returns the paths of the written files. */
@Override/* www.jav a  2s  .c  o m*/
public ImmutableSet<Path> extractArchive(Path archiveFile, ProjectFilesystem filesystem, Path relativePath,
        Optional<Path> stripPrefix, PatternsMatcher entriesToExclude, ExistingFileMode existingFileMode)
        throws IOException {

    // We want to remove stale contents of directories listed in {@code archiveFile}, but avoid
    // deleting and
    // re-creating any directories that already exist. We *also* want to avoid a full recursive
    // scan of listed directories, since that's almost as slow as deleting. So we preprocess the
    // contents of {@code archiveFile} and then scan the existing filesystem to remove stale
    // artifacts.

    ImmutableSet.Builder<Path> filesWritten = ImmutableSet.builder();
    try (ZipFile zip = new ZipFile(archiveFile.toFile())) {
        SortedMap<Path, ZipArchiveEntry> pathMap;
        if (stripPrefix.isPresent()) {
            pathMap = getZipFilePathsStrippingPrefix(zip, relativePath, stripPrefix.get(), entriesToExclude);
        } else {
            pathMap = getZipFilePaths(zip, relativePath, entriesToExclude);
        }
        // A zip file isn't required to list intermediate paths (e.g., it can contain "foo/" and
        // "foo/bar/baz"), but we need to know not to delete those intermediates, so fill them in.
        for (SortedMap.Entry<Path, ZipArchiveEntry> p : new ArrayList<>(pathMap.entrySet())) {
            if (!isTopLevel(p.getKey(), pathMap)) {
                fillIntermediatePaths(p.getKey(), pathMap);
            }
        }

        DirectoryCreator creator = new DirectoryCreator(filesystem);

        for (SortedMap.Entry<Path, ZipArchiveEntry> p : pathMap.entrySet()) {
            Path target = p.getKey();
            ZipArchiveEntry entry = p.getValue();
            if (entry.isDirectory()) {
                extractDirectory(existingFileMode, pathMap, creator, target);
            } else {
                extractFile(filesWritten, zip, creator, target, entry);
            }
        }
    }
    return filesWritten.build();
}

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

@Override
public boolean execute(Context context) throws Exception {
    this.context = context;
    File tmpFile = null;//from ww  w  .j  a  v  a2 s.  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:info.magnolia.ui.framework.command.ImportZipCommand.java

private void processEntry(ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
    if (entry.getName().startsWith("__MACOSX")) {
        return;//from   w w  w.j  a v  a2  s .c  o m
    } else if (entry.getName().endsWith(".DS_Store")) {
        return;
    }

    if (entry.isDirectory()) {
        ensureFolder(entry);
    } else {
        handleFileEntry(zip, entry);
    }

}

From source file:com.kalix.tools.kibana.KibanaController.java

/**
 * download kibana from remote server/*from   w ww  .  ja va 2 s.c  om*/
 *
 * @throws Exception
 */
public void download() throws Exception {
    File target = new File(workingDirectory, KIBANA_FOLDER);
    if (target.exists()) {
        LOGGER.warn("Kibana folder already exists, download is skipped");
        return;
    }
    LOGGER.debug("Downloading Kibana from {}", KIBANA_LOCATION);
    if (isWindows()) {
        try (ZipArchiveInputStream inputStream = new ZipArchiveInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            ZipArchiveEntry entry;
            while ((entry = (ZipArchiveEntry) inputStream.getNextEntry()) != null) {
                File file = new File(workingDirectory, entry.getName());
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    int read;
                    byte[] buffer = new byte[4096];
                    try (FileOutputStream outputStream = new FileOutputStream(file)) {
                        while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                            outputStream.write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    } else {
        try (GzipCompressorInputStream gzInputStream = new GzipCompressorInputStream(
                new URL(KIBANA_LOCATION).openStream())) {
            try (TarArchiveInputStream inputStream = new TarArchiveInputStream(gzInputStream)) {
                TarArchiveEntry entry;
                while ((entry = (TarArchiveEntry) inputStream.getNextEntry()) != null) {
                    File file = new File(workingDirectory, entry.getName());
                    if (entry.isDirectory()) {
                        file.mkdirs();
                    } else {
                        int read;
                        byte[] buffer = new byte[4096];
                        try (FileOutputStream outputStream = new FileOutputStream(file)) {
                            while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
                                outputStream.write(buffer, 0, read);
                            }
                        }
                        file.setLastModified(entry.getLastModifiedDate().getTime());
                        if (entry instanceof TarArchiveEntry) {
                            int mode = ((TarArchiveEntry) entry).getMode();
                            if ((mode & 00100) > 0) {
                                file.setExecutable(true, (mode & 00001) == 0);
                            }
                        }
                    }
                }
            }
        }
    }
    overrideConfig();
}