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:org.opencastproject.util.ZipUtilTest.java

@Test
public void zipNoRecFileFile() throws Exception {

    File destFile = new File(destDir, "noRecFileFile.zip");

    Vector<String> names = new Vector<String>();
    names.add(srcFileName);//from  w w w  .  j  a v  a  2s  .c  o  m
    names.add(nestedSrcFileName);

    File test = ZipUtil.zip(new File[] { srcFile, nestedSrcFile, nestedSrcDir }, destFile, false,
            ZipUtil.NO_COMPRESSION);
    Assert.assertTrue(test.exists());
    ZipFile zip = new ZipFile(test);
    Assert.assertEquals(2, zip.size());
    Enumeration<? extends ZipEntry> entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Assert.assertTrue(names.contains(entry.getName()));
        }
    } catch (AssertionError ae) {
        zip.close();
        throw ae;
    }

    zip.close();
}

From source file:org.opencastproject.util.ZipUtilTest.java

@Test
public void zipNoRecStrStr() throws Exception {

    File destFile = new File(destDir, "noRecStrStr.zip");

    Vector<String> names = new Vector<String>();
    names.add(srcFileName);/*from   w  ww.  j av  a  2s . c  o m*/
    names.add(nestedSrcFileName);

    File test = ZipUtil.zip(
            new String[] { srcFile.getCanonicalPath(), nestedSrcFile.getCanonicalPath(),
                    nestedSrcDir.getCanonicalPath() },
            destFile.getCanonicalPath(), false, ZipUtil.NO_COMPRESSION);
    Assert.assertTrue(test.exists());
    ZipFile zip = new ZipFile(test);
    Assert.assertEquals(2, zip.size());
    Enumeration<? extends ZipEntry> entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Assert.assertTrue(names.contains(entry.getName()));
        }
    } catch (AssertionError ae) {
        zip.close();
        throw ae;
    }

    zip.close();
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void removeResource() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE);

    container.addResource("Soup for everyone", "soup.txt", "text/plain");

    container.addResource("Sub-folder entry 1", "sub/1.txt", "text/plain");
    container.addResource("Sub-folder entry 2", "sub/2.txt", "text/plain");
    container.addResource("Sub-folder entry 2", "sub/3/woho.txt", "text/plain");

    assertTrue(container.listAllResources().keySet().contains("soup.txt"));
    container.removeResource("soup.txt");
    assertFalse(container.listAllResources().keySet().contains("soup.txt"));

    try {//ww w  .  j a  v  a2 s. com
        container.getResourceAsString("soup.txt");
        fail("Could still retrieve soup.txt");
    } catch (Exception ex) {
        // OK
    }

    container.save(tmpFile);
    // reload
    UCFPackage container2 = new UCFPackage(tmpFile);

    assertTrue(container2.listAllResources().keySet().contains("sub/"));
    container2.removeResource("sub"); // should not work
    assertTrue(container2.listAllResources().keySet().contains("sub/"));
    assertTrue(container2.listAllResources().keySet().contains("sub/1.txt"));

    container2.removeResource("sub/");
    assertFalse(container2.listAllResources().keySet().contains("sub/"));
    assertFalse(container2.listAllResources().keySet().contains("sub/1.txt"));

    container2.save(tmpFile);

    ZipFile zipFile = new ZipFile(tmpFile);
    assertNull("soup.txt still in zip file", zipFile.getEntry("soup.txt"));
    assertNull("sub/1.txt still in zip file", zipFile.getEntry("sub/1.txt"));
    assertNull("sub/2.txt still in zip file", zipFile.getEntry("sub/2.txt"));
    assertNull("sub/3.txt still in zip file", zipFile.getEntry("sub/3.txt"));
    assertNull("sub/ still in zip file", zipFile.getEntry("sub/"));
    zipFile.close();

    UCFPackage loaded = new UCFPackage(tmpFile);
    assertFalse(loaded.listAllResources().keySet().contains("soup.txt"));
    assertFalse(loaded.listAllResources().keySet().contains("sub/"));
    assertFalse(loaded.listAllResources().keySet().contains("sub/1.txt"));

    try {
        loaded.getResourceAsString("sub/1.txt");
        fail("Could still retrieve soup.txt");
    } catch (Exception ex) {
        // OK
    }
    loaded.save(tmpFile);
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipDownload.java

