Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

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

@Test
public void testBuildJavaLibraryWithoutSrcsAndVerifyAbi() throws IOException, CompressorException {
    setUpProjectWorkspaceForScenario("abi");
    workspace.enableDirCache();/* ww w  .j ava2 s .  com*/

    // 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.nosphere.honker.deptree.DepTreeFilesLoader.java

private List<DepTreeData.SomeFile> loadFilesFromZip(File zipFile) {
    ZipFile zip = null;
    try {/*from  w ww.  ja va 2 s. c o  m*/
        zip = new ZipFile(zipFile, ZipFile.OPEN_READ);
        List<DepTreeData.SomeFile> files = new ArrayList<>();
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String basename = StringUtils.substringAfterLast(entry.getName(), "/");
            String extension = FilenameUtils.getExtension(basename);
            if (!StringUtils.isEmpty(extension)) {
                basename = FilenameUtils.removeExtension(basename);
            }
            basename = basename.toLowerCase();
            if (BASENAMES.contains(basename)) {
                InputStream fileStream = zip.getInputStream(entry);
                try {
                    String content = IOUtils.toString(fileStream, "UTF-8");
                    files.add(new DepTreeData.SomeFile(basename, entry.getName(), content));
                } finally {
                    IOUtils.closeQuietly(fileStream);
                }
            }
        }
        return files;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException ignored) {
                // Ignored
            }
        }
    }
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

/**
 * @deprecated//from w  w  w  .j  a v a 2s.  c  o  m
 */
public void getGeneManiaData() {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            String directoryPath = DirectorySettings.getCacheDirectory().getAbsolutePath();
            if (!(new File(directoryPath + "/done.txt")).exists()) {
                URL pathToGMData = WebResources.GENEMANIA_DATA_URL;
                System.out.println("Downloding GeneMania data from " + pathToGMData.toString());
                try {
                    if (true) {
                        throw new IOException(
                                "Temporarily preventing gm data from downloading. Because it's so large it should only be downloaded once and on demand");
                    }
                    File data = RemoteFileCache.getCacheFile(pathToGMData);
                    System.out.println("data is" + data.getAbsolutePath());
                    ZipFile zipData = new ZipFile(data.getAbsolutePath());
                    Enumeration entries = zipData.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = (ZipEntry) entries.nextElement();
                        if (entry.isDirectory()) {
                            (new File(directoryPath + "/" + entry.getName())).mkdirs();
                            continue;
                        }
                        //System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipData.getInputStream(entry), new BufferedOutputStream(
                                new FileOutputStream(directoryPath + "/" + entry.getName())));
                    }
                    zipData.close();
                    FileWriter fstream = new FileWriter(directoryPath + "/done.txt");
                    BufferedWriter out = new BufferedWriter(fstream);
                    out.write("This file indicates that the GeneMANIA data has finished downloading.");
                    out.close();
                } catch (IOException ex) {
                    Logger.getLogger(AppController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    };
    Thread t = new Thread(r);
    t.start();
}

From source file:org.pentaho.webpackage.deployer.archive.impl.UrlTransformer.java

boolean canHandleZipFile(File file) {
    ZipFile zipFile = null;

    try {/*www .  j a  va2s  .c  o  m*/
        zipFile = new ZipFile(file);

        // exclude real jar files
        // (we only accept the jar extension because of exploded bundles (jardir))
        if (zipFile.getEntry("META-INF/MANIFEST.MF") != null) {
            return false;
        }

        ZipInputStream zipInputStream = null;

        try {
            zipInputStream = new ZipInputStream(new FileInputStream(file));

            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                final String name = FilenameUtils.getName(entry.getName());
                if (name.equals(WebPackageURLConnection.PACKAGE_JSON)) {
                    return true;
                }
            }
        } catch (IOException ignored) {
            // Ignore
        } finally {
            try {
                if (zipInputStream != null) {
                    zipInputStream.close();
                }
            } catch (IOException ignored) {
                // Ignore
            }
        }
    } catch (IOException ignored) {
        // Ignore
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ignored) {
                // Ignore
            }
        }
    }

    return false;
}

From source file:org.roda.common.certification.ODFSignatureUtils.java

