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

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get the name of the entry.

Usage

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Entry to new name.//w w w  .  j a v  a 2 s . c o m
 *
 * @param source the source
 * @param name the name
 * @return the zip archive entry
 * @throws ZipException the zip exception
 */
public static ZipArchiveEntry entryToNewName(ZipArchiveEntry source, String name) throws ZipException {
    if (source.getName().equals(name))
        return new ZipArchiveEntry(source);
    ZipArchiveEntry ret = new ZipArchiveEntry(name);
    byte[] extra = source.getExtra();
    if (extra != null) {
        ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ));
    } else {
        ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true)));
    }
    ret.setInternalAttributes(source.getInternalAttributes());
    ret.setExternalAttributes(source.getExternalAttributes());
    ret.setExtraFields(source.getExtraFields(true));
    ret.setCrc(source.getCrc());
    ret.setMethod(source.getMethod());
    ret.setSize(source.getSize());
    return ret;
}

From source file:jetbrains.exodus.entitystore.BackupTests.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void extractEntireZip(@NotNull final File zip, @NotNull final File restoreDir)
        throws IOException {
    try (ZipFile zipFile = new ZipFile(zip)) {
        final Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            final ZipArchiveEntry zipEntry = zipEntries.nextElement();
            final File entryFile = new File(restoreDir, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                entryFile.mkdirs();//from w  w w . j a  v  a2  s . c  o m
            } else {
                entryFile.getParentFile().mkdirs();
                try (FileOutputStream target = new FileOutputStream(entryFile)) {
                    try (InputStream in = zipFile.getInputStream(zipEntry)) {
                        IOUtil.copyStreams(in, target, IOUtil.BUFFER_ALLOCATOR);
                    }
                }
            }
        }
    }
}

From source file:com.zimbra.cs.util.ZipUtil.java

public static String bestGuessAtEntryName(ZipArchiveEntry zae, Locale locale) {
    GeneralPurposeBit gbp = zae.getGeneralPurposeBit();
    if ((null != gbp) && gbp.usesUTF8ForNames()) {
        return (zae.getName());
    }/*  w  ww  .  j  a v  a 2s.  c  o m*/
    byte[] rawName = zae.getRawName();
    /* First of all, assume UTF-8.  java.util.zip assumes UTF-8 names, so this is a reasonable first
     * guess.  If the name isn't US-ASCII and it isn't UTF-8 there is a reasonable chance this
     * will fail because of the way UTF-8 works - and we can try other charsets.
     */
    String guess = convertBytesIfPossible(rawName, StandardCharsets.UTF_8);
    if (guess != null) {
        return guess;
    }
    guess = getNameFromUnicodeExtraPathIfPresent(zae);
    if (guess != null) {
        return guess;
    }
    List<String> charsetsForLocale = defaultCharsetForLocale.get(locale);
    if (null != charsetsForLocale) {
        for (String charsetForLocale : charsetsForLocale) {
            guess = convertBytesIfPossible(rawName, Charset.forName(charsetForLocale));
            if (guess != null) {
                return guess;
            }
        }
    }
    return zae.getName();
}

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

/**
 * Get a listing of all files in a zip file
 *
 * @param zip The zip file to scan/*  w  w  w .j a v a  2 s .  c o  m*/
 * @param relativePath The relative path where the extraction will be rooted
 * @return The list of paths in {@code zip} sorted by path so dirs come before contents.
 */
private static SortedMap<Path, ZipArchiveEntry> getZipFilePaths(ZipFile zip, Path relativePath,
        PatternsMatcher entriesToExclude) {
    SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>();
    for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) {
        String entryName = entry.getName();
        if (entriesToExclude.matchesAny(entryName)) {
            continue;
        }
        Path target = relativePath.resolve(entryName).normalize();
        pathMap.put(target, entry);
    }
    return pathMap;
}

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

