Example usage for java.util.zip ZipFile stream

List of usage examples for java.util.zip ZipFile stream

Introduction

In this page you can find the example usage for java.util.zip ZipFile stream.

Prototype

public Stream<? extends ZipEntry> stream() 

Source Link

Document

Returns an ordered Stream over the ZIP file entries.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zf = new ZipFile("ziptest.zip");

    Stream<? extends ZipEntry> entryStream = zf.stream();
    entryStream.forEach(entry -> {/*from  w  ww  . j a  v a 2s . c om*/
        try {
            // Get the input stream for the current zip entry
            InputStream is = zf.getInputStream(entry);
            System.out.println(entry.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

    });
}

From source file:com.dclab.preparation.ReadTest.java

public void dig(File folder) {
    File[] files = folder.listFiles();
    Logger.getAnonymousLogger().info("OPENING folder " + folder.getName());
    Map<Boolean, List<File>> isZip = Arrays.stream(files)
            .collect(Collectors.partitioningBy((f -> f.getName().endsWith("zip"))));
    Map<Boolean, List<File>> isFolder = isZip.get(false).stream()
            .collect(Collectors.partitioningBy(f -> f.isDirectory()));
    isFolder.get(false).stream().filter(y -> y.getName().endsWith("xml")).forEach(this::scanFile);
    isFolder.get(true).stream().forEach(this::dig);
    isZip.get(true).stream().forEach(z -> {
        try {//from w w  w  .jav  a  2  s .c om
            ZipFile zipFile = new ZipFile(z);
            zipFile.stream().forEach(ze -> {
                try {
                    String s = handleZip(zipFile, ze);
                    if (s != null) {
                        printLine(s);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            });
        } catch (IOException ex) {
            Logger.getLogger(ReadTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    });

}

From source file:com.redhat.red.koji.build.BuildFinder.java

Set<String> findMissingBuilds(File zipFile, int skipParts) throws IOException, KojiClientException {
    ZipFile zf = new ZipFile(zipFile);
    Logger logger = LoggerFactory.getLogger(getClass());
    final Set<String> missingBuilds = new HashSet<>();

    client.withKojiSession((session) -> {
        zf.stream().parallel().filter((entry) -> !entry.isDirectory()).forEach((entry) -> {
            String entryName = entry.getName();

            if (entryName.endsWith(".md5") || entryName.endsWith(".sha1")
                    || entryName.endsWith("maven-metadata.xml")) {
                logger.debug("Skipping checksum file: {}", entryName);
            } else {
                String[] parts = entryName.split("/");
                if (parts.length > skipParts) {
                    String[] realParts = new String[parts.length - skipParts];
                    System.arraycopy(parts, skipParts, realParts, 0, realParts.length);
                    String path = join(realParts, "/");

                    Boolean foundT_missingF = null;
                    synchronized (missing) {
                        if (missing.contains(path)) {
                            foundT_missingF = false;
                        }/*from  www.  j a  va  2  s . co  m*/
                    }

                    synchronized (found) {
                        if (found.contains(path)) {
                            foundT_missingF = true;
                        }
                    }

                    if (foundT_missingF == null) {
                        ArtifactPathInfo pathInfo = ArtifactPathInfo.parse(path);
                        if (pathInfo != null) {
                            ArtifactRef aref = pathInfo.getArtifact();
                            logger.info("??? {} (trimmed path: '{}', real path: '{}'", aref, path, entryName);
                            try {
                                List<KojiBuildInfo> builds = client.listBuildsContaining(aref, session);
                                if (builds == null || builds.isEmpty()) {
                                    synchronized (missing) {
                                        missing.add(path);
                                    }

                                    synchronized (missingBuilds) {
                                        missingBuilds.add(entryName);
                                    }
                                } else {
                                    synchronized (found) {
                                        found.add(path);
                                    }
                                }
                            } catch (KojiClientException e) {
                                logger.error("Failed to query koji for artifact: " + aref, e);
                            }
                        }
                    } else if (!foundT_missingF) {
                        synchronized (missingBuilds) {
                            missingBuilds.add(entryName);
                        }
                    }
                }
            }
        });

        return null;
    });

    return missingBuilds;
}

From source file:hudson.model.DirectoryBrowserSupportSEC904Test.java

private List<String> getListOfEntriesInDownloadedZip(UnexpectedPage zipPage) throws Exception {
    List<String> result;

    File zipfile = null;/*  www. ja  va2 s .  c om*/
    ZipFile readzip = null;
    try {
        zipfile = download(zipPage);

        readzip = new ZipFile(zipfile);
        result = readzip.stream().map(ZipEntry::getName).collect(Collectors.toList());
    } finally {
        if (readzip != null) {
            readzip.close();
        }
        if (zipfile != null) {
            zipfile.delete();
        }
    }
    return result;
}

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

@Test
public void testBuildJavaLibraryWithoutSrcsAndVerifyAbi() throws IOException, CompressorException {
    setUpProjectWorkspaceForScenario("abi");
    workspace.enableDirCache();//from   w ww .ja va  2s .c  o m

    // Run `buck build`.
    BuildTarget target = BuildTargetFactory.newInstance("//:no_srcs");
    ProcessResult buildResult = workspace.runBuckCommand("build", target.getFullyQualifiedName());
    buildResult.assertSuccess("Successful build should exit with 0.");
    Path outputPath = CompilerOutputPaths.of(target, filesystem).getOutputJarPath().get();
    Path outputFile = workspace.getPath(outputPath);
    assertTrue(Files.exists(outputFile));
    // TODO(mbolin): When we produce byte-for-byte identical JAR files across builds, do:
    //
    //   HashCode hashOfOriginalJar = Files.hash(outputFile, Hashing.sha1());
    //
    // And then compare that to the output when //:no_srcs is built again with --no-cache.
    long sizeOfOriginalJar = Files.size(outputFile);

    // This verifies that the ABI key was written correctly.
    workspace.verify();

    // Verify the build cache.
    Path buildCache = workspace.getPath(filesystem.getBuckPaths().getCacheDir());
    assertTrue(Files.isDirectory(buildCache));

    ArtifactCache dirCache = TestArtifactCaches.createDirCacheForTest(workspace.getDestPath(), buildCache);

    int totalArtifactsCount = DirArtifactCacheTestUtil.getAllFilesInCache(dirCache).size();

    assertEquals("There should be two entries (a zip and metadata) per rule key type (default and input-"
            + "based) in the build cache.", 4, totalArtifactsCount);

    Sha1HashCode ruleKey = workspace.getBuildLog().getRuleKey(target.getFullyQualifiedName());

    // Run `buck clean`.
    ProcessResult cleanResult = workspace.runBuckCommand("clean", "--keep-cache");
    cleanResult.assertSuccess("Successful clean should exit with 0.");

    totalArtifactsCount = getAllFilesInPath(buildCache).size();
    assertEquals("The build cache should still exist.", 4, totalArtifactsCount);

    // Corrupt the build cache!
    Path artifactZip = DirArtifactCacheTestUtil.getPathForRuleKey(dirCache, new RuleKey(ruleKey.asHashCode()),
            Optional.empty());
    HashMap<String, byte[]> archiveContents = new HashMap<>(TarInspector.readTarZst(artifactZip));
    archiveContents.put(outputPath.toString(), emptyJarFile());
    writeTarZst(artifactZip, archiveContents);

    // Run `buck build` again.
    ProcessResult buildResult2 = workspace.runBuckCommand("build", target.getFullyQualifiedName());
    buildResult2.assertSuccess("Successful build should exit with 0.");
    assertTrue(Files.isRegularFile(outputFile));

    ZipFile outputZipFile = new ZipFile(outputFile.toFile());
    assertEquals("The output file will be an empty zip if it is read from the build cache.", 0,
            outputZipFile.stream().count());
    outputZipFile.close();

    // Run `buck clean` followed by `buck build` yet again, but this time, specify `--no-cache`.
    ProcessResult cleanResult2 = workspace.runBuckCommand("clean", "--keep-cache");
    cleanResult2.assertSuccess("Successful clean should exit with 0.");
    ProcessResult buildResult3 = workspace.runBuckCommand("build", "--no-cache",
            target.getFullyQualifiedName());
    buildResult3.assertSuccess();
    outputZipFile = new ZipFile(outputFile.toFile());
    assertNotEquals("The contents of the file should no longer be pulled from the corrupted build cache.", 0,
            outputZipFile.stream().count());
    outputZipFile.close();
    assertEquals(
            "We cannot do a byte-for-byte comparision with the original JAR because timestamps might "
                    + "have changed, but we verify that they are the same size, as a proxy.",
            sizeOfOriginalJar, Files.size(outputFile));
}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static boolean findInZip(final File file, final String prefix, final String suffix) {
    try {// ww w  .ja va2  s . com
        final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

        final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
                .filter(ze -> ze.getName().toLowerCase().endsWith(suffix))
                .filter(ze -> ze.getName().toLowerCase().startsWith(prefix)).findFirst();
        return result.isPresent();
    } catch (Exception e) {
        SystemUtils.LOG.warning("unable to read zip file " + file + ": " + e.getMessage());
    }
    return false;
}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static String getRootFolder(final File file, final String headerFileName) throws IOException {
    final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

    final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
            .filter(ze -> ze.getName().toLowerCase().endsWith(headerFileName)).findFirst();
    if (result.isPresent()) {
        ZipEntry ze = (ZipEntry) result.get();
        String path = ze.toString();
        int sepIndex = path.lastIndexOf('/');
        if (sepIndex > 0) {
            return path.substring(0, sepIndex) + '/';
        } else {/*ww w.j  a v  a2 s .c  om*/
            return "";
        }
    }
    return "";
}

From source file:org.esa.snap.util.ZipUtils.java

public static boolean findInZip(final File file, final String prefix, final String suffix) {
    try {//from   w ww.j a v a  2s. c  o m
        final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

        final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
                .filter(ze -> ze.getName().toLowerCase().endsWith(suffix))
                .filter(ze -> ze.getName().toLowerCase().startsWith(prefix)).findFirst();
        return result.isPresent();
    } catch (Exception e) {
        //
    }
    return false;
}

From source file:org.esa.snap.util.ZipUtils.java

public static String getRootFolder(final File file, final String headerFileName) throws IOException {
    final ZipFile productZip = new ZipFile(file, ZipFile.OPEN_READ);

    final Optional result = productZip.stream().filter(ze -> !ze.isDirectory())
            .filter(ze -> ze.getName().toLowerCase().endsWith(headerFileName)).findFirst();
    ZipEntry ze = (ZipEntry) result.get();
    String path = ze.toString();//from   w  ww.  ja v a 2  s.co m
    int sepIndex = path.lastIndexOf('/');
    if (sepIndex > 0) {
        return path.substring(0, sepIndex) + '/';
    } else {
        return "";
    }
}

From source file:org.wso2.carbon.uuf.internal.io.util.ZipArtifactHandler.java

/**
 * @param zipFile zip app//from  w  ww .java  2 s. c om
 * @return app name
 * @throws FileOperationException I/O error
 */
public static String getAppName(Path zipFile) {
    ZipFile zip = null;
    try {
        zip = new ZipFile(zipFile.toFile());
        ZipEntry firstEntry = zip.stream().findFirst().orElseThrow(() -> new FileOperationException(
                "Cannot find app directory in zip artifact '" + zipFile + "'."));
        if (firstEntry.isDirectory()) {
            return Paths.get(firstEntry.getName()).getFileName().toString();
        } else {
            throw new FileOperationException(
                    "Cannot find an app directory inside the zip artifact '" + zipFile + "'.");
        }
    } catch (IOException e) {
        throw new FileOperationException("An error occurred when opening zip artifact '" + zipFile + "'.", e);
    } finally {
        IOUtils.closeQuietly(zip);
    }
}