public static String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    String result = "Passed";
    ZipFile zipFile = new ZipFile(input.toString());
    Enumeration<?> enumeration;
    for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) enumeration.nextElement();
        String entryName = entry.getName();
        if (META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entryName)) {
            InputStream zipStream = zipFile.getInputStream(entry);
            InputSource inputSource = new InputSource(zipStream);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            try {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(inputSource);
                NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                for (int i = 0; i < signatureNodeList.getLength(); i++) {
                    Node signatureNode = signatureNodeList.item(i);
                    verifyCertificates(input, signatureNode);
                }//from w  w  w . ja v  a 2s  . c  om
            } catch (ParserConfigurationException | SAXException e) {
                result = "Signatures document can not be parsed";
            } catch (CertificateExpiredException e) {
                result = "Contains expired certificates";
            } catch (CertificateRevokedException e) {
                result = "Contains revoked certificates";
            } catch (CertificateNotYetValidException e) {
                result = "Contains certificates not yet valid";
            } catch (MarshalException | XMLSignatureException e) {
                result = "Digital signatures are not valid";
            }

            IOUtils.closeQuietly(zipStream);
        }
    }

    zipFile.close();
    return result;
}

From source file:ch.jamiete.hilda.plugins.PluginManager.java

/**
 * Attempts to load plugin data from the {@code plugin.json} file.
 * @param file/*  w ww .  j  ava 2s . co m*/
 * @return the plugin data or {@code null} if no data could be loaded
 * @throws IllegalArgumentException if any of the conditions of a plugin data file are not met
 */
private PluginData loadPluginData(final File file) {
    PluginData data = null;

    try {
        final ZipFile zipFile = new ZipFile(file);
        final Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final InputStream stream = zipFile.getInputStream(entry);

            if (entry.getName().equals("plugin.json")) {
                data = new Gson().fromJson(IOUtils.toString(stream, Charset.defaultCharset()),
                        PluginData.class);

                Sanity.nullCheck(data.name, "A plugin must define its name.");
                Sanity.nullCheck(data.mainClass, "A plugin must define its main class.");
                Sanity.nullCheck(data.version, "A plugin must define its version.");
                Sanity.nullCheck(data.author, "A plugin must define its author.");

                data.pluginFile = file;

                if (data.dependencies == null) {
                    data.dependencies = new String[0];
                }
            }
        }

        zipFile.close();
    } catch (final Exception ex) {
        Hilda.getLogger().log(Level.SEVERE,
                "Encountered exception when trying to load plugin JSON for " + file.getName(), ex);
    }

    return data;
}

From source file:org.sakaiproject.nakamura.importer.ImportSiteArchiveServlet.java

/**
 * {@inheritDoc}//from   ww w  . j a  v  a  2 s  . c o m
 * 
 * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
 *      org.apache.sling.api.SlingHttpServletResponse)
 */
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException {
    final RequestParameter siteParam = request.getRequestParameter("site");
    if (siteParam == null || !siteParam.getString().startsWith("/")) {
        final String errorMessage = "A site must be specified, and it must be an absolute path pointing to a site.";
        sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage, new IllegalArgumentException(errorMessage),
                response);
        return;
    }
    final String sitePath = siteParam.getString();

    final RequestParameter[] files = request.getRequestParameters("Filedata");
    if (files == null || files.length < 1) {
        final String errorMessage = "Missing Filedata parameter.";
        sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage, new IllegalArgumentException(errorMessage),
                response);
        return;
    }
    final Session session = request.getResourceResolver().adaptTo(Session.class);
    for (RequestParameter p : files) {
        LOG.info("Processing file: " + p.getFileName() + ": " + p.getContentType() + ": " + p.getSize()
                + " bytes");
        try {
            // create temporary local file of zip contents
            final File tempZip = File.createTempFile("siteArchive", ".zip");
            tempZip.deleteOnExit(); // just in case
            final InputStream in = p.getInputStream();
            final FileOutputStream out = new FileOutputStream(tempZip);
            final byte[] buf = new byte[4096];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            // process the zip file
            ZipFile zip = null;
            try {
                zip = new ZipFile(tempZip);
            } catch (ZipException e) {
                sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                        "Invalid zip file: " + p.getFileName() + ": " + p.getContentType() + ": " + p.getSize(),
                        null, response);
            }
            if (zip != null) {
                for (ZipEntry entry : Collections.list(zip.entries())) {
                    if (entry.getName().startsWith("__MACOSX") || entry.getName().endsWith(".DS_Store")) {
                        ; // skip entry
                    } else {
                        if ("content.xml".equals(entry.getName())) {
                            processContentXml(zip.getInputStream(entry), sitePath, session, zip);
                        }
                    }
                }
                zip.close();
            }
            // delete temporary file
            if (tempZip.delete()) {
                LOG.debug("{}: temporary zip file deleted.", tempZip.getAbsolutePath());
            } else {
                LOG.warn("Could not delete temporary file: {}", tempZip.getAbsolutePath());
            }
        } catch (IOException e) {
            sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage(), e, response);
        } catch (XMLStreamException e) {
            sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getLocalizedMessage(), e, response);
        }
    }
    response.setStatus(HttpServletResponse.SC_OK);
    return;
}