/**
 * Get a listing of all files in a zip file that start with a prefix, ignore others
 *
 * @param zip The zip file to scan//  w  w w .  j av a2  s  . c om
 * @param relativePath The relative path where the extraction will be rooted
 * @param prefix The prefix that will be stripped off.
 * @return The list of paths in {@code zip} sorted by path so dirs come before contents. Prefixes
 *     are stripped from paths in the zip file, such that foo/bar/baz.txt with a prefix of foo/
 *     will be in the map at {@code relativePath}/bar/baz.txt
 */
private static SortedMap<Path, ZipArchiveEntry> getZipFilePathsStrippingPrefix(ZipFile zip, Path relativePath,
        Path prefix, PatternsMatcher entriesToExclude) {
    SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>();
    for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) {
        String entryName = entry.getName();
        if (entriesToExclude.matchesAny(entryName)) {
            continue;
        }
        Path entryPath = Paths.get(entryName);
        if (entryPath.startsWith(prefix)) {
            Path target = relativePath.resolve(prefix.relativize(entryPath)).normalize();
            pathMap.put(target, entry);
        }
    }
    return pathMap;
}

From source file:com.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a ZIP file that's contained in the classpath.
 * @param path path of ZIP resource/* w  w  w. j  av  a  2 s  .c o  m*/
 * @return contents of files within the ZIP
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 * @throws IllegalArgumentException if {@code path} cannot be found, or if zipPaths contains duplicates
 */
public static Map<String, byte[]> readZipFromResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);

    Map<String, byte[]> ret = new LinkedHashMap<>();

    try (InputStream is = url.openStream(); ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) {
        ZipArchiveEntry entry;
        while ((entry = zais.getNextZipEntry()) != null) {
            ret.put(entry.getName(), IOUtils.toByteArray(zais));
        }
    }

    return ret;
}

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

/**
 * Unzips a file to a destination and returns the paths of the written files.
 *///from   w w  w .j  a  v a  2 s .com
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:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

private static MediaType detectKmz(ZipFile zip) {
    boolean kmlFound = false;

    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        String name = entry.getName();
        if (!entry.isDirectory() && name.indexOf('/') == -1 && name.indexOf('\\') == -1) {
            if (name.endsWith(".kml") && !kmlFound) {
                kmlFound = true;/*from w  w  w .  j  a  v a 2s .  c  o m*/
            } else {
                return null;
            }
        }
    }

    if (kmlFound) {
        return MediaType.application("vnd.google-earth.kmz");
    } else {
        return null;
    }
}

From source file:mj.ocraptor.extraction.tika.parser.pkg.ZipContainerDetector.java

@SuppressWarnings("unchecked")
private static MediaType detectIpa(ZipFile zip) {
    // Note - consider generalising this logic, if another format needs many regexp matching
    Set<Pattern> tmpPatterns = (Set<Pattern>) ipaEntryPatterns.clone();

    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        String name = entry.getName();

        Iterator<Pattern> ip = tmpPatterns.iterator();
        while (ip.hasNext()) {
            if (ip.next().matcher(name).matches()) {
                ip.remove();/*from  w w w  .j av  a 2  s  .c  o  m*/
            }
        }
        if (tmpPatterns.isEmpty()) {
            // We've found everything we need to find
            return MediaType.application("x-itunes-ipa");
        }
    }

    // If we get here, not all required entries were found
    return null;
}

From source file:com.android.tradefed.util.ZipUtil2.java

/**
 * A util method to apply unix mode from {@link ZipArchiveEntry} to the created local file
 * system entry if necessary//ww  w .  j av  a  2  s  .co m
 * @param entry the entry inside zipfile (potentially contains mode info)
 * @param localFile the extracted local file entry
 * @throws IOException
 */
private static void applyUnixModeIfNecessary(ZipArchiveEntry entry, File localFile) throws IOException {
    if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX) {
        Files.setPosixFilePermissions(localFile.toPath(), FileUtil.unixModeToPosix(entry.getUnixMode()));
    } else {
        CLog.i("Entry does not contain Unix mode info: %s", entry.getName());
    }
}