Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

private static Game getFromCache(String cacheName) throws FileNotFoundException, IOException {
    File f = new File("archive.zip");
    logger.log(Level.FINEST, "Loading file {0} from cache", cacheName);
    if (f.exists()) {
        try (ZipFile file = new ZipFile(f)) {
            ZipEntry entry = file.getEntry(cacheName);
            if (entry != null) {
                try (InputStream stream = file.getInputStream(entry)) {
                    return readGameFromStream(stream);
                }/*from www  . j ava2s  . co  m*/
            }
        }
    }
    return null;
}

From source file:com.cloudant.sync.datastore.DatastoreSchemaTests.java

@SuppressWarnings("ResultOfMethodCallIgnored") // mkdirs result should be fine
private boolean unzipToDirectory(File zipPath, File outputDirectory) {
    try {//from www.  j a v  a  2s.  c o  m

        ZipFile zipFile = new ZipFile(zipPath);
        try {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(outputDirectory, entry.getName());
                if (entry.isDirectory())
                    entryDestination.mkdirs();
                else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = zipFile.getInputStream(entry);
                    OutputStream out = new FileOutputStream(entryDestination);
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    out.close();
                }
            }
        } finally {
            zipFile.close();
        }

        return true;

    } catch (Exception ex) {
        return false;
    }
}

From source file:com.thoughtworks.go.util.ZipUtilTest.java

@Test
void shouldPreserveFileTimestampWhileGeneratingTheZipFile() throws Exception {
    File file = temporaryFolder.newFile("foo.txt");
    file.setLastModified(1297989100000L); // Set this to any date in the past which is greater than the epoch
    File zip = zipUtil.zip(file, temporaryFolder.newFile("foo.zip"), Deflater.DEFAULT_COMPRESSION);

    ZipFile actualZip = new ZipFile(zip.getAbsolutePath());
    ZipEntry entry = actualZip.getEntry(file.getName());

    assertThat(entry.getTime()).isEqualTo(file.lastModified());
}

From source file:org.nebulaframework.core.job.archive.GridArchive.java

/**
 * Detects all classes inside the given {@code .nar} file and returns an
 * array of fully qualified class name of each class, as {@code String}.
 * /* w w w .  jav a 2 s .c  om*/
 * @param file
 *            {@code .nar File}
 * 
 * @return Fully qualified class names classes in {@code File}
 * 
 * @throws IOException
 *             if occurred during File I/O operations
 */
protected static String[] getAllClassNames(File file) throws IOException {

    // Holds Class Names
    List<String> names = new ArrayList<String>();

    // Create ZipArchive for File
    ZipFile archive = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = archive.entries();

    // Read each entry in archive
    while (entries.hasMoreElements()) {

        ZipEntry entry = entries.nextElement();

        // Ignore Directories
        if (entry.isDirectory())
            continue;

        // Ignore content in NEBULA-INF
        if (entry.getName().startsWith(GridArchive.NEBULA_INF)) {
            continue;
        }

        // Add each file which is a valid class file to list
        if (isClass(entry.getName())) {
            names.add(toClassName(entry.getName()));
        }
    }
    return names.toArray(new String[] {});
}

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

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

    // 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:dpfmanager.shell.modules.client.core.ClientService.java