From source file:com.ning.maven.plugins.duplicatefinder.ClasspathDescriptor.java

private void addArchive(File element) throws IOException {
    if (addCached(element)) {
        return;//w w w .j ava  2s  .c o m
    }

    List classes = new ArrayList();
    List resources = new ArrayList();
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(element);
        Enumeration entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                String name = entry.getName();

                if ("class".equals(FilenameUtils.getExtension(name))) {
                    String className = FilenameUtils.removeExtension(name).replace('/', '.').replace('\\', '.');

                    classes.add(className);
                    addClass(className, element);
                } else {
                    String resourcePath = name.replace('\\', File.separatorChar);

                    resources.add(resourcePath);
                    addResource(resourcePath, element);
                }
            }
        }

        CACHED_BY_ELEMENT.put(element, new Cached(classes, resources));
    } finally {
        // IOUtils has no closeQuietly for Closable in the 1.x series.
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException ex) {
                // ignored
            }
        }
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * ZIPZIPdescFileName//w  w  w.j  av a  2 s.  c  om
 * 
 * @param zipFileName ?ZIP
 * @param descFileName 
 */
public static boolean unZipFiles(String zipFileName, String descFileName) {
    String descFileNames = descFileName;
    if (!descFileNames.endsWith(File.separator)) {
        descFileNames = descFileNames + File.separator;
    }
    try {
        // ?ZIPZipFile
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipEntry entry = null;
        String entryName = null;
        String descFileDir = null;
        byte[] buf = new byte[4096];
        int readByte = 0;
        // ?ZIPentry
        @SuppressWarnings("rawtypes")
        Enumeration enums = zipFile.entries();
        // ??entry
        while (enums.hasMoreElements()) {
            entry = (ZipEntry) enums.nextElement();
            // entry??
            entryName = entry.getName();
            descFileDir = descFileNames + entryName;
            if (entry.isDirectory()) {
                // entry
                new File(descFileDir).mkdirs();
                continue;
            } else {
                // entry
                new File(descFileDir).getParentFile().mkdirs();
            }
            File file = new File(descFileDir);
            // ?
            OutputStream os = new FileOutputStream(file);
            // ZipFileentry?
            InputStream is = zipFile.getInputStream(entry);
            while ((readByte = is.read(buf)) != -1) {
                os.write(buf, 0, readByte);
            }
            os.close();
            is.close();
        }
        zipFile.close();
        log.debug("?!");
        return true;
    } catch (Exception e) {
        log.debug("" + e.getMessage());
        return false;
    }
}

From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java

private List unzip(String zip, String destination) {
    List destLs = new ArrayList();
    Enumeration entries;/*w  ww  .  j av a2  s  .c o  m*/
    ZipFile zipFile;
    File dest = new File(destination);
    dest.mkdir();
    if (dest.isDirectory()) {

        try {
            zipFile = new ZipFile(zip);

            entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();

                if (entry.isDirectory()) {

                    (new File(dest.getAbsolutePath() + File.separator + entry.getName())).mkdirs();
                    continue;
                }

                if (entry.getName().lastIndexOf("/") > 0) {
                    File f = new File(dest.getAbsolutePath() + File.separator
                            + entry.getName().substring(0, entry.getName().lastIndexOf("/")));
                    f.mkdirs();
                }
                copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                        new FileOutputStream(dest.getAbsolutePath() + File.separator + entry.getName())));
                destLs.add(dest.getAbsolutePath() + File.separator + TMP_UNZIP_DIR + File.separator
                        + entry.getName());
            }

            zipFile.close();
        } catch (IOException e) {
            deleteDir(new File(destination));
            LOGGER.error(e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } else {
        LOGGER.info("There is already a file by that name");
    }
    return destLs;
}