@Override
public DownloadJob call() {
    final File src = getZipFile();

    if (src.isDirectory()) {
        return this;
    }//w ww . jav  a 2s .c om

    ZipFile zf = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        zf = isJarOperation() ? new JarFile(src) : new ZipFile(src);

        final ZipEntry entry = zf.getEntry(getFullPath());
        if (entry != null) {
            if (entry.isDirectory()) {
                error = new TransferException("Cannot read stream. Source is a directory: %s!%s",
                        getLocation().getUri(), getFullPath());
            } else {
                in = zf.getInputStream(entry);
                out = getTransfer().openOutputStream(TransferOperation.DOWNLOAD, true, eventMetadata);

                copy(in, out);

                return this;
            }
        } else {
            error = new TransferException("Cannot find entry: %s in: %s", getFullPath(),
                    getLocation().getUri());
        }
    } catch (final IOException e) {
        error = new TransferException("Failed to copy from: %s to: %s. Reason: %s", e, src, getTransfer(),
                e.getMessage());
    } finally {
        closeQuietly(in);
        if (zf != null) {
            //noinspection EmptyCatchBlock
            try {
                zf.close();
            } catch (final IOException e) {
            }
        }

        closeQuietly(out);
    }

    if (error != null) {
        logger.error("Failed to download: {}. Reason: {}", this, error);
    }

    return null;
}

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

@Override
protected File doInBackground() throws Exception {
    ZipFile zip = new ZipFile(source);
    parseResourceTable();/*  www  .  j  a v  a 2s  .c o  m*/
    if (filenames == null) {
        Enumeration<? extends ZipEntry> e = zip.entries();
        Vector<String> tmp = new Vector<String>();
        while (e.hasMoreElements()) {
            tmp.add(e.nextElement().getName());
        }
        filenames = tmp;
    }

    for (String filename : filenames) {
        ZipEntry entry = zip.getEntry(filename);
        InputStream in = zip.getInputStream(entry);
        OutputStream out = openDestination(filename);

        if (isBinaryXml(filename)) {
            XmlTranslator xmlTranslator = new XmlTranslator();
            ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
            BinaryXmlParser binaryXmlParser = new BinaryXmlParser(buffer, resourceTable);
            binaryXmlParser.setLocale(Locale.getDefault());
            binaryXmlParser.setXmlStreamer(xmlTranslator);
            binaryXmlParser.parse();
            IOUtils.write(xmlTranslator.getXml(), out);
        } else {
            // Simply extract
            IOUtils.copy(in, out);
        }
        in.close();
        out.close();
    }

    zip.close();
    return dest;
}

From source file:org.wso2.developerstudio.eclipse.updater.core.UpdateManager.java

/**
 * Extracts a jar file to a given directory.
 * //from  www.j  ava2  s  .c  om
 * @param jar
 *            Source jar file.
 * @param extractpath
 *            Destination to extract.
 * 
 * @throws IOException
 */
private void extractJar(File jar, File extractpath) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(extractpath, 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();
    }
}

From source file:org.docx4j.openpackaging.io3.stores.ZipPartStore.java

