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:org.apache.tika.parser.utils.ZipSalvager.java

/**
 * This streams the broken zip and rebuilds a new zip that
 * is at least a valid zip file.  The contents of the final stream
 * may be truncated, but the result should be a valid zip file.
 * <p>//w w w .j a  va 2  s  .c om
 * This does nothing fancy to fix the underlying broken zip.
 *
 * @param brokenZip
 * @param salvagedZip
 */
public static void salvageCopy(InputStream brokenZip, File salvagedZip) {
    try (ZipArchiveOutputStream outputStream = new ZipArchiveOutputStream(salvagedZip)) {
        ZipArchiveInputStream zipArchiveInputStream = new ZipArchiveInputStream(brokenZip);
        ZipArchiveEntry zae = zipArchiveInputStream.getNextZipEntry();
        while (zae != null) {
            try {
                if (!zae.isDirectory() && zipArchiveInputStream.canReadEntryData(zae)) {
                    //create a new ZAE and copy over only the name so that
                    //if there is bad info (e.g. CRC) in brokenZip's zae, that
                    //won't be propagated or cause an exception
                    outputStream.putArchiveEntry(new ZipArchiveEntry(zae.getName()));
                    //this will copy an incomplete stream...so there
                    //could be truncation of the xml/contents, but the zip file
                    //should be intact.
                    boolean successfullyCopied = false;
                    try {
                        IOUtils.copy(zipArchiveInputStream, outputStream);
                        successfullyCopied = true;
                    } catch (IOException e) {
                        //this can hit a "truncated ZipFile" IOException
                    }
                    outputStream.flush();
                    outputStream.closeArchiveEntry();
                    if (!successfullyCopied) {
                        break;
                    }
                }
                zae = zipArchiveInputStream.getNextZipEntry();
            } catch (ZipException | EOFException e) {
                break;
            }

        }
        outputStream.flush();
        outputStream.finish();

    } catch (IOException e) {
        LOG.warn("problem fixing zip", e);
    }
}

From source file:org.apache.wookie.w3c.util.WidgetPackageUtils.java

/**
 * uses apache commons compress to unpack all the zip entries into a target folder
 * partly adapted from the examples on the apache commons compress site, and an
 * example of generic Zip unpacking. Note this iterates over the ZipArchiveEntry enumeration rather
 * than use the more typical ZipInputStream parsing model, as according to the doco it will
 * more reliably read the entries correctly. More info here: http://commons.apache.org/compress/zip.html
 * @param zipfile the Zip File to unpack
 * @param targetFolder the folder into which to unpack the Zip file
 * @throws IOException/*from w w  w .jav a  2  s. co m*/
 */
@SuppressWarnings("unchecked")
public static void unpackZip(ZipFile zipfile, File targetFolder) throws IOException {
    targetFolder.mkdirs();
    BufferedOutputStream out = null;
    InputStream in = null;
    ZipArchiveEntry zipEntry;

    Enumeration entries = zipfile.getEntries();
    try {
        while (entries.hasMoreElements()) {
            zipEntry = (ZipArchiveEntry) entries.nextElement();
            // Don't add directories - use mkdirs instead
            if (!zipEntry.isDirectory()) {
                File outFile = new File(targetFolder, zipEntry.getName());

                // Ensure that the parent Folder exists
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                // Read the entry
                in = new BufferedInputStream(zipfile.getInputStream(zipEntry));
                out = new BufferedOutputStream(new FileOutputStream(outFile));
                IOUtils.copy(in, out);
                // Restore time stamp
                outFile.setLastModified(zipEntry.getTime());

                // Close File
                out.close();
                // Close Stream
                in.close();
            }
        }

    }
    // We'll catch this exception to close the file otherwise it remains locked
    catch (IOException ex) {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        // And throw it again
        throw ex;
    }
}

From source file:org.artificer.atom.archive.ArchiveUtils.java

/**
 * Unpacks the given archive file into the output directory.
 * @param archiveFile an archive file/*from   w  w w.  ja v a 2 s  .c  om*/
 * @param toDir where to unpack the archive to
 * @throws IOException
 */
