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

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

Introduction

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

Prototype

public ZipArchiveEntry getEntry(String name) 

Source Link

Document

Returns a named entry - or null if no entry by that name exists.

Usage

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

@Test
public void testShouldBeAbleToCreateCustomizedAndroidApplicationXML() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilder();
    builder.init(new DefaultAndroidApp(new File(APK_FILE)));
    builder.cleanUpPrebuildServer();//w w w . j  av a2 s .c  o  m
    File file = builder.createAndAddCustomizedAndroidManifestToSelendroidServer();
    ZipFile zipFile = new ZipFile(file);
    ZipArchiveEntry entry = zipFile.getEntry("AndroidManifest.xml");
    Assert.assertEquals(entry.getName(), "AndroidManifest.xml");
    Assert.assertTrue("Expecting non empty AndroidManifest.xml file", entry.getSize() > 700);

    // Verify that apk is not yet signed
    CommandLine cmd = new CommandLine(AndroidSdk.aapt());
    cmd.addArgument("list", false);
    cmd.addArgument(builder.getSelendroidServer().getAbsolutePath(), false);

    String output = ShellCommand.exec(cmd);

    assertResultDoesNotContainFile(output, "META-INF/CERT.RSA");
    assertResultDoesNotContainFile(output, "META-INF/CERT.SF");
}

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

/**
* Test of compressStreamToZip method, of class ZipManager.
*
* @throws Exception/*from w w w . ja  v  a  2  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";
    String outfilename = PathTestUtil.TARGET_DIR + "temp" + separatorChar + "testCompressStreamToZip.zip";
    ZipManager.compressStreamToZip(inputStream, filePathNameToCreate, outfilename);
    inputStream.close();
    File file = new File(outfilename);
    assertThat(file, is(notNullValue()));
    assertThat(file.exists(), is(true));
    assertThat(file.isFile(), is(true));
    int result = ZipManager.getNbFiles(new File(outfilename));
    assertThat(result, is(1));
    ZipFile zipFile = new ZipFile(file);
    assertThat(zipFile.getEntry("/dir1/dir2/FrenchScrum.odp"), is(notNullValue()));
    zipFile.close();
}

From source file:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java

/**
 * Import the collections in the zip file.
 * /*from w w w .ja  v a 2  s  .c om*/
 * @see edu.ur.ir.ir_import.CollectionImportService#importCollections(java.io.File)
 */
public void importCollections(File zipFile, Repository repository) {
    if (log.isDebugEnabled()) {
        log.debug("import collections");
    }
    try {
        ZipFile zip = new ZipFile(zipFile);
        ZipArchiveEntry entry = zip.getEntry("collection.xml");
        File f = new File("collection.xml");
        zipHelper.getZipEntry(f, entry, zip);
        if (f != null) {
            try {
                getCollections(f, repository, zip);
            } catch (DuplicateNameException e) {
                log.error(e);
            }
            FileUtils.deleteQuietly(f);
        }

    } catch (IOException e) {
        log.error(e);
    }

}

From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

private static void _testJarsDiff(File warFile1, File warFile2) throws IOException {
    DifferenceCalculator differenceCalculator = new DifferenceCalculator(warFile1, warFile2);

    differenceCalculator.setFilenameRegexToIgnore(Collections.singleton(".*META-INF.*"));
    differenceCalculator.setIgnoreTimestamps(true);

    Differences differences = differenceCalculator.getDifferences();

    if (!differences.hasDifferences()) {
        return;// w w w  . j a  v a2 s  .co m
    }

    StringBuilder message = new StringBuilder();

    message.append("WAR ");
    message.append(warFile1);
    message.append(" and ");
    message.append(warFile2);
    message.append(" do not match:");
    message.append(System.lineSeparator());

    boolean realChange;

    Map<String, ZipArchiveEntry> added = differences.getAdded();
    Map<String, ZipArchiveEntry[]> changed = differences.getChanged();
    Map<String, ZipArchiveEntry> removed = differences.getRemoved();

    if (added.isEmpty() && !changed.isEmpty() && removed.isEmpty()) {
        realChange = false;

        ZipFile zipFile1 = null;
        ZipFile zipFile2 = null;

        try {
            zipFile1 = new ZipFile(warFile1);
            zipFile2 = new ZipFile(warFile2);

            for (Map.Entry<String, ZipArchiveEntry[]> entry : changed.entrySet()) {
                ZipArchiveEntry[] zipArchiveEntries = entry.getValue();

                ZipArchiveEntry zipArchiveEntry1 = zipArchiveEntries[0];
                ZipArchiveEntry zipArchiveEntry2 = zipArchiveEntries[0];

                if (zipArchiveEntry1.isDirectory() && zipArchiveEntry2.isDirectory()
                        && (zipArchiveEntry1.getSize() == zipArchiveEntry2.getSize())
                        && (zipArchiveEntry1.getCompressedSize() <= 2)
                        && (zipArchiveEntry2.getCompressedSize() <= 2)) {

                    // Skip zipdiff bug

                    continue;
                }

                try (InputStream inputStream1 = zipFile1
                        .getInputStream(zipFile1.getEntry(zipArchiveEntry1.getName()));
                        InputStream inputStream2 = zipFile2
                                .getInputStream(zipFile2.getEntry(zipArchiveEntry2.getName()))) {

                    List<String> lines1 = StringTestUtil.readLines(inputStream1);
                    List<String> lines2 = StringTestUtil.readLines(inputStream2);

                    message.append(System.lineSeparator());

                    message.append("--- ");
                    message.append(zipArchiveEntry1.getName());
                    message.append(System.lineSeparator());

                    message.append("+++ ");
                    message.append(zipArchiveEntry2.getName());
                    message.append(System.lineSeparator());

                    Patch<String> diff = DiffUtils.diff(lines1, lines2);

                    for (Delta<String> delta : diff.getDeltas()) {
                        message.append('\t');
                        message.append(delta.getOriginal());
                        message.append(System.lineSeparator());

                        message.append('\t');
                        message.append(delta.getRevised());
                        message.append(System.lineSeparator());
                    }
                }

                realChange = true;

                break;
            }
        } finally {
            ZipFile.closeQuietly(zipFile1);
            ZipFile.closeQuietly(zipFile2);
        }
    } else {
        realChange = true;
    }

    Assert.assertFalse(message.toString(), realChange);
}

