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

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

From source file:de.nx42.maps4cim.util.Compression.java

/**
 * Reads the first file entry in a zip file and returns it's contents
 * as uncompressed byte-array/*  w  w  w.  j a v  a  2s .  c  om*/
 * @param zipFile the zip file to read from
 * @return the first file entry (uncompressed)
 * @throws IOException if there is an error accessing the zip file
 */
public static byte[] readFirstZipEntry(File zipFile) throws IOException {
    // open zip
    ZipFile zf = new ZipFile(zipFile);
    Enumeration<ZipArchiveEntry> entries = zf.getEntries();

    // read first entry to byte[]
    ZipArchiveEntry entry = entries.nextElement();
    InputStream is = zf.getInputStream(entry);
    byte[] raw = ByteStreams.toByteArray(is);

    // close all streams and return byte[]
    is.close();
    zf.close();
    return raw;
}

From source file:edu.jhu.hlt.acute.iterators.zip.ZipArchiveEntryByteIterator.java

/**
 * Wrap a {@link Path} object. /*w ww . j  ava  2s . c  om*/
 * 
 * @throws IOException if there are issues with the underlying archive
 */
public ZipArchiveEntryByteIterator(Path p) throws IOException {
    this.zf = new ZipFile(p.toFile());
    this.iter = this.zf.getEntries();
}

From source file:com.facebook.buck.zip.Unzip.java

/**
 * Unzips a file to a destination and returns the paths of the written files.
 *//*  ww  w  . j  a v a  2  s.c  o m*/
public static ImmutableList<Path> extractZipFile(Path zipFile, ProjectFilesystem filesystem, Path relativePath,
        ExistingFileMode existingFileMode) throws IOException {
    // if requested, clean before extracting
    if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) {
        try (ZipFile zip = new ZipFile(zipFile.toFile())) {
            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                filesystem.deleteRecursivelyIfExists(relativePath.resolve(entry.getName()));
            }
        }
    }
    ImmutableList.Builder<Path> filesWritten = ImmutableList.builder();
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = entry.getName();
            Path target = relativePath.resolve(fileName);

            // TODO(bolinfest): Keep track of which directories have already been written to avoid
            // making unnecessary Files.createDirectories() calls. In practice, a single zip file will
            // have many entries in the same directory.

            if (entry.isDirectory()) {
                // Create the directory and all its parent directories
                filesystem.mkdirs(target);
            } else {
                // Create parent folder
                filesystem.createParentDirs(target);

                filesWritten.add(target);
                // Write file
                try (InputStream is = zip.getInputStream(entry)) {
                    if (entry.isUnixSymlink()) {
                        filesystem.createSymLink(target,
                                filesystem.getPath(new String(ByteStreams.toByteArray(is), Charsets.UTF_8)),
                                /* force */ true);
                    } else {
                        try (OutputStream out = filesystem.newFileOutputStream(target)) {
                            ByteStreams.copy(is, out);
                        }
                    }
                }

                // restore mtime for the file
                filesystem.resolve(target).toFile().setLastModified(entry.getTime());

                // TODO(shs96c): Implement what the comment below says we should do.
                //
                // Sets the file permissions of the output file given the information in {@code entry}'s
                // extra data field. According to the docs at
                // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
                // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
                // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
                //
                // <pre>
                //    The following is the layout of the ASi extra block for Unix.  The
                //    local-header and central-header versions are identical.
                //    (Last Revision 19960916)
                //
                //    Value         Size        Description
                //    -----         ----        -----------
                //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
                //   TSize         Short       total data size for this block
                //   CRC           Long        CRC-32 of the remaining data
                //   Mode          Short       file permissions
                //   SizDev        Long        symlink'd size OR major/minor dev num
                //   UID           Short       user ID
                //   GID           Short       group ID
                //   (var.)        variable    symbolic link filename
                //
                //   Mode is the standard Unix st_mode field from struct stat, containing
                //   user/group/other permissions, setuid/setgid and symlink info, etc.
                // </pre>
                //
                // From the stat man page, we see that the following mask values are defined for the file
                // permissions component of the st_mode field:
                //
                // <pre>
                //   S_ISUID   0004000   set-user-ID bit
                //   S_ISGID   0002000   set-group-ID bit (see below)
                //   S_ISVTX   0001000   sticky bit (see below)
                //
                //   S_IRWXU     00700   mask for file owner permissions
                //
                //   S_IRUSR     00400   owner has read permission
                //   S_IWUSR     00200   owner has write permission
                //   S_IXUSR     00100   owner has execute permission
                //
                //   S_IRWXG     00070   mask for group permissions
                //   S_IRGRP     00040   group has read permission
                //   S_IWGRP     00020   group has write permission
                //   S_IXGRP     00010   group has execute permission
                //
                //   S_IRWXO     00007   mask for permissions for others
                //   (not in group)
                //   S_IROTH     00004   others have read permission
                //   S_IWOTH     00002   others have write permission
                //   S_IXOTH     00001   others have execute permission
                // </pre>
                //
                // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
                // but we'll check and throw if they are.
                //
                // Before we do anything, we should check the header ID. Pfft!
                //
                // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
                // values in the external file attributes of a zip entry (found in the zip's central
                // directory) assuming that the OS creating the zip was one of an enormous list that
                // includes UNIX but not Windows, it first searches for the extra fields, and if not found
                // falls through to a code path that supports MS-DOS and which stores the UNIX file
                // attributes in the upper 16 bits of the external attributes field.
                //
                // We'll support neither approach fully, but we encode whether this file was executable
                // via storing 0100 in the fields that are typically used by zip implementations to store
                // POSIX permissions. If we find it was executable, use the platform independent java
                // interface to make this unpacked file executable.

                Set<PosixFilePermission> permissions = MorePosixFilePermissions
                        .fromMode(entry.getExternalAttributes() >> 16);
                if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)) {
                    MoreFiles.makeExecutable(filesystem.resolve(target));
                }
            }
        }
    }
    return filesWritten.build();
}

