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:Main.java

public static String getJarSignature(String packagePath) throws IOException {
    Pattern signatureFilePattern = Pattern.compile("META-INF/[A-Z]+\\.SF");

    ZipFile packageZip = null;
    try {/*from   w w w. j av a 2s  .c  o  m*/
        packageZip = new ZipFile(packagePath);
        // For each file in the zip.
        for (ZipEntry entry : Collections.list(packageZip.entries())) {
            // Ignore non-signature files.
            if (!signatureFilePattern.matcher(entry.getName()).matches()) {
                continue;
            }

            BufferedReader sigContents = null;
            try {
                sigContents = new BufferedReader(new InputStreamReader(packageZip.getInputStream(entry)));
                // For each line in the signature file.
                while (true) {
                    String line = sigContents.readLine();
                    if (line == null || line.equals("")) {
                        throw new IllegalArgumentException(
                                "Failed to find manifest digest in " + entry.getName());
                    }
                    String prefix = "SHA1-Digest-Manifest: ";
                    if (line.startsWith(prefix)) {
                        return line.substring(prefix.length());
                    }
                }
            } finally {
                if (sigContents != null) {
                    sigContents.close();
                }
            }
        }
    } finally {
        if (packageZip != null) {
            packageZip.close();
        }
    }

    throw new IllegalArgumentException("Failed to find signature file.");
}

From source file:org.mycontroller.standalone.backup.Restore.java

private static void extractZipFile(String zipFileName, String destination)
        throws FileNotFoundException, IOException {
    ZipFile zipFile = new ZipFile(zipFileName);
    Enumeration<?> enu = zipFile.entries();
    //create destination if not exists
    FileUtils.forceMkdir(FileUtils.getFile(destination));
    while (enu.hasMoreElements()) {
        ZipEntry zipEntry = (ZipEntry) enu.nextElement();
        String name = zipEntry.getName();
        long size = zipEntry.getSize();
        long compressedSize = zipEntry.getCompressedSize();
        _logger.debug("name:{} | size:{} | compressed size:{}", name, size, compressedSize);
        File file = FileUtils.getFile(destination + File.separator + name);
        //Create destination if it's not available
        if (name.endsWith(File.separator)) {
            file.mkdirs();//from   www  .j ava 2s .  c  om
            continue;
        }

        File parent = file.getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }

        InputStream is = zipFile.getInputStream(zipEntry);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = is.read(bytes)) >= 0) {
            fos.write(bytes, 0, length);
        }
        is.close();
        fos.close();
    }
    zipFile.close();
}

From source file:org.apache.archiva.remotedownload.DownloadSnapshotTest.java

@Test
public void downloadSNAPSHOT() throws Exception {

    File tmpIndexDir = new File(System.getProperty("java.io.tmpdir") + "/tmpIndex");
    if (tmpIndexDir.exists()) {
        FileUtils.deleteDirectory(tmpIndexDir);
    }//w w  w.ja va2  s.  co m
    String id = Long.toString(System.currentTimeMillis());
    ManagedRepository managedRepository = new ManagedRepository();
    managedRepository.setId(id);
    managedRepository.setName("name of " + id);
    managedRepository.setLocation(System.getProperty("basedir") + "/src/test/repositories/snapshot-repo");
    managedRepository.setIndexDirectory(System.getProperty("java.io.tmpdir") + "/tmpIndex/" + id);

    ManagedRepositoriesService managedRepositoriesService = getManagedRepositoriesService();

    if (managedRepositoriesService.getManagedRepository(id) != null) {
        managedRepositoriesService.deleteManagedRepository(id, false);
    }

    getManagedRepositoriesService().addManagedRepository(managedRepository);

    RoleManagementService roleManagementService = getRoleManagementService(authorizationHeader);

    if (!roleManagementService.templatedRoleExists(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id)) {
        roleManagementService.createTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id);
    }

    getUserService(authorizationHeader).createGuestUser();
    roleManagementService.assignRole(ArchivaRoleConstants.TEMPLATE_GUEST, "guest");

    roleManagementService.assignTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, id, "guest");

    getUserService(authorizationHeader).removeFromCache("guest");

    File file = new File("target/archiva-model-1.4-M4-SNAPSHOT.jar");
    if (file.exists()) {
        file.delete();
    }

    HttpWagon httpWagon = new HttpWagon();
    httpWagon.connect(new Repository("foo", "http://localhost:" + port));

    httpWagon.get(
            "/repository/" + id
                    + "/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-SNAPSHOT.jar",
            file);

    ZipFile zipFile = new ZipFile(file);
    List<String> entries = getZipEntriesNames(zipFile);
    ZipEntry zipEntry = zipFile.getEntry("org/apache/archiva/model/ArchivaArtifact.class");
    assertNotNull("cannot find zipEntry org/apache/archiva/model/ArchivaArtifact.class, entries: " + entries
            + ", content is: " + FileUtils.readFileToString(file), zipEntry);
    zipFile.close();
    file.deleteOnExit();

}

From source file:at.alladin.rmbt.android.about.RMBTAboutFragment.java

/**
 * /*from ww  w . ja v a  2 s  .  c  o  m*/
 * @param context
 * @return
 */
private String getAppInfo(final Context context) {
    PackageInfo pInfo;
    try {

        String date = "";
        try {
            final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    0);
            final ZipFile zf = new ZipFile(ai.sourceDir);
            final ZipEntry ze = zf.getEntry("classes.dex");
            zf.close();
            final long time = ze.getTime();
            date = DateFormat.getDateTimeInstance().format(new java.util.Date(time));

        } catch (final Exception e) {// not much we can do
        }

        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        clientVersion = pInfo.versionName + " (" + pInfo.versionCode + ")\n("
                + RevisionHelper.getVerboseRevision() + ")\n(" + date + ")";
        clientName = context.getResources().getString(R.string.app_name);
    } catch (final Exception e) {
        // e1.printStackTrace();
        Log.e(DEBUG_TAG, "version of the application cannot be found", e);
    }

    return clientVersion;
}