From source file:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java

/**
 * Add the primary picture to the collection.
 * //ww w  .  j  a va 2  s .c o m
 * @param primaryPicture
 * @param c
 * @param repository
 * @param zip
 */
private void addPrimaryPicture(String primaryPicture, InstitutionalCollection c, Repository repository,
        ZipFile zip) {
    File f = new File(primaryPicture);
    ZipArchiveEntry entry = zip.getEntry(primaryPicture);
    zipHelper.getZipEntry(f, entry, zip);
    IrFile picture;
    try {
        picture = repositoryService.createIrFile(repository, f, primaryPicture,
                "primary news picture for collection id = " + c.getId());
        c.setPrimaryPicture(picture);
    } catch (IllegalFileSystemNameException e) {
        log.error(e);
    }

    if (!FileUtils.deleteQuietly(f)) {
        log.error("file " + f + " not deleted");
    }
}

From source file:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java

/**
 * Add a single picture to the collection.
 * //ww  w.j a  v a2s . c  o m
 * @param picture
 * @param c
 * @param repository
 * @param zip
 */
private void addPicture(String picture, InstitutionalCollection c, Repository repository, ZipFile zip) {
    if (picture != null) {
        File f = new File(picture);
        ZipArchiveEntry entry = zip.getEntry(picture);
        zipHelper.getZipEntry(f, entry, zip);
        IrFile thePicture;
        try {
            thePicture = repositoryService.createIrFile(repository, f, picture,
                    "primary news picture for collection id = " + c.getId());
            c.addPicture(thePicture);
        } catch (IllegalFileSystemNameException e) {
            log.error(e);
        }

        if (!FileUtils.deleteQuietly(f)) {
            log.error("file " + f + " not deleted");
        }
    }
}

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();//  w w  w .  j  av  a2s  .  c  om
    }

    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:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Tests JarDelta and JarPatcher on two identical files.
 *
 * @throws Exception the exception/*w  ww  .j a  va 2  s. c o  m*/
 */
@Test
public void testJarPatcherIdentFile() throws Exception {
    ZipFile originalZip = makeSourceZipFile(sourceFile);
    new JarDelta().computeDelta(sourceFile.getAbsolutePath(), sourceFile.getAbsolutePath(), originalZip,
            originalZip, new ZipArchiveOutputStream(new FileOutputStream(patchFile)));
    ZipFile patch = new ZipFile(patchFile);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        patch.close();
        throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found");
    }
    BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = patchlist.readLine();
    String sourceName = next;
    next = patchlist.readLine();
    ZipFile source = new ZipFile(sourceFile);
    new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, source,
            new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist);
    compareFiles(new ZipFile(sourceFile), new ZipFile(resultFile));
}

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

/**
 * Run jar patcher./*w ww  .  j  a  v a2  s.c  o m*/
 *
 * @param originalName the original name
 * @param targetName the target name
 * @param originalZip the original zip
 * @param newZip the new zip
 * @param comparefiles the comparefiles
 * @throws Exception the exception
 */
private void runJarPatcher(String originalName, String targetName, ZipFile originalZip, ZipFile newZip,
        boolean comparefiles) throws Exception {
    try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(patchFile))) {
        new JarDelta().computeDelta(originalName, targetName, originalZip, newZip, output);
    }
    ZipFile patch = new ZipFile(patchFile);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        patch.close();
        throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found");
    }
    BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = patchlist.readLine();
    String sourceName = next;
    next = patchlist.readLine();
    new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, new ZipFile(originalName),
            new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist);
    if (comparefiles) {
        compareFiles(new ZipFile(targetName), new ZipFile(resultFile));
    }
}

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   www  .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;
}