Example usage for org.apache.commons.compress.archivers.zip ZipFile close

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile close

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the archive.

Usage

From source file:org.obm.sync.ObmSyncArchiveUtils.java

private static File[] replaceServiceJar(File[] asFile) {
    return FluentIterable.from(Arrays.asList(asFile)).transform(new Function<File, File>() {

        @Override//  w  w w  .  j ava  2s.  c o m
        public File apply(File input) {
            if (input.getName().contains("services-module")) {
                ZipFile servicesZip = null;
                try {
                    File outputFile = File.createTempFile("services-module", ".jar");
                    servicesZip = new ZipFile(input);

                    ChangeSet changeSet = new ChangeSet();
                    changeSet.add(new JarArchiveEntry("META-INF/MANIFEST.MF"),
                            ClassLoader.getSystemClassLoader().getResourceAsStream("MANIFEST.MF"));
                    ChangeSetPerformer changeSetPerformer = new ChangeSetPerformer(changeSet);
                    JarArchiveOutputStream jarArchiveOutputStream = new JarArchiveOutputStream(
                            new FileOutputStream(outputFile));
                    changeSetPerformer.perform(servicesZip, jarArchiveOutputStream);
                    return outputFile;
                } catch (IOException e) {
                    Throwables.propagate(e);
                } finally {
                    try {
                        if (servicesZip != null) {
                            servicesZip.close();
                        }
                    } catch (IOException e) {
                        Throwables.propagate(e);
                    }
                }
            }
            return input;
        }
    }).toArray(File.class);
}

From source file:org.opentestsystem.authoring.testitembank.service.impl.ApipZipInputFileExtractorService.java

@Override
public final ApipZipFileContent extractData(final File zippedFile) {
    final ApipZipFileContent zipContent = new ApipZipFileContent();
    try {/*from  ww w. jav a  2s.  c o m*/
        final ZipFile zip = new ZipFile(zippedFile);
        final HashMap<String, ZipArchiveEntry> mappedEntries = getMappedZipFileEntries(zip);
        final ApipManifest manifest = extractManifest(zip, mappedEntries);
        zipContent.setManifest(manifest);
        zipContent.setItemMetadata(getApipItemMetadata(zip, mappedEntries, manifest));
        zipContent.setItemContentMap(getItemZipMap(manifest, zip, mappedEntries));
        zip.close();
    } catch (final IOException e) {
        throw new TestItemBankException("zip.io.error", e);
    }

    return zipContent;
}

From source file:org.sead.nds.repository.BagGenerator.java

private void validateBagFile(File bagFile) throws IOException {
    // Run a confirmation test - should verify all files and hashes
    ZipFile zf = new ZipFile(bagFile);
    // Check files calculates the hashes and file sizes and reports on
    // whether hashes are correct
    // The file sizes are added to totalDataSize which is compared with the
    // stats sent in the request
    checkFiles(sha1Map, zf);//  w ww .j  a  v  a  2 s.  co  m

    log.info("Data Count: " + dataCount);
    log.info("Data Size: " + totalDataSize);
    // Check stats
    if (pubRequest.getJSONObject("Aggregation Statistics").getLong("Number of Datasets") != dataCount) {
        log.warn("Request contains incorrect data count: should be: " + dataCount);
    }
    // Total size is calced during checkFiles
    if (pubRequest.getJSONObject("Aggregation Statistics").getLong("Total Size") != totalDataSize) {
        log.warn("Request contains incorrect Total Size: should be: " + totalDataSize);
    }

    zf.close();
}

From source file:org.silverpeas.core.util.ZipUtilTest.java

/**
* Test of compressPathToZip method, of class ZipManager.
*
* @throws Exception/*from  w w  w.j av  a2s. co  m*/
*/
@Test
public void testCompressPathToZip(MavenTestEnv mavenTestEnv) throws Exception {
    File path = new File(mavenTestEnv.getResourceTestDirFile(), "ZipSample");
    File outfile = new File(tempDir, "testCompressPathToZip.zip");
    ZipUtil.compressPathToZip(path, outfile);
    ZipFile zipFile = new ZipFile(outfile, CharEncoding.UTF_8);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.getEntries();
        assertThat(zipFile.getEncoding(), is(CharEncoding.UTF_8));
        int nbEntries = 0;
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            nbEntries++;
        }
        assertThat(nbEntries, is(5));
        assertThat(zipFile.getEntry("ZipSample/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2b/simple.txt"), is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2a/simple.txt"), is(notNullValue()));

        ZipEntry accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/s\u00efmplifi\u00e9.txt");
        if (accentuatedEntry == null) {
            accentuatedEntry = zipFile.getEntry("ZipSample/level1/level2a/"
                    + new String("smplifi.txt".getBytes("UTF-8"), Charset.defaultCharset()));
        }
        assertThat(accentuatedEntry, is(notNullValue()));
        assertThat(zipFile.getEntry("ZipSample/level1/level2c/"), is(nullValue()));
    } finally {
        zipFile.close();
    }
}

From source file:org.silverpeas.core.util.ZipUtilTest.java

/**
* Test of compressStreamToZip method, of class ZipManager.
*
* @throws Exception//from  w w w . j av a2  s .c om
*/
@Test
public void testCompressStreamToZip() throws Exception {
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("FrenchScrum.odp");
    String filePathNameToCreate = separatorChar + "dir1" + separatorChar + "dir2" + separatorChar
            + "FrenchScrum.odp";
    File outfile = new File(tempDir, "testCompressStreamToZip.zip");
    ZipUtil.compressStreamToZip(inputStream, filePathNameToCreate, outfile.getPath());
    inputStream.close();
    assertThat(outfile, is(notNullValue()));
    assertThat(outfile.exists(), is(true));
    assertThat(outfile.isFile(), is(true));
    int result = ZipUtil.getNbFiles(outfile);
    assertThat(result, is(1));
    ZipFile zipFile = new ZipFile(outfile);
    assertThat(zipFile.getEntry("/dir1/dir2/FrenchScrum.odp"), is(notNullValue()));
    zipFile.close();
}

