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.apache.tajo.util.ClassUtil.java

private static void findClasses(Set<Class> matchedClassSet, File root, File file, boolean includeJars,
        @Nullable Class type, String packageFilter, @Nullable Predicate predicate) {
    if (file.isDirectory()) {
        for (File child : file.listFiles()) {
            findClasses(matchedClassSet, root, child, includeJars, type, packageFilter, predicate);
        }/*from  w  w  w.  ja va 2 s  .c o  m*/
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
                return;
            }
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                int extIndex = name.lastIndexOf(".class");
                if (extIndex > 0) {
                    String qualifiedClassName = name.substring(0, extIndex).replace("/", ".");
                    if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                        try {
                            Class clazz = Class.forName(qualifiedClassName);

                            if (isMatched(clazz, type, predicate)) {
                                matchedClassSet.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            LOG.error(e.getMessage(), e);
                        }
                    }
                }
            }

            try {
                jar.close();
            } catch (IOException e) {
                LOG.warn("Closing " + file.getName() + " was failed.");
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String qualifiedClassName = createClassName(root, file);
            if (qualifiedClassName.indexOf(packageFilter) >= 0 && !isTestClass(qualifiedClassName)) {
                try {
                    Class clazz = Class.forName(qualifiedClassName);
                    if (isMatched(clazz, type, predicate)) {
                        matchedClassSet.add(clazz);
                    }
                } catch (ClassNotFoundException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:hudson.remoting.RegExpBenchmark.java

private List<String> getAllRTClasses() throws Exception {
    List<String> classes = new ArrayList<String>();
    // Object.class.getProtectionDomain().getCodeSource() returns null :(
    String javaHome = System.getProperty("java.home");
    JarFile jf = new JarFile(javaHome + "/lib/rt.jar");
    for (JarEntry je : Collections.list(jf.entries())) {
        if (!je.isDirectory() && je.getName().endsWith(".class")) {
            String name = je.getName().replace('/', '.');
            // remove the .class
            name = name.substring(0, name.length() - 6);
            classes.add(name);//from w  w w  .  ja  v a2s .  c  o  m
        }
    }
    jf.close();
    // add in a couple from xalan and commons just for testing...
    classes.add(new String("org.apache.commons.collections.functors.EvilClass"));
    classes.add(new String("org.codehaus.groovy.runtime.IWIllHackYou"));
    classes.add(new String("org.apache.xalan.YouAreOwned"));
    return classes;
}

From source file:org.red5.server.plugin.PluginLauncher.java

public void afterPropertiesSet() throws Exception {

    ApplicationContext common = (ApplicationContext) applicationContext.getBean("red5.common");
    Server server = (Server) common.getBean("red5.server");

    //server should be up and running at this point so load any plug-ins now         

    //get the plugins dir
    File pluginsDir = new File(System.getProperty("red5.root"), "plugins");

    File[] plugins = pluginsDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            //lower the case
            String tmp = name.toLowerCase();
            //accept jars and zips
            return tmp.endsWith(".jar") || tmp.endsWith(".zip");
        }//from   www. j  a  va  2 s .com
    });

    if (plugins != null) {

        IRed5Plugin red5Plugin = null;

        log.debug("{} plugins to launch", plugins.length);
        for (File plugin : plugins) {
            JarFile jar = null;
            Manifest manifest = null;
            try {
                jar = new JarFile(plugin, false);
                manifest = jar.getManifest();
            } catch (Exception e1) {
                log.warn("Error loading plugin manifest: {}", plugin);
            } finally {
                jar.close();
            }
            if (manifest == null) {
                continue;
            }
            Attributes attributes = manifest.getMainAttributes();
            if (attributes == null) {
                continue;
            }
            String pluginMainClass = attributes.getValue("Red5-Plugin-Main-Class");
            if (pluginMainClass == null || pluginMainClass.length() <= 0) {
                continue;
            }
            // attempt to load the class; since it's in the plugins directory this should work
            ClassLoader loader = common.getClassLoader();
            Class<?> pluginClass;
            String pluginMainMethod = null;
            try {
                pluginClass = Class.forName(pluginMainClass, true, loader);
            } catch (ClassNotFoundException e) {
                continue;
            }
            try {
                //handle plug-ins without "main" methods
                pluginMainMethod = attributes.getValue("Red5-Plugin-Main-Method");
                if (pluginMainMethod == null || pluginMainMethod.length() <= 0) {
                    //just get an instance of the class
                    red5Plugin = (IRed5Plugin) pluginClass.newInstance();
                } else {
                    Method method = pluginClass.getMethod(pluginMainMethod, (Class<?>[]) null);
                    Object o = method.invoke(null, (Object[]) null);
                    if (o != null && o instanceof IRed5Plugin) {
                        red5Plugin = (IRed5Plugin) o;
                    }
                }
                //register and start
                if (red5Plugin != null) {
                    //set top-level context
                    red5Plugin.setApplicationContext(applicationContext);
                    //set server reference
                    red5Plugin.setServer(server);
                    //register the plug-in to make it available for lookups
                    PluginRegistry.register(red5Plugin);
                    //start the plugin
                    red5Plugin.doStart();
                }
                log.info("Loaded plugin: {}", pluginMainClass);
            } catch (Throwable t) {
                log.warn("Error loading plugin: {}; Method: {}", pluginMainClass, pluginMainMethod);
                log.error("", t);
            }
        }
    } else {
        log.info("Plugins directory cannot be accessed or doesnt exist");
    }

}

