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:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java

@Test
public void testZipDirectory() throws Exception {
    FileUtils.forceMkdir(new File("target/Z-testfiles/source"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/CP0-input.csv"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/CP1-input.csv"));

    String aTargetFilename = "target/Z2-input.zip";
    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:target/Z-testfiles/source/");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(3)).incrementReadCount();
    verify(aStepContribution, times(3)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/CP1-input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java

@Test
public void testZipDirectories() throws Exception {
    FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/CP0-input.csv"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/Z-testfiles/source/subdir/CP1-input.csv"));

    String aTargetFilename = "target/Z3-input.zip";
    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/"));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:target/Z-testfiles/source/");
    aTasklet.setSourceFactory(aSourceFactory);
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory);

    assertFalse(new File(aTargetFilename).exists());

    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(4)).incrementReadCount();
    verify(aStepContribution, times(4)).incrementWriteCount(1);

    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/CP0-input.csv", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/subdir", aEntries.nextElement().getName());
    assertTrue(aEntries.hasMoreElements());
    assertEquals("source/subdir/CP1-input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();
}

From source file:cn.vlabs.clb.server.utils.UnCompress.java

public void unzip(File file) {
    ZipFile zipfile = null;
    try {/*from   w  w  w .  j  a  va 2  s .c om*/
        if (encoding == null)
            zipfile = new ZipFile(file);
        else
            zipfile = new ZipFile(file, encoding);
        Enumeration<ZipArchiveEntry> iter = zipfile.getEntries();
        while (iter.hasMoreElements()) {
            ZipArchiveEntry entry = iter.nextElement();
            if (!entry.isDirectory()) {
                InputStream entryis = null;
                try {
                    entryis = zipfile.getInputStream(entry);
                    listener.onNewEntry(new ZipEntryAdapter(entry, zipfile));
                } finally {
                    IOUtils.closeQuietly(entryis);
                }
            }
        }
    } catch (ZipException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error("file not found " + e.getMessage(), e);
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Compares the content of two zip files. The zip files are considered equal, if
 * the content of all zip entries is equal to the content of its corresponding entry
 * in the other zip file.//from ww w.java 2  s  .co m
 *
 * @author S3460
 * @param zipSource the zip source
 * @param resultZip the result zip
 * @throws Exception the exception
 */
private void compareFiles(ZipFile zipSource, ZipFile resultZip) throws Exception {
    boolean rc = false;
    try {
        for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
            ZipArchiveEntry sourceEntry = enumer.nextElement();
            ZipArchiveEntry resultEntry = resultZip.getEntry(sourceEntry.getName());
            assertNotNull("Entry nicht generiert: " + sourceEntry.getName(), resultEntry);
            byte[] oldBytes = toBytes(zipSource, sourceEntry);
            byte[] newBytes = toBytes(resultZip, resultEntry);
            rc = equal(oldBytes, newBytes);
            assertTrue("bytes the same " + sourceEntry, rc);
        }
    } finally {
        zipSource.close();
        resultZip.close();
    }
}

From source file:io.selendroid.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();
    File tempdir = new File(FileUtils.getTempDirectoryPath() + File.separatorChar + targetPackageName
            + System.currentTimeMillis());

    if (!tempdir.exists()) {
        tempdir.mkdirs();/*from w  w w  . ja va  2  s .co m*/
    }

    File customizedManifest = new File(tempdir, "AndroidManifest.xml");
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(
            new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk"));
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk");
    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:com.silverpeas.util.ZipManagerTest.java

/**
* Test of compressPathToZip method, of class ZipManager.
*
* @throws Exception/*from   w ww .java2s.c  om*/
*/
@Test
public void testCompressPathToZip() throws Exception {
    String path = PathTestUtil.TARGET_DIR + "test-classes" + separatorChar + "ZipSample";
    String outfilename = PathTestUtil.TARGET_DIR + "temp" + separatorChar + "testCompressPathToZip.zip";
    ZipManager.compressPathToZip(path, outfilename);
    ZipFile zipFile = new ZipFile(new File(outfilename), 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:io.selendroid.standalone.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();

    File tmpDir = Files.createTempDir();
    if (deleteTmpFiles()) {
        tmpDir.deleteOnExit();//  ww w . j a  v a  2  s .  c o m
    }

    File customizedManifest = new File(tmpDir, "AndroidManifest.xml");
    if (deleteTmpFiles()) {
        customizedManifest.deleteOnExit();
    }
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    File manifestApkFile = File.createTempFile("manifest", ".apk");
    if (deleteTmpFiles()) {
        manifestApkFile.deleteOnExit();
    }

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(manifestApkFile.getAbsolutePath(), false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(manifestApkFile);
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = File.createTempFile("selendroid-server", ".apk");
    if (deleteTmpFiles()) {
        finalSelendroidServerFile.deleteOnExit();
    }

    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:autoupdater.FileDAO.java

/**
 * Unzips a zip archive.//from w ww . j av a  2  s  .c  o  m
 *
 * @param zip the zipfile to unzip
 * @param fileLocationOnDiskToDownloadTo the folder to unzip in
 * @return true if successful
 * @throws IOException
 */
public boolean unzipFile(ZipFile zip, File fileLocationOnDiskToDownloadTo) throws IOException {
    FileOutputStream dest = null;
    InputStream inStream = null;
    Enumeration<ZipArchiveEntry> zipFileEnum = zip.getEntries();
    while (zipFileEnum.hasMoreElements()) {
        ZipArchiveEntry entry = zipFileEnum.nextElement();
        File destFile = new File(fileLocationOnDiskToDownloadTo, entry.getName());
        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                throw new IOException("could not create the folders to unzip in");
            }
        }
        if (!entry.isDirectory()) {
            try {
                dest = new FileOutputStream(destFile);
                inStream = zip.getInputStream(entry);
                IOUtils.copyLarge(inStream, dest);
            } finally {
                if (dest != null) {
                    dest.close();
                }
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            if (!destFile.exists()) {
                if (!destFile.mkdirs()) {
                    throw new IOException("could not create folders to unzip file");
                }
            }
        }
    }
    zip.close();
    return true;
}

From source file:com.naryx.tagfusion.expression.function.file.ZipList.java

private cfQueryResultData performZiplist(cfSession session, File zipfile, String charset) throws IOException {
    ZipFile zFile = null;
    try {//from w  w  w  . java  2s  .c o m
        cfQueryResultData filesQuery = new cfQueryResultData(new String[] { "name", "type", "compressedsize",
                "size", "compressedpercent", "datelastmodified", "comment" }, "CFZIP");
        zFile = new ZipFile(zipfile, charset);

        List<Map<String, cfData>> allResultRows = new ArrayList<Map<String, cfData>>();
        Map<String, cfData> resultRow;
        Enumeration<? extends ZipArchiveEntry> files = zFile.getEntries();
        ZipArchiveEntry nextEntry = null;
        long size;
        double compressed;

        while (files.hasMoreElements()) {
            nextEntry = (ZipArchiveEntry) files.nextElement();
            resultRow = new FastMap<String, cfData>(8);
            resultRow.put("name", new cfStringData(nextEntry.getName()));
            resultRow.put("comment", new cfStringData(nextEntry.getComment()));
            resultRow.put("datelastmodified", new cfDateData(nextEntry.getTime()));

            if (nextEntry.isDirectory()) {
                resultRow.put("compressedsize", new cfNumberData(0));
                resultRow.put("size", new cfNumberData(0));
                resultRow.put("type", new cfStringData("Dir"));
                resultRow.put("compressedpercent", new cfNumberData(0));

            } else {
                size = nextEntry.getSize();
                resultRow.put("compressedsize",
                        new cfStringData(String.valueOf(nextEntry.getCompressedSize())));
                resultRow.put("size", new cfStringData(String.valueOf(size)));
                resultRow.put("type", new cfStringData("File"));
                if (size != 0) {
                    compressed = ((float) nextEntry.getCompressedSize() / (float) size);
                    resultRow.put("compressedpercent",
                            new cfStringData(String.valueOf(100 - (int) (compressed * 100))));
                } else {
                    resultRow.put("compressedpercent", new cfStringData("0"));
                }
            }

            allResultRows.add(resultRow);
        }
        filesQuery.populateQuery(allResultRows);
        return filesQuery;
    } finally {
        try {
            zFile.close();
        } catch (IOException ignored) {
        }
    }
}

From source file:adams.core.io.ZipUtils.java

/**
 * Unzips the specified file from a ZIP file.
 *
 * @param input   the ZIP file to unzip/* w  ww .ja v  a2 s .co m*/
 * @param archiveFile   the file from the archive to extract
 * @param output   the name of the output file
 * @param createDirs   whether to create the directory structure represented
 *          by output file
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      whether file was successfully extracted
 */
public static boolean decompress(File input, String archiveFile, File output, boolean createDirs,
        int bufferSize, StringBuilder errors) {
    boolean result;
    ZipFile zipfile;
    Enumeration<ZipArchiveEntry> enm;
    ZipArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    BufferedInputStream in;
    BufferedOutputStream out;
    FileOutputStream fos;
    int len;
    String error;
    long read;

    result = false;
    zipfile = null;
    try {
        // unzip archive
        buffer = new byte[bufferSize];
        zipfile = new ZipFile(input.getAbsoluteFile());
        enm = zipfile.getEntries();
        while (enm.hasMoreElements()) {
            entry = enm.nextElement();

            if (entry.isDirectory())
                continue;
            if (!entry.getName().equals(archiveFile))
                continue;

            in = null;
            out = null;
            fos = null;
            outName = null;
            try {
                // output name
                outName = output.getAbsolutePath();

                // create directory, if necessary
                outFile = new File(outName).getParentFile();
                if (!outFile.exists()) {
                    if (!createDirs) {
                        error = "Output directory '" + outFile.getAbsolutePath() + " does not exist', "
                                + "skipping extraction of '" + outName + "'!";
                        System.err.println(error);
                        errors.append(error + "\n");
                        break;
                    } else {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            break;
                        }
                    }
                }

                // extract data
                in = new BufferedInputStream(zipfile.getInputStream(entry));
                fos = new FileOutputStream(outName);
                out = new BufferedOutputStream(fos, bufferSize);
                read = 0;
                while (read < entry.getSize()) {
                    len = in.read(buffer);
                    read += len;
                    out.write(buffer, 0, len);
                }

                result = true;
                break;
            } catch (Exception e) {
                result = false;
                error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                System.err.println(error);
                errors.append(error + "\n");
            } finally {
                FileUtils.closeQuietly(in);
                FileUtils.closeQuietly(out);
                FileUtils.closeQuietly(fos);
            }
        }
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}