public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntriesInPhysicalOrder();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            String entryName = entry.getName();
            File outFile = new File(toDir, entryName);
            if (!outFile.getParentFile().exists()) {
                if (!outFile.getParentFile().mkdirs()) {
                    throw new IOException(Messages.i18n.format("FAILED_TO_CREATE_PARENT_DIR",
                            outFile.getParentFile().getCanonicalPath()));
                }
            }

            if (entry.isDirectory()) {
                if (outFile.isDirectory()) {
                    // Do nothing - already created.
                } else if (outFile.isFile()) {
                    throw new IOException(
                            Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath()));
                } else if (!outFile.mkdir()) {
                    throw new IOException(
                            Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath()));
                }
            } else {
                InputStream zipStream = null;
                OutputStream outFileStream = null;

                zipStream = zipFile.getInputStream(entry);
                outFileStream = new FileOutputStream(outFile);
                try {
                    IOUtils.copy(zipStream, outFileStream);
                } finally {
                    IOUtils.closeQuietly(zipStream);
                    IOUtils.closeQuietly(outFileStream);
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;//w ww  .j  a  v  a2  s  .  c o  m
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        @SuppressWarnings("unchecked")
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOUtils.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>/*  w w w  .j av  a2  s  .  com*/
 * unzip.
 * </p>
 * 
 * @param zipFile a {@link java.io.File} object.
 * @param destination a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.util.List} object.
 */
public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOs.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.callimachusproject.io.CarInputStream.java

private String readEntryType(ZipArchiveEntry entry, BufferedInputStream in) throws IOException {
    if (entry == null)
        return null;
    String type = ContentTypeExtraField.parseExtraField(entry);
    if (type != null || entry.isDirectory())
        return type;
    if (FILE_NAME.matcher(entry.getName()).find())
        return mimetypes.getContentType(entry.getName());
    return detectRdfType(in);
}

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));
                }/*ww w .j ava2  s  .  c  o 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 assertDirectory(ZipArchiveEntry entry, String name, LocalDateTime time) throws IOException {
    assertNotNull(name, entry);/*from ww w  .j  a  v a  2 s.c  o m*/
    assertTrue(name + " should be file", entry.isDirectory());
    assertEquals(name + ", name", name, entry.getName());
    assertEquals(name + ", timestamp", time, new LocalDateTime(entry.getTime()));
}

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.jar.JarArchiver.java

/**
 * Grab lists of all root-level files and all directories
 * contained in the given archive.//from ww  w  .j  av  a 2  s  .  com
 *
 * @param file  .
 * @param files .
 * @param dirs  .
 * @throws java.io.IOException .
 */
protected static void grabFilesAndDirs(String file, List<String> dirs, List<String> files) throws IOException {
    File zipFile = new File(file);
    if (!zipFile.exists()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.error("JarArchive skipping non-existing file: " + zipFile.getAbsolutePath());
    } else if (zipFile.isDirectory()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.info("JarArchiver skipping indexJar " + zipFile + " because it is not a jar");
    } else {
        org.apache.commons.compress.archivers.zip.ZipFile zf = null;
        try {
            zf = new org.apache.commons.compress.archivers.zip.ZipFile(file, "utf-8");
            Enumeration<ZipArchiveEntry> entries = zf.getEntries();
            HashSet<String> dirSet = new HashSet<String>();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry ze = entries.nextElement();
                String name = ze.getName();
                // avoid index for manifest-only jars.
                if (!name.equals(META_INF_NAME) && !name.equals(META_INF_NAME + '/') && !name.equals(INDEX_NAME)
                        && !name.equals(MANIFEST_NAME)) {
                    if (ze.isDirectory()) {
                        dirSet.add(name);
                    } else if (!name.contains("/")) {
                        files.add(name);
                    } else {
                        // a file, not in the root
                        // since the jar may be one without directory
                        // entries, add the parent dir of this file as
                        // well.
                        dirSet.add(name.substring(0, name.lastIndexOf("/") + 1));
                    }
                }
            }
            dirs.addAll(dirSet);
        } finally {
            if (zf != null) {
                zf.close();
            }
        }
    }
}