From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java

@Override
public <T> T each(Processor<T> processor) throws Exception {
    T result = null;//from  w  w w  . j  ava  2s .co m
    ZipFile zip = new ZipFile(zipDownload.getFile());
    try {
        Enumeration<ZipArchiveEntry> iter = zip.getEntries();
        while (iter.hasMoreElements() && result == null) {
            ZipArchiveEntry el = iter.nextElement();
            Path zipPath = new Path(el.getName());
            if (root.isPrefixOf(zipPath)) {
                String key = zipPath.removeFirstSegments(root.segmentCount()).toString();
                if ("".equals(key)) {
                    //path maches exactly, this means we hit the root of the
                    // code set. Do not store it because the root of a codeset
                    // is not actually an element of the codeset!
                } else {
                    CodeSetEntry cse = csEntry(zip, el);
                    result = processor.doit(cse);
                    if (result != null) {
                        //Bail out early when result found
                        return result;
                    }
                }
            }
        }
        return result;
    } finally {
        try {
            zip.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java

@Override
public <T> T readFileEntry(String path, Processor<T> processor) throws Exception {
    ZipFile zip = new ZipFile(zipDownload.getFile());
    try {/*from w w  w .  ja  v  a 2s .c o  m*/
        String entryName = root.append(path).toString();
        ZipArchiveEntry entry = zip.getEntry(entryName);
        return processor.doit(entry == null ? null : csEntry(zip, entry));
    } finally {
        try {
            zip.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.xwiki.contrib.maven.PackageExtensionsMojo.java

private Collection<String> getJarsIncludedInWar(Artifact web) throws IOException, MojoExecutionException {
    if (web == null) {
        return Collections.emptyList();
    }/*from   w  ww  . j  av  a2s.c  om*/

    getLog().info(String.format("Excluding Base WAR [%s:%s].", web.getGroupId(), web.getArtifactId()));

    Collection<String> jars = new ArrayList<>();

    // TODO: replace this by a a method which look to the POM of the WAR
    // Open the war and list all the jars
    ZipFile zipFile = new ZipFile(web.getFile());
    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        String entryName = entries.nextElement().getName();
        if (entryName.startsWith(JAR_DIRECTORY) && entryName.endsWith(".jar")) {
            jars.add(entryName.substring(JAR_DIRECTORY.length()));
        }
    }
    zipFile.close();

    return jars;
}

From source file:org.xwiki.filemanager.internal.job.PackJobTest.java

@Test
public void pack() throws Exception {
    Folder projects = mockFolder("Projects", "Pr\u00F4j\u00EA\u00E7\u021B\u0219", null,
            Arrays.asList("Concerto", "Resilience"), Arrays.asList("key.pub"));
    File key = mockFile("key.pub", "Projects");
    when(fileSystem.canView(key.getReference())).thenReturn(false);

    mockFolder("Concerto", "Projects", Collections.<String>emptyList(), Arrays.asList("pom.xml"));
    File pom = mockFile("pom.xml", "m&y p?o#m.x=m$l", "Concerto");
    setFileContent(pom, "foo");

    Folder resilience = mockFolder("Resilience", "Projects", Arrays.asList("src"), Arrays.asList("build.xml"));
    when(fileSystem.canView(resilience.getReference())).thenReturn(false);
    mockFolder("src", "Resilience");
    mockFile("build.xml");

    File readme = mockFile("readme.txt", "r\u00E9\u00E0dm\u00E8.txt");
    setFileContent(readme, "blah");

    PackRequest request = new PackRequest();
    request.setPaths(Arrays.asList(new Path(projects.getReference()), new Path(null, readme.getReference())));
    request.setOutputFileReference(//from  w ww. j  av a2s . co m
            new AttachmentReference("out.zip", new DocumentReference("wiki", "Space", "Page")));

    PackJob job = (PackJob) execute(request);

    ZipFile zip = new ZipFile(
            new java.io.File(testFolder.getRoot(), "temp/filemanager/wiki/Space/Page/out.zip"));
    List<String> folders = new ArrayList<String>();
    Map<String, String> files = new HashMap<String, String>();
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            folders.add(entry.getName());
        } else if (zip.canReadEntryData(entry)) {
            StringWriter writer = new StringWriter();
            IOUtils.copy(zip.getInputStream(entry), writer);
            files.put(entry.getName(), writer.toString());
        }
    }
    zip.close();

    assertEquals(Arrays.asList(projects.getName() + '/', projects.getName() + "/Concerto/"), folders);
    assertEquals(2, files.size());
    assertEquals("blah", files.get(readme.getName()));
    assertEquals("foo", files.get(projects.getName() + "/Concerto/" + pom.getName()));
    assertEquals(("blah" + "foo").getBytes().length, job.getStatus().getBytesWritten());
    assertTrue(job.getStatus().getOutputFileSize() > 0);
}

From source file:org.xwiki.filter.test.internal.ZIPFileAssertComparator.java

private static Map<String, byte[]> unzip(File filename) throws IOException {
    Map<String, byte[]> zipContent = new HashMap<String, byte[]>();

    ZipFile zipFile = new ZipFile(filename);

    try {// w w  w . j av  a2 s .  c o  m
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            InputStream inputStream = zipFile.getInputStream(entry);
            try {
                zipContent.put(entry.getName(), IOUtils.toByteArray(inputStream));
            } finally {
                inputStream.close();
            }
        }
    } finally {
        zipFile.close();
    }

    return zipContent;
}