private boolean unzipFileIntoDirectory(File file, File dest) {
    try {/*  www  . j a v a 2  s.  c o m*/
        ZipFile zipFile = new ZipFile(file);
        Enumeration files = zipFile.entries();
        while (files.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) files.nextElement();
            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            File f = new File(dest.getAbsolutePath() + File.separator + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(f);

            while ((bytesRead = eis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
        }
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Add a file to the path. This classloader reads the manifest, if
 * available, and adds any additional class path jars specified in the
 * manifest.//  w w  w  .  java 2s.  c o  m
 *
 * @param pathComponent the file which is to be added to the path for
 *                      this class loader
 *
 * @throws IOException if data needed from the file cannot be read.
 */
public void addPathFile(File pathComponent) throws IOException {
    pathComponents.addElement(pathComponent);

    if (pathComponent.isDirectory()) {
        return;
    }

    String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-"
            + pathComponent.length();
    String classpath = pathMap.get(absPathPlusTimeAndLength);
    if (classpath == null) {
        ZipFile jarFile = null;
        InputStream manifestStream = null;
        try {
            jarFile = new ZipFile(pathComponent);
            manifestStream = jarFile.getInputStream(new ZipEntry("META-INF/MANIFEST.MF"));

            if (manifestStream == null) {
                return;
            }
            Manifest manifest = new Manifest(manifestStream);
            classpath = manifest.getMainAttributes().getValue("Class-Path");

        } finally {
            if (manifestStream != null) {
                manifestStream.close();
            }
            if (jarFile != null) {
                jarFile.close();
            }
        }
        if (classpath == null) {
            classpath = "";
        }
        pathMap.put(absPathPlusTimeAndLength, classpath);
    }

    if (!"".equals(classpath)) {
        URL baseURL = pathComponent.toURL();
        StringTokenizer st = new StringTokenizer(classpath);
        while (st.hasMoreTokens()) {
            String classpathElement = st.nextToken();
            URL libraryURL = new URL(baseURL, classpathElement);
            if (!libraryURL.getProtocol().equals("file")) {
                logger.fine("Skipping jar library " + classpathElement
                        + " since only relative URLs are supported by this" + " loader");
                continue;
            }
            File libraryFile = new File(libraryURL.getFile());
            if (libraryFile.exists() && !isInPath(libraryFile)) {
                addPathFile(libraryFile);
            }
        }
    }
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

@Around("execution(* brut.androlib.Androlib.buildUnknownFiles(..))" + "&& args(appDir, outFile, meta)")
public void buildUnknownFiles_around(File appDir, File outFile, Map<String, Object> meta) throws Throwable {
    if (meta.containsKey("unknownFiles")) {
        LogHelper.info("Copying unknown files/dir...");

        Map<String, String> files = (Map<String, String>) meta.get("unknownFiles");
        File tempFile = File.createTempFile("buildUnknownFiles", "tmp", outFile.getParentFile());
        tempFile.delete();/*from   www. j  a va  2s .c om*/
        boolean renamed = outFile.renameTo(tempFile);
        if (!renamed) {
            throw new AndrolibException("Unable to rename temporary file");
        }

        try (ZipFile inputFile = new ZipFile(tempFile);
                FileOutputStream fos = new FileOutputStream(outFile);
                ZipOutputStream actualOutput = new ZipOutputStream(fos)) {
            copyExistingFiles(inputFile, actualOutput, files);
            copyUnknownFiles(appDir, actualOutput, files);
        } catch (IOException ex) {
            throw new AndrolibException(ex);
        } finally {
            // Remove our temporary file.
            tempFile.delete();
        }
    }
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private boolean isJarArchive(File file) {
    boolean isArchive = true;
    ZipFile zipFile = null;/*from www  . j  a v a 2  s  .  co m*/

    try {
        zipFile = new ZipFile(file);
    } catch (ZipException zipCurrupted) {
        isArchive = false;
    } catch (IOException anyIOError) {
        isArchive = false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ignored) {
            }
        }
    }

    return isArchive;
}

From source file:com.netspective.commons.xml.ParseContext.java

public InputSource createInputSource(File jarFile, ZipEntry jarFileEntry)
        throws FileNotFoundException, IOException {
    this.sourceFile = jarFile;
    this.sourceJarEntry = jarFileEntry;
    this.sourceJarFile = new ZipFile(jarFile);

    InputStream stream = sourceJarFile.getInputStream(jarFileEntry);
    if (stream != null) {
        InputSource inputSource = new InputSource(stream);
        inputSource.setSystemId(sourceJarFile.getName() + "!" + jarFileEntry.getName());

        this.inputSrcTracker = new FileTracker();
        ((FileTracker) this.inputSrcTracker).setFile(jarFile);
        if (parentSrcTracker != null)
            this.inputSrcTracker.setParent(parentSrcTracker);

        return inputSource;
    } else/*from   w w  w .ja v  a 2 s.co  m*/
        throw new FileNotFoundException("Zip entry '" + jarFileEntry.getName() + "' not found in zip file '"
                + jarFile.getAbsolutePath() + "'.");
}