List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getEntries
public Enumeration getEntries()
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//from w w w. j a v a2 s . co 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 a va2 s . c o m*/ * @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:divconq.tool.Updater.java
static public boolean tryUpdate() { @SuppressWarnings("resource") final Scanner scan = new Scanner(System.in); FuncResult<RecordStruct> ldres = Updater.loadDeployed(); if (ldres.hasErrors()) { System.out.println("Error reading deployed.json file: " + ldres.getMessage()); return false; }// w w w. j av a 2 s . co m RecordStruct deployed = ldres.getResult(); String ver = deployed.getFieldAsString("Version"); String packfolder = deployed.getFieldAsString("PackageFolder"); String packprefix = deployed.getFieldAsString("PackagePrefix"); if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) { System.out.println("Error reading deployed.json file: Missing Version or PackageFolder"); return false; } if (StringUtil.isEmpty(packprefix)) packprefix = "DivConq"; System.out.println("Current Version: " + ver); Path packpath = Paths.get(packfolder); if (!Files.exists(packpath) || !Files.isDirectory(packpath)) { System.out.println("Error reading PackageFolder - it may not exist or is not a folder."); return false; } File pp = packpath.toFile(); RecordStruct deployment = null; File matchpack = null; for (File f : pp.listFiles()) { if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip")) continue; System.out.println("Checking: " + f.getName()); // if not a match before, clear this deployment = null; try { ZipFile zf = new ZipFile(f); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.getName().equals("deployment.json")) { //System.out.println("crc: " + entry.getCrc()); FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry)); if (pres.hasErrors()) { System.out.println("Error reading deployment.json file"); break; } deployment = (RecordStruct) pres.getResult(); break; } } zf.close(); } catch (IOException x) { System.out.println("Error reading deployment.json file: " + x); } if (deployment != null) { String fndver = deployment.getFieldAsString("Version"); String fnddependson = deployment.getFieldAsString("DependsOn"); if (ver.equals(fnddependson)) { System.out.println("Found update: " + fndver); matchpack = f; break; } } } if ((matchpack == null) || (deployment == null)) { System.out.println("No updates found!"); return false; } String fndver = deployment.getFieldAsString("Version"); String umsg = deployment.getFieldAsString("UpdateMessage"); if (StringUtil.isNotEmpty(umsg)) { System.out.println("========================================================================"); System.out.println(umsg); System.out.println("========================================================================"); } System.out.println(); System.out.println("Do you want to install? (y/n)"); System.out.println(); String p = scan.nextLine().toLowerCase(); if (!p.equals("y")) return false; System.out.println(); System.out.println("Intalling: " + fndver); Set<String> ignorepaths = new HashSet<>(); ListStruct iplist = deployment.getFieldAsList("IgnorePaths"); if (iplist != null) { for (Struct df : iplist.getItems()) ignorepaths.add(df.toString()); } ListStruct dflist = deployment.getFieldAsList("DeleteFiles"); // deleting if (dflist != null) { for (Struct df : dflist.getItems()) { Path delpath = Paths.get(".", df.toString()); if (Files.exists(delpath)) { System.out.println("Deleting: " + delpath.toAbsolutePath()); try { Files.delete(delpath); } catch (IOException x) { System.out.println("Unable to Delete: " + x); } } } } // copying updates System.out.println("Checking for updated files: "); try { @SuppressWarnings("resource") ZipFile zf = new ZipFile(matchpack); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String entryname = entry.getName().replace('\\', '/'); boolean xfnd = false; for (String exculde : ignorepaths) if (entryname.startsWith(exculde)) { xfnd = true; break; } if (xfnd) continue; System.out.print("."); Path localpath = Paths.get(".", entryname); if (entry.isDirectory()) { if (!Files.exists(localpath)) Files.createDirectories(localpath); } else { boolean hashmatch = false; if (Files.exists(localpath)) { String local = null; String update = null; try (InputStream lin = Files.newInputStream(localpath)) { local = HashUtil.getMd5(lin); } try (InputStream uin = zf.getInputStream(entry)) { update = HashUtil.getMd5(uin); } hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update) && local.equals(update)); } if (!hashmatch) { System.out.print("[" + entryname + "]"); try (InputStream uin = zf.getInputStream(entry)) { Files.createDirectories(localpath.getParent()); Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception x) { System.out.println("Error updating: " + entryname + " - " + x); return false; } } } } zf.close(); } catch (IOException x) { System.out.println("Error reading update package: " + x); } // updating local config deployed.setField("Version", fndver); OperationResult svres = Updater.saveDeployed(deployed); if (svres.hasErrors()) { System.out.println("Intalled: " + fndver + " but could not update deployed.json. Repair the file before continuing.\nError: " + svres.getMessage()); return false; } System.out.println("Intalled: " + fndver); return true; }
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. *///from ww w . j a v a 2 s .co m 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: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 . ja v a 2 s. c om } } 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.taobao.android.tpatch.utils.PatchUtils.java
/** * ?so?bundle/*from w w w . j a v a 2 s. c o m*/ * * @param soFile * @return */ public static boolean isBundleFile(File soFile) { ZipFile zf = null; try { zf = new ZipFile(soFile); Enumeration<ZipArchiveEntry> en = zf.getEntries(); if (en.hasMoreElements()) { for (String name : BUNDLE_FILES) { ZipArchiveEntry zipArchiveEntry = zf.getEntry(name); if (null == zipArchiveEntry) { return false; } } return true; } return false; } catch (IOException e) { return false; } finally { if (null != zf) { try { zf.close(); } catch (IOException e) { } } } }
From source file:com.taobao.android.utils.ZipUtils.java
public static List<String> listZipEntries(File zipFile) { List<String> list = new ArrayList<String>(); ZipFile zip; try {/*from w w w. java 2s . c om*/ zip = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> en = zip.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); String name = ze.getName(); list.add(name); } if (null != zip) ZipFile.closeQuietly(zip); } catch (IOException e) { } return list; }
From source file:abfab3d.io.input.ModelLoader.java
/** * Unzip a file into a destination directory * * @param src// w ww . ja va2 s . c om * @param dest */ private static void unzip(File src, File dest) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(src); for (Enumeration e = zipFile.getEntries(); e.hasMoreElements();) { ZipArchiveEntry entry = (ZipArchiveEntry) e.nextElement(); unzipEntry(zipFile, entry, dest); } } finally { if (zipFile != null) zipFile.close(); } }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
/** * <p>//from ww w. j ava2s . co m * isZipFile. * </p> * * @param zipFile a {@link java.io.File} object. * @return a boolean. */ public static boolean isZipFile(File zipFile) { try { ZipFile zf = new ZipFile(zipFile); boolean isZip = zf.getEntries().hasMoreElements(); zf.close(); return isZip; } catch (IOException e) { return false; } }
From source file:com.igormaznitsa.mvngolang.utils.UnpackUtils.java
public static int unpackFileToFolder(@Nonnull final Log logger, @Nullable final String folder, @Nonnull final File archiveFile, @Nonnull final File destinationFolder, final boolean makeAllExecutable) throws IOException { final String normalizedName = archiveFile.getName().toLowerCase(Locale.ENGLISH); final ArchEntryGetter entryGetter; boolean modeZipFile = false; final ZipFile theZipFile; final ArchiveInputStream archInputStream; if (normalizedName.endsWith(".zip")) { logger.debug("Detected ZIP archive"); modeZipFile = true;/*from w w w . ja v a 2 s .co m*/ theZipFile = new ZipFile(archiveFile); archInputStream = null; entryGetter = new ArchEntryGetter() { private final Enumeration<ZipArchiveEntry> iterator = theZipFile.getEntries(); @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { ArchiveEntry result = null; if (this.iterator.hasMoreElements()) { result = this.iterator.nextElement(); } return result; } }; } else { theZipFile = null; final InputStream in = new BufferedInputStream(new FileInputStream(archiveFile)); try { if (normalizedName.endsWith(".tar.gz")) { logger.debug("Detected TAR.GZ archive"); archInputStream = new TarArchiveInputStream(new GZIPInputStream(in)); entryGetter = new ArchEntryGetter() { @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { return ((TarArchiveInputStream) archInputStream).getNextTarEntry(); } }; } else { logger.debug("Detected OTHER archive"); archInputStream = ARCHIVE_STREAM_FACTORY.createArchiveInputStream(in); logger.debug("Created archive stream : " + archInputStream.getClass().getName()); entryGetter = new ArchEntryGetter() { @Override @Nullable public ArchiveEntry getNextEntry() throws IOException { return archInputStream.getNextEntry(); } }; } } catch (ArchiveException ex) { IOUtils.closeQuietly(in); throw new IOException("Can't recognize or read archive file : " + archiveFile, ex); } catch (CantReadArchiveEntryException ex) { IOUtils.closeQuietly(in); throw new IOException("Can't read entry from archive file : " + archiveFile, ex); } } try { final String normalizedFolder = folder == null ? null : FilenameUtils.normalize(folder, true) + '/'; int unpackedFilesCounter = 0; while (true) { final ArchiveEntry entry = entryGetter.getNextEntry(); if (entry == null) { break; } final String normalizedPath = FilenameUtils.normalize(entry.getName(), true); logger.debug("Detected archive entry : " + normalizedPath); if (normalizedFolder == null || normalizedPath.startsWith(normalizedFolder)) { final File targetFile = new File(destinationFolder, normalizedFolder == null ? normalizedPath : normalizedPath.substring(normalizedFolder.length())); if (entry.isDirectory()) { logger.debug("Folder : " + normalizedPath); if (!targetFile.exists() && !targetFile.mkdirs()) { throw new IOException("Can't create folder " + targetFile); } } else { final File parent = targetFile.getParentFile(); if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { throw new IOException("Can't create folder : " + parent); } final FileOutputStream fos = new FileOutputStream(targetFile); try { if (modeZipFile) { logger.debug("Unpacking ZIP entry : " + normalizedPath); final InputStream zipEntryInStream = theZipFile .getInputStream((ZipArchiveEntry) entry); try { if (IOUtils.copy(zipEntryInStream, fos) != entry.getSize()) { throw new IOException( "Can't unpack file, illegal unpacked length : " + entry.getName()); } } finally { IOUtils.closeQuietly(zipEntryInStream); } } else { logger.debug("Unpacking archive entry : " + normalizedPath); if (!archInputStream.canReadEntryData(entry)) { throw new IOException("Can't read archive entry data : " + normalizedPath); } if (IOUtils.copy(archInputStream, fos) != entry.getSize()) { throw new IOException( "Can't unpack file, illegal unpacked length : " + entry.getName()); } } } finally { fos.close(); } if (makeAllExecutable) { try { targetFile.setExecutable(true, true); } catch (SecurityException ex) { throw new IOException("Can't make file executable : " + targetFile, ex); } } unpackedFilesCounter++; } } else { logger.debug("Archive entry " + normalizedPath + " ignored"); } } return unpackedFilesCounter; } finally { IOUtils.closeQuietly(theZipFile); IOUtils.closeQuietly(archInputStream); } }