From source file:org.jboss.as.test.integration.jdr.mgmt.JdrReportManagmentTestCase.java

private void validateJdrReportContents(File reportFile) {
    String reportName = reportFile.getName().replace(".zip", "");

    ZipFile reportZip = null;
    try {//from ww  w.j  a  v a 2  s  .  c o  m
        reportZip = new ZipFile(reportFile);
        validateReportEntries(reportZip, reportName);
    } catch (Exception e) {
        throw new RuntimeException("Unable to validate JDR report: " + reportFile.getName(), e);
    } finally {
        if (reportZip != null) {
            try {
                reportZip.close();
            } catch (IOException e) {
                throw new RuntimeException("Unable to close JDR report: " + reportFile.getName(), e);
            }
        }
    }
}

From source file:org.eclipse.tycho.nexus.internal.plugin.UnzipRepositoryPluginITCase.java

private String getTestData(String localArtifactPath, String testDataPrefix) throws ZipException, IOException {
    ZipFile zipFile = new ZipFile(testData().resolveFile(testDataPrefix + localArtifactPath));
    String expectedContent;/*from w w w .  j  a  va  2s .  co  m*/
    try {
        ZipEntry entry = zipFile.getEntry(POM_PROPERTIES_PATH_IN_ZIP);
        expectedContent = IOUtils.toString(zipFile.getInputStream(entry));
    } finally {
        zipFile.close();
    }
    return expectedContent;
}

From source file:com.azurenight.maven.TroposphereMojo.java

private void closeFile(ZipFile ja) throws MojoExecutionException {
    try {/* w ww  .j a  v  a2 s .  c om*/
        ja.close();
    } catch (IOException e) {
        throw new MojoExecutionException("closing jython artifact jar failed", e);
    }
}

From source file:org.apache.archiva.remotedownload.DownloadArtifactsTest.java

@Test
public void downloadWithRemoteRedirect() throws Exception {
    RemoteRepository remoteRepository = getRemoteRepositoriesService().getRemoteRepository("central");
    remoteRepository.setUrl("http://localhost:" + redirectPort);
    getRemoteRepositoriesService().updateRemoteRepository(remoteRepository);

    RoleManagementService roleManagementService = getRoleManagementService(authorizationHeader);

    if (!roleManagementService.templatedRoleExists(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
            "internal")) {
        roleManagementService.createTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER,
                "internal");
    }//ww w .  j a v a2 s .  c  o m

    getUserService(authorizationHeader).createGuestUser();
    roleManagementService.assignRole(ArchivaRoleConstants.TEMPLATE_GUEST, "guest");

    roleManagementService.assignTemplatedRole(ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, "internal",
            "guest");

    getUserService(authorizationHeader).removeFromCache("guest");

    File file = new File("target/junit-4.9.jar");
    if (file.exists()) {
        file.delete();
    }

    HttpWagon httpWagon = new HttpWagon();
    httpWagon.connect(new Repository("foo", "http://localhost:" + port));

    httpWagon.get("/repository/internal/junit/junit/4.9/junit-4.9.jar", file);

    ZipFile zipFile = new ZipFile(file);
    List<String> entries = getZipEntriesNames(zipFile);
    ZipEntry zipEntry = zipFile.getEntry("org/junit/runners/JUnit4.class");
    assertNotNull("cannot find zipEntry org/junit/runners/JUnit4.class, entries: " + entries + ", content is: "
            + FileUtils.readFileToString(file), zipEntry);
    zipFile.close();
    file.deleteOnExit();
}

From source file:org.sonar.api.utils.ZipUtils.java

public static File unzip(File zip, File toDir, ZipEntryFilter filter) throws IOException {
    if (!toDir.exists()) {
        FileUtils.forceMkdir(toDir);/*from w w  w  . ja va2 s. c o  m*/
    }

    ZipFile zipFile = new ZipFile(zip);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (filter.accept(entry)) {
                File to = new File(toDir, entry.getName());
                if (entry.isDirectory()) {
                    if (!to.exists() && !to.mkdirs()) {
                        throw new IOException("Error creating directory: " + to);
                    }
                } else {
                    File parent = to.getParentFile();
                    if (parent != null && !parent.exists() && !parent.mkdirs()) {
                        throw new IOException("Error creating directory: " + parent);
                    }

                    FileOutputStream fos = new FileOutputStream(to);
                    InputStream input = null;
                    try {
                        input = zipFile.getInputStream(entry);
                        IOUtils.copy(input, fos);
                    } finally {
                        IOUtils.closeQuietly(input);
                        IOUtils.closeQuietly(fos);
                    }
                }
            }
        }
        return toDir;

    } finally {
        zipFile.close();
    }
}

From source file:org.mule.appkit.it.AbstractMavenIT.java

protected String contentsOfMuleConfigFromZipFile(File muleAppZipFile) throws Exception {
    ZipFile zipFile = null;
    InputStream muleConfigStream = null;
    try {/*from   w ww. j a  va  2s.c  o  m*/
        zipFile = new ZipFile(muleAppZipFile);

        ZipEntry muleConfigEntry = zipFile.getEntry("mule-config.xml");
        assertNotNull(muleConfigEntry);

        muleConfigStream = zipFile.getInputStream(muleConfigEntry);
        return IOUtil.toString(muleConfigStream);
    } finally {
        if (zipFile != null) {
            zipFile.close();
        }
        if (muleConfigStream != null) {
            muleConfigStream.close();
        }
    }
}