Example usage for java.util.jar JarFile close

List of usage examples for java.util.jar JarFile close

Introduction

In this page you can find the example usage for java.util.jar JarFile close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:com.cwctravel.jenkinsci.plugins.htmlresource.HTMLResourceManagement.java

private boolean validateWebJAR(File file) throws IOException {
    boolean result = false;
    if (file.getName().endsWith(".jar")) {
        JarFile jarFile = new JarFile(file);
        try {//ww w. ja v  a 2 s  .  c  o  m
            result = jarFile.size() > 0;
        } finally {
            jarFile.close();
        }
    }

    return result;
}

From source file:org.jumpmind.util.JarBuilderUnitTest.java

@Test
public void testJarCreation() throws Exception {
    final String TEST_JAR_DIR = "target/test.jar.dir";
    File outputFile = new File("target/test.jar");
    outputFile.delete();/*from w  w w  . ja va  2  s  . c om*/
    assertFalse(outputFile.exists());

    FileUtils.deleteDirectory(new File(TEST_JAR_DIR));

    mkdir(TEST_JAR_DIR + "/subdir");
    mkdir(TEST_JAR_DIR + "/META-INF");
    emptyFile(TEST_JAR_DIR + "/META-INF/MANIFEST.MF");
    emptyFile(TEST_JAR_DIR + "/subdir/file2.txt");
    emptyFile(TEST_JAR_DIR + "/file2.txt");
    emptyFile("target/file1.txt");
    emptyFile(TEST_JAR_DIR + "/file3.txt");

    JarBuilder jarFile = new JarBuilder(new File(TEST_JAR_DIR), outputFile,
            new File[] { new File(TEST_JAR_DIR), new File("target/file1.txt") }, "3.0.0");
    jarFile.build();

    assertTrue(outputFile.exists());

    JarFile finalJar = new JarFile(outputFile);
    assertNotNull(finalJar.getEntry("subdir/file2.txt"));
    assertNotNull(finalJar.getEntry("file2.txt"));
    assertNull(finalJar.getEntry("target/test.jar.dir"));
    assertNull(finalJar.getEntry("test.jar.dir"));
    assertNull(finalJar.getEntry("file1.txt"));
    assertNotNull(finalJar.getEntry("file3.txt"));
    finalJar.close();
}

From source file:org.netbeans.nbbuild.MakeJnlp2.java

/** return alias if signed, or null if not */
private static String isSigned(File f) throws IOException {
    JarFile jar = new JarFile(f);
    try {/*w  w w.java 2  s .  c o m*/
        Enumeration<JarEntry> en = jar.entries();
        while (en.hasMoreElements()) {
            Matcher m = SF.matcher(en.nextElement().getName());
            if (m.matches()) {
                return m.group(1);
            }
        }
        return null;
    } finally {
        jar.close();
    }
}

From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java