From source file:de.flapdoodle.embed.process.extract.ZipExtractor.java

@Override
protected ArchiveWrapper archiveStream(File source) throws IOException {
    ZipFile zipIn = new ZipFile(source);
    return new ZipArchiveWrapper(zipIn);
}

From source file:com.yahoo.parsec.gradle.ParsecInitTask.java

/**
 * Execute./*from  w  ww.  j a  va2s.  com*/
 *
 * @throws TaskExecutionException TaskExecutionException
 */
@TaskAction
public void executeTask() throws TaskExecutionException {

    try {
        // Create ${buildDir}/bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());
        String rdlBinSuffix = System.getProperty("os.name").equals("Mac OS X") ? "darwin" : "linux";

        // Extract rdl to ${buildDir}/bin
        File file = fileUtils.getFileFromResource("/rdl-bin/rdl-bin.zip");
        try (ZipFile zipFile = new ZipFile(file);
                InputStream inputStream = zipFile
                        .getInputStream(zipFile.getEntry(PathUtils.RDL_BINARY + "-" + rdlBinSuffix))) {
            fileUtils.writeResourceAsExecutable(inputStream, pathUtils.getRdlBinaryPath());
        }

        extractParsecRdlGenerator(rdlBinSuffix,
                Arrays.asList("java-model", "java-server", "java-client", "swagger"));

        // Create ${baseDir}/parsec-bin
        fileUtils.checkAndCreateDirectory(pathUtils.getBinPath());

        // Copy all scripts under resource/scripts to ${baseDir}/parsec-bin
        for (Path scriptPath : fileUtils.listDirFilePaths("scripts")) {
            String scriptPathString = scriptPath.toString();
            if (scriptPathString.endsWith(".sh") || scriptPathString.endsWith(".rb")) {
                fileUtils.writeResourceAsExecutable(scriptPath.toString(),
                        pathUtils.getBinPath() + "/" + scriptPath.getFileName());
            }
        }
        String test = pathUtils.getBinPath();
        if (pluginExtension.isGenerateSwagger()) {
            String swaggerUIPath = pathUtils.getSwaggerUIPath();

            // Create ${buildDir}/generated-resources/swagger-ui
            fileUtils.checkAndCreateDirectory(swaggerUIPath);

            // Extract swagger-ui archive if ${buildDir}/generated-resources/swagger-ui is empty
            if (new File(swaggerUIPath).list().length <= 0) {
                fileUtils.unTarZip("/swagger-ui/swagger-ui.tgz", swaggerUIPath, true);
            }
        }
    } catch (IOException e) {
        throw new TaskExecutionException(this, e);
    }
}