From source file:com.liferay.ide.ui.editor.LiferayPropertiesSourceViewerConfiguration.java

@Override
public IContentAssistant getContentAssistant(final ISourceViewer sourceViewer) {
    if (this.propKeys == null) {
        final IEditorInput input = this.getEditor().getEditorInput();

        // first fine runtime location to get properties definitions
        final IPath appServerPortalDir = getAppServerPortalDir(input);
        final String propertiesEntry = getPropertiesEntry(input);

        PropKey[] keys = null;//from   w  ww .j  a v a 2  s  .c  om

        if (appServerPortalDir != null && appServerPortalDir.toFile().exists()) {
            try {
                final JarFile jar = new JarFile(
                        appServerPortalDir.append("WEB-INF/lib/portal-impl.jar").toFile());
                final ZipEntry lang = jar.getEntry(propertiesEntry);

                keys = parseKeys(jar.getInputStream(lang));

                jar.close();
            } catch (Exception e) {
                LiferayUIPlugin.logError("Unable to get portal properties file", e);
            }
        } else {
            return assitant;
        }

        final Object adapter = input.getAdapter(IFile.class);

        if (adapter instanceof IFile && isHookProject(((IFile) adapter).getProject())) {
            final ILiferayProject liferayProject = LiferayCore.create(((IFile) adapter).getProject());
            final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class);

            if (portal != null) {
                final Set<String> hookProps = new HashSet<String>();
                Collections.addAll(hookProps, portal.getHookSupportedProperties());

                final List<PropKey> filtered = new ArrayList<PropKey>();

                for (PropKey pk : keys) {
                    if (hookProps.contains(pk.getKey())) {
                        filtered.add(pk);
                    }
                }

                keys = filtered.toArray(new PropKey[0]);
            }
        }

        propKeys = keys;
    }

    if (propKeys != null && assitant == null) {
        final ContentAssistant ca = new ContentAssistant() {
            @Override
            public IContentAssistProcessor getContentAssistProcessor(final String contentType) {
                return new LiferayPropertiesContentAssistProcessor(propKeys, contentType);
            }
        };

        ca.setInformationControlCreator(getInformationControlCreator(sourceViewer));

        assitant = ca;
    }

    return assitant;
}

From source file:org.gradle.util.TestFile.java

