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:org.talend.commons.utils.resource.BundleFileUtil.java

public static Manifest getManifest(File f) throws IOException {
    if (f == null || !f.exists() || !f.isFile() || !f.getName().endsWith(FileExtensions.JAR_FILE_SUFFIX)) {
        return null;
    }//from  w  w  w.j  a v  a 2  s. c  o m
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(f);
        return jarFile.getManifest();
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:net.fabricmc.installer.installer.LocalVersionInstaller.java

public static void install(File mcDir, IInstallerProgress progress) throws Exception {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(Translator.getString("install.client.selectCustomJar"));
    fc.setFileFilter(new FileNameExtensionFilter("Jar Files", "jar"));
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File inputFile = fc.getSelectedFile();

        JarFile jarFile = new JarFile(inputFile);
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        String mcVersion = attributes.getValue("MinecraftVersion");
        Optional<String> stringOptional = ClientInstaller.isValidInstallLocation(mcDir, mcVersion);
        jarFile.close();
        if (stringOptional.isPresent()) {
            throw new Exception(stringOptional.get());
        }//ww  w. j  av a 2 s . c  om
        ClientInstaller.install(mcDir, mcVersion, progress, inputFile);
    } else {
        throw new Exception("Failed to find jar");
    }

}

From source file:org.sonar.updatecenter.deprecated.Plugin.java

public static Plugin extractMetadata(File file) throws IOException {
    JarFile jar = new JarFile(file);
    ZipEntry entry = jar.getEntry("META-INF/MANIFEST.MF");
    long timestamp = entry.getTime();
    Manifest manifest = jar.getManifest();
    jar.close();

    Attributes attributes = manifest.getMainAttributes();
    String pluginKey = attributes.getValue("Plugin-Key");
    Plugin plugin = new Plugin(pluginKey);
    plugin.setName(attributes.getValue("Plugin-Name"));
    plugin.setVersion(attributes.getValue("Plugin-Version"));
    plugin.setRequiredSonarVersion(attributes.getValue("Sonar-Version"));
    plugin.setHomepage(attributes.getValue("Plugin-Homepage"));
    plugin.setDate(timestamp);/*from   ww  w.ja  v a  2 s  .c o m*/
    return plugin;
}

From source file:org.ow2.chameleon.core.utils.BundleHelper.java

/**
 * Checks whether the given file is a bundle or not.
 * The check is based on the {@literal Bundle-ManifestVersion} header.
 * If the file is a directory this method checks if the directory is an exploded bundle.
 * If the file is a jar file, it checks the manifest.
 *
 * @param file the file.//from  w  w  w. j a v  a2s. c  o m
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isBundle(File file) {

    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);
            return jar.getManifest() != null && jar.getManifest().getMainAttributes() != null
                    && jar.getManifest().getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) != null;
            // We check the symbolic name because it's the only mandatory header
            // see http://wiki.osgi.org/wiki/Bundle-SymbolicName.
        } catch (IOException e) {
            LoggerFactory.getLogger(BundleHelper.class)
                    .error("Cannot check if the file {} is a bundle, " + "cannot open it", file.getName(), e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(new Closeable() {
                @Override
                public void close() throws IOException {
                    if (finalJar != null) {
                        finalJar.close();
                    }
                }
            });
        }
    }

    return isExplodedBundle(file);

}

From source file:org.tangram.util.SetupUtils.java

private static Set<String> getResourceListing(URL pathUrl, String prefix, String suffix)
        throws URISyntaxException, IOException {
    Set<String> result = new HashSet<>();
    if ("file".equals(pathUrl.getProtocol())) {
        for (String name : new File(pathUrl.toURI()).list()) {
            if (name.endsWith(suffix)) {
                result.add(prefix + "/" + name);
            } // if
        } // for//  w  w  w .j a v a2  s  .com
    } // if

    if ("jar".equals(pathUrl.getProtocol())) {
        String jarPath = pathUrl.getPath().substring(5, pathUrl.getPath().indexOf("!")); // only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
            String name = entries.nextElement().getName();
            if (name.startsWith(prefix) && name.endsWith(suffix)) {
                result.add(name);
            } // if
        } // for
        jar.close();
    } // if

    return result;
}

From source file:org.wisdom.maven.utils.WebJars.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file./*  w w w .  j ava 2 s. c  om*/
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isWebJar(File file) {
    Set<String> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WEBJAR_LOCATION) == null) {
                return false;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(matcher.group(1) + "-" + matcher.group(2));
                }
            }
        } catch (IOException e) {
            LoggerFactory.getLogger(DependencyCopy.class)
                    .error("Cannot check if the file {} is a webjar, " + "cannot open it", file.getName(), e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(new Closeable() {
                @Override
                public void close() throws IOException {
                    if (finalJar != null) {
                        finalJar.close();
                    }
                }
            });
        }

        for (String lib : found) {
            LoggerFactory.getLogger(DependencyCopy.class).info("Web Library found in {} : {}", file.getName(),
                    lib);
        }

        return !found.isEmpty();
    }

    return false;
}

From source file:com.app.server.util.ClassLoaderUtil.java