public ZipPartStore(File f) throws Docx4JException {
    log.info("Filepath = " + f.getPath());

    ZipFile zf = null;
    try {// w w  w  . j a  v a 2 s.co m
        if (!f.exists()) {
            log.info("Couldn't find " + f.getPath());
        }
        zf = new ZipFile(f);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new Docx4JException("Couldn't get ZipFile", ioe);
    }

    partByteArrays = new HashMap<String, ByteArray>();
    Enumeration entries = zf.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        //log.info( "\n\n" + entry.getName() + "\n" );
        InputStream in = null;
        try {
            byte[] bytes = getBytesFromInputStream(zf.getInputStream(entry));
            partByteArrays.put(entry.getName(), new ByteArray(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // At this point, we've finished with the zip file
    try {
        zf.close();
    } catch (IOException exc) {
        exc.printStackTrace();
    }
}

From source file:com.isomorphic.maven.packaging.Distribution.java

/**
 * Extract the relevant contents from each file in the distribution.  Additionally creates ZIP/JAR
 * files from specified resources (e.g., javadoc).
 * //  ww  w  .j  a  va2 s  .  co m
 * @param to The directory to which each file should be extracted.
 * @throws IOException
 */
public void unpack(File to) throws IOException {

    outer: for (File file : files) {

        String ext = FilenameUtils.getExtension(file.getName()).toUpperCase();

        //copy uncompressed files to target, renaming as necessary per 'contents' configuration
        if (!"ZIP".equals(ext)) {
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(file.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(file.getName(), filterEntry.getKey()));
                    FileUtils.copyFile(file, target);
                    LOGGER.debug("Copied file '{}' to file '{}'", file.getName(), target.getAbsolutePath());
                    continue outer;
                }
            }
            FileUtils.copyFileToDirectory(file, new File(to, "lib"));
            continue outer;
        }

        //otherwise extract contents (again renaming / relocating contents as necessary)
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zip.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            for (Map.Entry<String, AntPathMatcherFilter> filterEntry : content.entrySet()) {
                AntPathMatcherFilter filter = filterEntry.getValue();
                if (filter.accept(entry.getName())) {
                    File target = FileUtils.getFile(to,
                            ArchiveUtils.rewritePath(entry.getName(), filterEntry.getKey()));
                    FileUtils.copyInputStreamToFile(zip.getInputStream(entry), target);
                    LOGGER.debug("Copied input stream to file '{}'", target.getAbsolutePath());
                }
            }
        }
        zip.close();
    }

    /*
     * Create any number of assemblies by dropping their resources here.
     * Each subdirectory will get zipped up and then deleted
     */
    File assembliesDir = new File(to, "assembly");

    @SuppressWarnings("unchecked")
    Collection<File> assemblies = CollectionUtils.arrayToList(assembliesDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File arg0) {
            return arg0.isDirectory();
        }
    }));
    for (File assembly : assemblies) {
        String name = FilenameUtils.getBaseName(assembly.getName());
        LOGGER.debug("Copying resources for assembly '{}'", name);
        ArchiveUtils.zip(assembly, FileUtils.getFile(assembliesDir, name + ".zip"));
        FileUtils.deleteQuietly(assembly);
    }

    LOGGER.debug("Repackaging Javadoc...");
    File docLib = new File(to, "doc/lib");

    //TODO these paths should probably all be stuck in some constant
    File client = FileUtils.getFile(to, "doc/api/client");
    if (client.exists()) {
        ArchiveUtils.jar(client, new File(docLib, "smartgwt-javadoc.jar"));
    }

    File server = FileUtils.getFile(to, "doc/api/server");
    if (server.exists()) {
        ArchiveUtils.jar(server, new File(docLib, "isomorphic-javadoc.jar"));
    }
}

From source file:org.mozilla.gecko.AboutHomeContent.java

private String readFromZipFile(Activity activity, String filename) {
    ZipFile zip = null;
    String str = null;// w w  w .  jav  a2s .  c o  m
    try {
        InputStream fileStream = null;
        File applicationPackage = new File(activity.getApplication().getPackageResourcePath());
        zip = new ZipFile(applicationPackage);
        if (zip == null)
            return null;
        ZipEntry fileEntry = zip.getEntry(filename);
        if (fileEntry == null)
            return null;
        fileStream = zip.getInputStream(fileEntry);
        str = readStringFromStream(fileStream);
    } catch (IOException ioe) {
        Log.e(LOGTAG, "error reading zip file: " + filename, ioe);
    } finally {
        try {
            if (zip != null)
                zip.close();
        } catch (IOException ioe) {
            // catch this here because we can continue even if the
            // close failed
            Log.e(LOGTAG, "error closing zip filestream", ioe);
        }
    }
    return str;
}

From source file:org.apache.tika.parser.odf.OpenDocumentParser.java

public void parse(InputStream stream, ContentHandler baseHandler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {

    // Open the Zip stream
    // Use a File if we can, and an already open zip is even better
    ZipFile zipFile = null;
    ZipInputStream zipStream = null;
    if (stream instanceof TikaInputStream) {
        TikaInputStream tis = (TikaInputStream) stream;
        Object container = ((TikaInputStream) stream).getOpenContainer();
        if (container instanceof ZipFile) {
            zipFile = (ZipFile) container;
        } else if (tis.hasFile()) {
            zipFile = new ZipFile(tis.getFile());
        } else {//from   ww w .  j  a v a2s  .  c  o  m
            zipStream = new ZipInputStream(stream);
        }
    } else {
        zipStream = new ZipInputStream(stream);
    }

    // Prepare to handle the content
    XHTMLContentHandler xhtml = new XHTMLContentHandler(baseHandler, metadata);

    // As we don't know which of the metadata or the content
    //  we'll hit first, catch the endDocument call initially
    EndDocumentShieldingContentHandler handler = new EndDocumentShieldingContentHandler(xhtml);

    if (zipFile != null) {
        try {
            handleZipFile(zipFile, metadata, context, handler);
        } finally {
            //Do we want to close silently == catch an exception here?
            zipFile.close();
        }
    } else {
        try {
            handleZipStream(zipStream, metadata, context, handler);
        } finally {
            //Do we want to close silently == catch an exception here?
            zipStream.close();
        }
    }

    // Only now call the end document
    if (handler.getEndDocumentWasCalled()) {
        handler.reallyEndDocument();
    }
}