From source file:de.nx42.maps4cim.util.Compression.java

/**
 * Reads the first file entry in a zip file and writes it in uncompressed
 * form to the desired file./*from w w  w  .  ja va 2s.  c o  m*/
 * @param zipFile the zip file to read from
 * @param dest the file to write the first zip file entry to
 * @return same as destination
 * @throws IOException if there is an error accessing the zip file or the
 * destination file
 */
public static File readFirstZipEntry(File zipFile, File dest) throws IOException {
    // open zip and get first entry
    ZipFile zf = new ZipFile(zipFile);
    Enumeration<ZipArchiveEntry> entries = zf.getEntries();
    ZipArchiveEntry entry = entries.nextElement();

    // write to file
    InputStream in = zf.getInputStream(entry);
    OutputStream out = new FileOutputStream(dest);
    ByteStreams.copy(in, out);

    // close all streams and return the new file
    in.close();
    out.close();
    zf.close();
    return dest;
}

From source file:com.google.jenkins.plugins.persistentmaster.volume.zip.ZipExtractor.java

ZipExtractor(Path zip) throws IOException {
    zipPath = Preconditions.checkNotNull(zip);
    logger.finer("Extracting zip volume for path: " + zipPath);
    zipFile = new ZipFile(zipPath.toFile());
}

From source file:de.crowdcode.movmvn.core.Unzipper.java

/**
 * Unzip a file./*w w  w. j a va 2  s  .c  o  m*/
 * 
 * @param archiveFile
 *            to be unzipped
 * @param outPath
 *            the place to put the result
 * @throws IOException
 *             exception
 * @throws ZipException
 *             exception
 */
public void unzipFileToDir(final File archiveFile, final File outPath) throws IOException, ZipException {
    ZipFile zipFile = new ZipFile(archiveFile);
    Enumeration<ZipArchiveEntry> e = zipFile.getEntries();
    while (e.hasMoreElements()) {
        ZipArchiveEntry entry = e.nextElement();
        File file = new File(outPath, entry.getName());
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(file);
        } else {
            InputStream is = zipFile.getInputStream(entry);
            FileOutputStream os = FileUtils.openOutputStream(file);
            try {
                IOUtils.copy(is, os);
            } finally {
                os.close();
                is.close();
            }
            file.setLastModified(entry.getTime());
        }
    }
}

From source file:com.github.wolfdogs.kemono.util.resource.zip.ZipDirResource.java

public ZipDirResource(File file) throws IOException {
    this.zipFile = new ZipFile(file);

    initialize();//from   www. j  a v  a  2  s . c o  m

    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry zipArchiveEntry = entries.nextElement();
        String entryPath = zipArchiveEntry.getName();

        createResource(entryPath, zipArchiveEntry);
    }
}

From source file:com.oculusinfo.binning.io.impl.ZipResourcePyramidStreamSource.java

public ZipResourcePyramidStreamSource(String zipFilePath, String tileExtension) {
    try {//from  w  w w  . ja  v  a 2 s  .co  m
        _tileSetArchive = new ZipFile(zipFilePath);
        _tileExtension = tileExtension;
    } catch (IOException e) {
        _logger.warn("Could not create zip file for " + zipFilePath, e);
    }
}