public static boolean cleanupJarFileFactory(CopyOnWriteArrayList setJarFileNames2Close) {
    boolean res = false;
    Class classJarURLConnection = null;
    try {// w w  w  .java2  s .  c  o  m
        classJarURLConnection = Class.forName("sun.net.www.protocol.jar.JarURLConnection");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    if (classJarURLConnection == null) {
        return res;
    }
    Field f = null;
    try {
        f = classJarURLConnection.getDeclaredField("factory");
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    if (f == null) {
        return res;
    }
    f.setAccessible(true);
    Object obj = null;
    try {
        obj = f.get(null);
    } catch (IllegalAccessException e) {
        // ignore
    }
    if (obj == null) {
        return res;
    }
    Class classJarFileFactory = obj.getClass();
    //
    HashMap fileCache = null;
    try {
        f = classJarFileFactory.getDeclaredField("fileCache");
        f.setAccessible(true);
        obj = f.get(null);
        if (obj instanceof HashMap) {
            fileCache = (HashMap) obj;
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    HashMap urlCache = null;
    try {
        f = classJarFileFactory.getDeclaredField("urlCache");
        f.setAccessible(true);
        obj = f.get(null);
        if (obj instanceof HashMap) {
            urlCache = (HashMap) obj;
        }
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    if (urlCache != null) {
        HashMap urlCacheTmp = (HashMap) urlCache.clone();
        Iterator it = urlCacheTmp.keySet().iterator();
        while (it.hasNext()) {
            obj = it.next();
            if (!(obj instanceof JarFile)) {
                continue;
            }
            JarFile jarFile = (JarFile) obj;
            if (setJarFileNames2Close.contains(jarFile.getName().trim().toUpperCase())) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (fileCache != null) {
                    fileCache.remove(jarFile);
                }
                urlCache.remove(jarFile);
            }
        }
        res = true;
    } else if (fileCache != null) {
        // urlCache := null
        HashMap fileCacheTmp = (HashMap) fileCache.clone();
        Iterator it = fileCacheTmp.keySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            obj = fileCache.get(key);
            if (!(obj instanceof JarFile)) {
                continue;
            }
            JarFile jarFile = (JarFile) obj;

            try {
                jarFile.close();
            } catch (IOException e) {
                // ignore
            }
            fileCache.remove(key);

        }
        res = true;
    }
    setJarFileNames2Close.clear();
    return res;
}

From source file:org.jvnet.hudson.test.JellyTestSuiteBuilder.java

static Map<URL, String> scan(File resources, String extension) throws IOException {
    Map<URL, String> result = new HashMap<>();
    if (resources.isDirectory()) {
        for (File f : FileUtils.listFiles(resources, new String[] { extension }, true)) {
            result.put(f.toURI().toURL(),
                    f.getAbsolutePath().substring((resources.getAbsolutePath() + File.separator).length()));
        }// w ww .j a  v a  2 s  .  c  o  m
    } else if (resources.getName().endsWith(".jar")) {
        String jarUrl = resources.toURI().toURL().toExternalForm();
        JarFile jf = new JarFile(resources);
        Enumeration<JarEntry> e = jf.entries();
        while (e.hasMoreElements()) {
            JarEntry ent = e.nextElement();
            if (ent.getName().endsWith("." + extension)) {
                result.put(new URL("jar:" + jarUrl + "!/" + ent.getName()), ent.getName());
            }
        }
        jf.close();
    }
    return result;
}

From source file:hudson.plugins.simpleupdatesite.HPI.java

public static HPI loadHPI(File file) throws IOException {
    JarFile jarFile = new JarFile(file);
    try {/* w w w .  ja  va 2s .  c om*/
        ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
        HPI hpi = new HPI();
        hpi.init(jarFile.getManifest().getMainAttributes(), entry.getTime());
        return hpi;
    } finally {
        jarFile.close();
    }
}

From source file:org.wisdom.resources.WebJarDeployer.java

/**
 * Checks whether the given file is a WebJar or not (http://www.webjars.org/documentation).
 * The check is based on the presence of {@literal META-INF/resources/webjars/} directory in the jar file.
 *
 * @param file the file.//from   ww w. j  a  v a2  s.c  om
 * @return the set of libraries found in the file, {@code null} if none.
 */
public static Set<DetectedWebJar> isWebJar(File file) {
    Set<DetectedWebJar> found = new LinkedHashSet<>();
    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);

            // Fast return if the base structure is not there
            if (jar.getEntry(WebJarController.WEBJAR_LOCATION) == null) {
                return null;
            }

            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                Matcher matcher = WebJarController.WEBJAR_REGEX.matcher(entry.getName());
                if (matcher.matches()) {
                    found.add(new DetectedWebJar(matcher.group(1), matcher.group(2), entry.getName(), file));
                }
            }
        } catch (IOException e) {
            LOGGER.error("Cannot check if the file {} is a webjar, " + "cannot open it", file.getName(), e);
            return null;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(new Closeable() {
                @Override
                public void close() throws IOException {
                    if (finalJar != null) {
                        finalJar.close();
                    }
                }
            });
        }

        for (DetectedWebJar lib : found) {
            LOGGER.info("Web Library found in {} : {}", file.getName(), lib.id);
        }

        return found;
    }

    return null;
}