@Override
protected URL findResource(String name) {

    URL ret = null;/*  w  w  w .  j  a v  a 2s.co m*/
    JarFile jarFile = null;

    try {
        for (Resource entry : this.classPath) {
            if (entry.getFilename().toLowerCase().endsWith(".jar")) {
                jarFile = new JarFile(entry.getFile());
                ZipEntry ze = jarFile.getEntry(name);
                jarFile.close();

                if (ze != null) {
                    ret = new URL("jar:" + entry.getURL() + "!/" + name);
                    break;
                }
            } else {
                Resource file = entry.createRelative(name);
                if (file.exists()) {
                    ret = file.getURL();
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new WMRuntimeException(e);
    }

    return ret;
}

From source file:uk.codingbadgers.bootstrap.tasks.TaskInstallerUpdateCheck.java

@Override
public void run(Bootstrap bootstrap) {
    try {//from  w  w  w . j ava  2  s.c om
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(INSTALLER_UPDATE_URL);
        request.setHeader(new BasicHeader("Accept", GITHUB_MIME_TYPE));

        HttpResponse response = client.execute(request);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();

            String localVersion = null;

            if (bootstrap.getInstallerFile().exists()) {
                JarFile jar = new JarFile(bootstrap.getInstallerFile());
                Manifest manifest = jar.getManifest();
                localVersion = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
                jar.close();
            }

            JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray();
            JsonObject release = json.get(0).getAsJsonObject();

            JsonObject installerAsset = null;
            JsonObject librariesAsset = null;
            int i = 0;

            for (JsonElement element : release.get("assets").getAsJsonArray()) {
                JsonObject object = element.getAsJsonObject();
                if (INSTALLER_LABEL.equals(object.get("name").getAsString())) {
                    installerAsset = object;
                } else if (INSTALLER_LIBS_LABEL.equals(object.get("name").getAsString())) {
                    librariesAsset = object;
                }
            }

            if (VersionComparator.getInstance().compare(localVersion, release.get("name").getAsString()) < 0) {
                bootstrap.addDownload(DownloadType.INSTALLER, new EtagDownload(
                        installerAsset.get("url").getAsString(), bootstrap.getInstallerFile()));
                localVersion = release.get("name").getAsString();
            }

            File libs = new File(bootstrap.getInstallerFile() + ".libs");
            boolean update = true;

            if (libs.exists()) {
                FileReader reader = null;

                try {
                    reader = new FileReader(libs);
                    JsonElement parsed = PARSER.parse(reader);

                    if (parsed.isJsonObject()) {
                        JsonObject libsJson = parsed.getAsJsonObject();

                        if (libsJson.has("installer")) {
                            JsonObject installerJson = libsJson.get("installer").getAsJsonObject();
                            if (installerJson.get("version").getAsString().equals(localVersion)) {
                                update = false;
                            }
                        }
                    }
                } catch (JsonParseException ex) {
                    throw new BootstrapException(ex);
                } finally {
                    reader.close();
                }
            }

            if (update) {
                new EtagDownload(librariesAsset.get("url").getAsString(),
                        new File(bootstrap.getInstallerFile() + ".libs")).download();

                FileReader reader = null;
                FileWriter writer = null;

                try {
                    reader = new FileReader(libs);
                    JsonObject libsJson = PARSER.parse(reader).getAsJsonObject();

                    JsonObject versionJson = new JsonObject();
                    versionJson.add("version", new JsonPrimitive(localVersion));

                    libsJson.add("installer", versionJson);
                    writer = new FileWriter(libs);
                    new Gson().toJson(libsJson, writer);
                } catch (JsonParseException ex) {
                    throw new BootstrapException(ex);
                } finally {
                    reader.close();
                    writer.close();
                }
            }

            EntityUtils.consume(entity);
        } else if (statusLine.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            System.err.println("Hit rate limit, skipping update check");
        } else {
            throw new BootstrapException("Error sending request to github. Error " + statusLine.getStatusCode()
                    + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        throw new BootstrapException(e);
    }
}

From source file:org.wso2.carbon.automation.engine.frameworkutils.CodeCoverageUtils.java

private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException {
    if (!jarFilePath.endsWith(".jar")) {
        throw new IllegalArgumentException(
                "Jar file should have the extension .jar. " + jarFilePath + " is invalid");
    }/*from   ww w  . j a  v a  2  s. c om*/
    JarFile jarFile = new JarFile(jarFilePath);
    Manifest manifest = jarFile.getManifest();
    if (manifest == null) {
        throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file");
    }
    String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator;
    String jarFileName = jarFilePath;
    if (jarFilePath.lastIndexOf(fileSeparator) != -1) {
        jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1);
    }
    ArchiveManipulator archiveManipulator = null;
    String tempExtractedDir = null;
    try {
        archiveManipulator = new ArchiveManipulator();
        tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator
                + jarFileName.substring(0, jarFileName.lastIndexOf('.'));
        ArchiveExtractorUtil.extractFile(jarFilePath, tempExtractedDir);
    } catch (Exception e) {
        log.error("Could not extract the file", e);
    } finally {
        jarFile.close();
    }
    String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package");
    if (dynamicImports != null) {
        manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*");
    } else {
        manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*");
    }
    File newManifest = new File(
            tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF");
    FileOutputStream manifestOut = null;
    try {
        manifestOut = new FileOutputStream(newManifest);
        manifest.write(manifestOut);
    } catch (IOException e) {
        log.error("Could not write content to new MANIFEST.MF file", e);
    } finally {
        if (manifestOut != null) {
            manifestOut.close();
        }
    }

    if (tempExtractedDir != null)
        archiveManipulator.archiveDir(jarFilePath, tempExtractedDir);

    FileUtils.forceDelete(newManifest);
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * Get absolute path to the gwt-user.jar.
 * //from w  ww  . j av  a2  s.co  m
 * @param project
 *          optional GWT {@link IProject}, if not <code>null</code>, then project-specific
 *          gwt-user.jar may be returned; if <code>null</code>, then workspace-global one.
 */
public static IPath getUserLibPath(final IProject project) {
    // when no project, use workspace-global GWT_HOME
    if (project == null) {
        return new Path(Activator.getGWTLocation()).append("gwt-user.jar");
    }
    // try to find  project-specific GWT location
    return ExecutionUtils.runObject(new RunnableObjectEx<IPath>() {
        public IPath runObject() throws Exception {
            IJavaProject javaProject = JavaCore.create(project);
            String[] entries = ProjectClassLoader.getClasspath(javaProject);
            // try to find gwt-user.jar by name
            String userJarEntry = getUserJarEntry(entries);
            if (userJarEntry != null) {
                return new Path(userJarEntry);
            }
            // try to find gwt-user.jar by contents
            for (String entry : entries) {
                if (entry.endsWith(".jar")) {
                    JarFile jarFile = new JarFile(entry);
                    try {
                        if (jarFile.getEntry("com/google/gwt/core/Core.gwt.xml") != null) {
                            return new Path(entry);
                        }
                    } finally {
                        jarFile.close();
                    }
                }
            }
            // not found
            return null;
        }
    });
}

From source file:org.codehaus.mojo.license.osgi.AboutFileLicenseResolver.java

public List<License> resolve(String artifactId, File file) throws IOException {
    List<License> licenses = new ArrayList<License>();
    JarFile jarFile = new JarFile(file);
    try {//  w  w  w. ja  v  a2  s . c  om
        ZipEntry entry = jarFile.getEntry(ABOUT_HTML);
        if (entry != null) {
            licenses.add(createJarEmbeddedLicense(artifactId, file, ABOUT_HTML));
            String content = readContent(jarFile, entry);
            licenses.addAll(findThrirdPartyLicenses(artifactId, file, content));
        }
        return licenses;
    } finally {
        jarFile.close();
    }
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

@SuppressWarnings("rawtypes")
public static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {/*  w  w w  . ja  v  a  2s  .  c  om*/
        Enumeration entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = (JarEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = jar.getInputStream(entry);
                try {
                    File file = new File(toDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        jar.close();
    }
}

From source file:org.nuxeo.osgi.util.jar.JarFileFactoryCloser.java

public void close(URL location) throws IOException {
    if (!ok) {/*from ww w  . j  a v  a  2 s  .co  m*/
        return;
    }
    JarFile jar = null;
    try {
        jar = (JarFile) factoryGetMethod.invoke(factory, new Object[] { location });
        factoryCloseMethod.invoke(factory, jar);
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Cannot use reflection on jar file factory", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Cannot use reflection on jar file factory", e);
    }
    jar.close();
}