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

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

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 .  j  a  va2  s .c  o  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.mirth.connect.util.ArchiveUtils.java

/**
 * Extracts folders/files from a zip archive using zip-optimized code from commons-compress.
 *//*from w  w w  .  j a v a  2s  . c  o m*/
private static void extractZipArchive(File archiveFile, File destinationFolder) throws CompressException {
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        ZipArchiveEntry entry = null;
        byte[] buffer = new byte[BUFFER_SIZE];

        for (; entries.hasMoreElements(); entry = entries.nextElement()) {
            File outputFile = new File(
                    destinationFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR + entry.getName());

            if (entry.isDirectory()) {
                FileUtils.forceMkdir(outputFile);
            } else {
                InputStream inputStream = zipFile.getInputStream(entry);
                OutputStream outputStream = FileUtils.openOutputStream(outputFile);

                try {
                    IOUtils.copyLarge(inputStream, outputStream, buffer);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } catch (Exception e) {
        throw new CompressException(e);
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

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

/**
 * Unzips the files in a ZIP file. Files can be filtered based on their
 * filename, using a regular expression (the matching sense can be inverted).
 *
 * @param input   the ZIP file to unzip//w w  w  .j a va  2  s  .  co m
 * @param outputDir   the directory where to store the extracted files
 * @param createDirs   whether to re-create the directory structure from the
 *          ZIP file
 * @param match   the regular expression that the files are matched against
 * @param invertMatch   whether to invert the matching sense
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      the successfully extracted files
 */
@MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html")
public static List<File> decompress(File input, File outputDir, boolean createDirs, BaseRegExp match,
        boolean invertMatch, int bufferSize, StringBuilder errors) {
    List<File> result;
    ZipFile archive;
    Enumeration<ZipArchiveEntry> enm;
    ZipArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    BufferedInputStream in;
    BufferedOutputStream out;
    FileOutputStream fos;
    int len;
    String error;
    long read;

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

            if (entry.isDirectory() && !createDirs)
                continue;

            // does name match?
            if (!match.isMatchAll() && !match.isEmpty()) {
                if (invertMatch && match.isMatch(entry.getName()))
                    continue;
                else if (!invertMatch && !match.isMatch(entry.getName()))
                    continue;
            }

            // extract
            if (entry.isDirectory() && createDirs) {
                outFile = new File(outputDir.getAbsolutePath() + File.separator + entry.getName());
                if (!outFile.mkdirs()) {
                    error = "Failed to create directory '" + outFile.getAbsolutePath() + "'!";
                    System.err.println(error);
                    errors.append(error + "\n");
                }
            } else {
                in = null;
                out = null;
                fos = null;
                outName = null;
                try {
                    // assemble output name
                    outName = outputDir.getAbsolutePath() + File.separator;
                    if (createDirs)
                        outName += entry.getName();
                    else
                        outName += new File(entry.getName()).getName();

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

                    // extract data
                    in = new BufferedInputStream(archive.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.add(new File(outName));
                } catch (Exception e) {
                    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) {
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

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 w  ww . jav a 2s. com*/
}

From source file:jetbrains.exodus.entitystore.BackupTests.java

@SuppressWarnings("ResultOfMethodCallIgnored")
public static void extractEntireZip(@NotNull final File zip, @NotNull final File restoreDir)
        throws IOException {
    try (ZipFile zipFile = new ZipFile(zip)) {
        final Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            final ZipArchiveEntry zipEntry = zipEntries.nextElement();
            final File entryFile = new File(restoreDir, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                entryFile.mkdirs();//from  ww w  . j  a v a2 s .  co  m
            } else {
                entryFile.getParentFile().mkdirs();
                try (FileOutputStream target = new FileOutputStream(entryFile)) {
                    try (InputStream in = zipFile.getInputStream(zipEntry)) {
                        IOUtil.copyStreams(in, target, IOUtil.BUFFER_ALLOCATOR);
                    }
                }
            }
        }
    }
}

From source file:com.facebook.buck.zip.ZipStepTest.java

/**
 * Tests a couple bugs:/* w  ww.j  ava 2  s  . c  om*/
 *     1) {@link com.facebook.buck.zip.OverwritingZipOutputStream} was writing uncompressed zip
 *        entries incorrectly.
 *     2) {@link ZipStep} wasn't setting the output size when writing uncompressed entries.
 */
@Test
public void minCompressionWritesCorrectZipFile() throws IOException {
    Path parent = tmp.newFolder("zipstep");
    Path out = parent.resolve("output.zip");

    Path toZip = tmp.newFolder("zipdir");
    byte[] contents = "hello world".getBytes();
    Files.write(toZip.resolve("file1.txt"), contents);
    Files.write(toZip.resolve("file2.txt"), contents);
    Files.write(toZip.resolve("file3.txt"), contents);

    ZipStep step = new ZipStep(filesystem, Paths.get("zipstep/output.zip"), ImmutableSet.of(), false,
            ZipCompressionLevel.MIN_COMPRESSION_LEVEL, Paths.get("zipdir"));
    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    // Use apache's common-compress to parse the zip file, since it reads the central
    // directory and will verify it's valid.
    try (ZipFile zip = new ZipFile(out.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        ZipArchiveEntry entry1 = entries.nextElement();
        assertArrayEquals(contents, ByteStreams.toByteArray(zip.getInputStream(entry1)));
        ZipArchiveEntry entry2 = entries.nextElement();
        assertArrayEquals(contents, ByteStreams.toByteArray(zip.getInputStream(entry2)));
        ZipArchiveEntry entry3 = entries.nextElement();
        assertArrayEquals(contents, ByteStreams.toByteArray(zip.getInputStream(entry3)));
    }
}

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();//from  w w w.  j  av 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:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java

@Test
public void shouldOnlyUnpackContentsOfZipSources() throws IOException {
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
    workspace.setUp();/*from   w  w w.jav  a 2  s  .  com*/

    Path zip = workspace.buildAndReturnOutput("//example:zipsources");

    try (ZipFile zipFile = new ZipFile(zip.toFile())) {
        ZipInspector inspector = new ZipInspector(zip);
        inspector.assertFileDoesNotExist("taco.txt");
    }
}

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

/**
 * Indicates the number of files (not directories) inside the archive.
 *
 * @param archive the archive whose content is analyzed.
 * @return the number of files (not directories) inside the archive.
 *//*from   ww  w  . ja  va2 s .c o m*/
public static int getNbFiles(File archive) {
    ZipFile zipFile = null;
    int nbFiles = 0;
    try {
        zipFile = new ZipFile(archive);
        @SuppressWarnings("unchecked")
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry ze = entries.nextElement();
            if (!ze.isDirectory()) {
                nbFiles++;
            }
        }
    } catch (IOException ioe) {
        SilverTrace.warn("util", "ZipManager.getNbFiles()", "util.EXE_ERROR_WHILE_COUNTING_FILE",
                "sourceFile = " + archive.getPath(), ioe);
    } finally {
        if (zipFile != null) {
            ZipFile.closeQuietly(zipFile);
        }
    }
    return nbFiles;
}

From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java

@Test
public void shouldExcludeFromRegularZip() throws IOException {
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
    workspace.setUp();//from   www  .  j  a  v  a 2  s .  co m

    Path zip = workspace.buildAndReturnOutput("//example:exclude_from_zip");

    try (ZipFile zipFile = new ZipFile(zip.toFile())) {
        ZipInspector inspector = new ZipInspector(zip);
        inspector.assertFileDoesNotExist("cake.txt");
    }
}