public Manifest getManifest() {
    assertIsFile();//  ww  w  . jav  a 2s.c  om
    try {
        JarFile jarFile = new JarFile(this);
        try {
            return jarFile.getManifest();
        } finally {
            jarFile.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.hyperic.hq.plugin.tomcat.TomcatServerDetector.java

private boolean isCorrectVersion(String versionJar) {
    boolean correctVersion = false;
    try {/*from   w w w  .ja  v a 2  s.c om*/
        JarFile jarFile = new JarFile(versionJar);
        log.debug("[isInstallTypeVersion] versionJar='" + jarFile.getName() + "'");
        Attributes attributes = jarFile.getManifest().getMainAttributes();
        jarFile.close();
        String tomcatVersion = attributes.getValue("Specification-Version");
        String expectedVersion = getTypeProperty("tomcatVersion");
        if (expectedVersion == null) {
            expectedVersion = getTypeInfo().getVersion();
        }
        log.debug("[isInstallTypeVersion] tomcatVersion='" + tomcatVersion + "' (" + expectedVersion + ")");
        correctVersion = tomcatVersion.equals(expectedVersion);
    } catch (IOException e) {
        log.debug("Error getting Tomcat version (" + e + ")", e);
    }
    return correctVersion;
}

From source file:org.apache.hadoop.streaming.StreamUtil.java

static void unJar(File jarFile, File toDir) throws IOException {
    JarFile jar = new JarFile(jarFile);
    try {/*from w  w  w . j  a  va  2  s .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());
                    file.getParentFile().mkdirs();
                    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:com.taobao.android.apatch.MergePatch.java

private Dex getDexFromJar(File file) throws IOException {
    JarFile jarFile = null;
    try {/*from ww  w . java  2s  . co  m*/
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("classes.dex");
        return new Dex(jarFile.getInputStream(dexEntry));
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:net.avalonrealms.plugins.core.Core.java

@Override
public void onEnable() {
    // Folders/*from w w w .j  av a2  s .c  o m*/
    downloadFolder = new File(getDataFolder(), "downloads");
    errorFolder = new File(getDataFolder(), "errors");
    addonFolder = new File(getDataFolder(), "addons");
    repoFolder = new File(getDataFolder(), "repo");

    // Make folders TODO check result
    downloadFolder.mkdirs();
    errorFolder.mkdirs();
    addonFolder.mkdirs();
    repoFolder.mkdirs();

    // Utils
    errorUtils = new ErrorUtils(this);
    hookUtils = new HookUtils(this);

    // Updater
    updater = new Updater(this);

    // CommandInfo map
    try {
        Class<?> craftServer = SVPTools.getCurrentCBClass("CraftServer");
        if (craftServer == null)
            throw new RuntimeException("Computer says no to getting the craft server");
        Field f = craftServer.getDeclaredField("commandMap");
        f.setAccessible(true);
        commandMap = (CommandMap) f.get(getServer());
    } catch (Exception e) {
        errorUtils.logError(e);
        getServer().getPluginManager().disablePlugin(this);
        return;
    }

    // Listeners
    PluginManager p = getServer().getPluginManager();

    if (getHookUtils().isHooked(HookUtils.Hook.WORLD_GUARD)) {
        p.registerEvents(new WGListener(this, (com.sk89q.worldguard.bukkit.WorldGuardPlugin) getHookUtils()
                .getHook(HookUtils.Hook.WORLD_GUARD)), this);
    } else {
        getLogger().warning("WorldGuard was not found. WorldGuard events will not run.");
    }

    // Addons
    File[] addons = getAddonFolder().listFiles();

    if (addons == null) {
        throw new RuntimeException("Unable to create addon directory");
    }

    for (File file : addons) {
        if (file.isDirectory() || !file.getName().endsWith(".jar")) {
            continue;
        }

        try {
            ClasspathTools.addFileToClasspath(getClassLoader(), file);

            JarFile jar = new JarFile(file);

            Class<?> main = Class.forName(jar.getManifest().getMainAttributes().getValue("Addon-Package"));
            CoreAddon addon = (CoreAddon) main.newInstance();
            addon.setManifestValues(jar.getManifest());
            coreAddons.put(addon.getName(), addon);

            jar.close();
        } catch (Exception e) {
            errorUtils.logError(e);
        }
    }

    for (CoreAddon addon : Maps.newHashMap(coreAddons).values()) {
        addon.initialise(this);
        addon.onEnable();
    }

    getLogger().info("Enabled " + coreAddons.size() + " addons.");
}

From source file:io.joynr.util.JoynrUtil.java

public static void copyDirectoryFromJar(String jarName, String srcDir, File tmpDir) throws IOException {

    JarFile jf = null;
    JarInputStream jarInputStream = null;

    try {/*from w  ww.  j  a v a 2s  .  c om*/
        jf = new JarFile(jarName);
        JarEntry je = jf.getJarEntry(srcDir);
        if (je.isDirectory()) {
            FileInputStream fis = new FileInputStream(jarName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            jarInputStream = new JarInputStream(bis);
            JarEntry ze = null;
            while ((ze = jarInputStream.getNextJarEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
                if (ze.getName().contains(je.getName())) {
                    InputStream is = jf.getInputStream(ze);
                    String name = ze.getName().substring(ze.getName().lastIndexOf("/") + 1);
                    File tmpFile = new File(tmpDir + "/" + name); //File.createTempFile(file.getName(), "tmp");
                    tmpFile.deleteOnExit();
                    OutputStream outputStreamRuntime = new FileOutputStream(tmpFile);
                    copyStream(is, outputStreamRuntime);
                }
            }
        }
    } finally {
        if (jf != null) {
            jf.close();
        }
        if (jarInputStream != null) {
            jarInputStream.close();
        }
    }
}