Example usage for java.lang ClassLoader getResources

List of usage examples for java.lang ClassLoader getResources

Introduction

In this page you can find the example usage for java.lang ClassLoader getResources.

Prototype

public Enumeration<URL> getResources(String name) throws IOException 

Source Link

Document

Finds all the resources with the given name.

Usage

From source file:org.jfunktor.common.vfs.VirtualFileSystem.java

public static void printContents(String path, ClassLoader loader) {
    try {/*from   w w  w. java 2s.co m*/
        Enumeration<URL> resources = loader.getResources(path);
        if (null != resources) {
            log.debug("Source of path " + path);
            while (resources.hasMoreElements()) {
                URL resourceURL = resources.nextElement();
                log.debug("Path " + resourceURL);
                if (exists(resourceURL)) {
                    log.debug("Listing contents of URL " + resourceURL);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (VFSException e) {
        e.printStackTrace();
    }
}

From source file:org.richfaces.util.RenderPhaseComponentVisitorUtils.java

private static RenderPhaseComponentVisitor[] init() {
    LinkedList<RenderPhaseComponentVisitor> list = new LinkedList<RenderPhaseComponentVisitor>();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String resource = "META-INF/services/org.richfaces.component.RenderPhaseComponentVisitor";
    try {/*from w  ww.j a  va2s . c o  m*/
        Enumeration<URL> resources = loader.getResources(resource);
        while (resources.hasMoreElements()) {
            InputStream stream = URLToStreamHelper.urlToStreamSafe(resources.nextElement());
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            try {
                String handlerClassName = null;
                while ((handlerClassName = reader.readLine()) != null) {
                    if (handlerClassName.length() > 0) {
                        try {
                            Class<?> handlerClass = ServicesUtils.loadClass(loader, handlerClassName);
                            Object handler = handlerClass.newInstance();
                            list.add((RenderPhaseComponentVisitor) handler);
                        } catch (Exception e) {
                            throw new FacesException("Error create instance for class " + handlerClassName, e);
                        }
                    }
                }

            } finally {
                try {
                    reader.close();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new FacesException("Error load resource " + resource, e);
    }
    return list.toArray(new RenderPhaseComponentVisitor[list.size()]);
}

From source file:org.rhq.core.pc.plugin.PluginValidator.java

private static SimplePluginFinder findPluginJars() throws Exception {
    SimplePluginFinder pluginFinder = new SimplePluginFinder();
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> descriptorUrls = classloader.getResources(PLUGIN_DESCRIPTOR_PATH);
    while (descriptorUrls.hasMoreElements()) {
        URL descriptorUrl = descriptorUrls.nextElement();
        URLConnection connection = descriptorUrl.openConnection();
        if (connection instanceof JarURLConnection) {
            URL jarUrl = ((JarURLConnection) connection).getJarFileURL();
            pluginFinder.addUrl(jarUrl);
            LOG.info("Found plugin jar: " + jarUrl);
        } else {/*  w w  w .  j a va  2 s .  c om*/
            LOG.warn("Found a plugin descriptor outside of a jar, skipping: " + descriptorUrl);
        }
    }

    return pluginFinder;
}

From source file:ReflectUtils.java

/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package//from   w  w w .  ja  va 2s. c o m
 * @return The classes
 * @throws ClassNotFoundException
 * @throws IOException
 */
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
    //        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes.toArray(new Class[classes.size()]);
}

From source file:adalid.util.info.JavaInfo.java

public static void printManifestInfo(String extension, boolean details) {
    ClassLoader loader;
    Enumeration<URL> resources;
    try {/*w ww. j a v a2s. co m*/
        //          loader = ClassLoader.getSystemClassLoader();
        loader = Thread.currentThread().getContextClassLoader();
        resources = loader.getResources(JarFile.MANIFEST_NAME);
        printManifestInfo(extension, details, resources);
    } catch (IOException ex) {
        logger.fatal(ex);
    }
}

From source file:org.jcurl.core.helpers.Service.java

@SuppressWarnings("unchecked")
public static <E> Iterable<Class<E>> providerClasses(final Class<E> clz, ClassLoader cl) {
    try {/*from  w ww  . j a va 2 s .  c o m*/
        if (cl == null)
            cl = clz.getClassLoader();
        final Collection<Class<E>> ret = new LinkedHashSet<Class<E>>();
        // scan all
        for (final Enumeration<URL> e = cl.getResources(META_INF_SERVICES + clz.getName()); e
                .hasMoreElements();) {
            final URL o = e.nextElement();
            final BufferedReader r = new BufferedReader(new InputStreamReader(o.openStream(), UTF_8));
            for (CharSequence line = r.readLine(); line != null; line = r.readLine()) {
                final Matcher m = pat.matcher(line);
                if (!m.matches())
                    continue;
                try {
                    final Class<?> c = Class.forName(m.group(1), true, cl);
                    if (clz.isAssignableFrom(c)) {
                        final Class<E> clz_ = (Class<E>) c;
                        if (ret.contains(clz_))
                            log.warn("Duplicate class " + clz_.getName() + " in " + o.toString());
                        else
                            ret.add(clz_);
                    }
                } catch (final ClassCastException e1) {
                    // ignore.
                } catch (final ClassNotFoundException e1) {
                    // ignore.
                }
            }
        }
        return ret;
    } catch (final IOException e) {
        throw new RuntimeException("Uncaught Exception", e);
    }
}

From source file:org.docx4j.jaxb.Context.java

public static void searchManifestsForJAXBImplementationInfo(ClassLoader loader) {
    Enumeration resEnum;//w  ww.ja  va  2 s . c om
    try {
        resEnum = loader.getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            InputStream is = null;
            try {
                URL url = (URL) resEnum.nextElement();
                //                   System.out.println("\n\n" + url);
                is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);

                    Attributes mainAttribs = manifest.getMainAttributes();
                    String impTitle = mainAttribs.getValue("Implementation-Title");
                    if (impTitle != null && impTitle.contains("JAXB Reference Implementation")
                            || impTitle.contains("org.eclipse.persistence")) {

                        log.info("\n" + url);
                        for (Object key2 : mainAttribs.keySet()) {

                            log.info(key2 + " : " + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                        }
                    }

                    // In 2.1.3, it is in here
                    for (String key : manifest.getEntries().keySet()) {
                        //System.out.println(key);                       
                        if (key.equals("com.sun.xml.bind.v2.runtime")) {
                            log.info("Found JAXB reference implementation in " + url);
                            mainAttribs = manifest.getAttributes((String) key);

                            for (Object key2 : mainAttribs.keySet()) {
                                log.info(key2 + " : "
                                        + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                            }
                        }
                    }

                }
            } catch (Exception e) {
                // Silently ignore 
                //                  log.error(e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e1) {
        // Silently ignore 
        //           log.error(e1);
    }

}

From source file:com.feedzai.fos.server.remote.impl.RemoteInterfacesTest.java

/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package/* w  ww  . j a va  2s  .  c om*/
 * @return The classes
 * @throws ClassNotFoundException
 * @throws java.io.IOException
 */
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes.toArray(new Class[classes.size()]);
}

From source file:com.singular.utils.FileUtils.java

/**
 * Taken from apache hadoop project.//from  ww  w . j a v  a2 s  .co  m
 * Apache 2.0 license.
 *
 * @param className
 * @return
 */
public static String findContainingJar(Class className) {
    ClassLoader loader = className.getClassLoader();
    String classFile = className.getName().replaceAll("\\.", "/") + ".class";

    try {
        for (Enumeration itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();

            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:uk.co.danielrendall.imagetiler.utils.PackageFinder.java

/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package//from  w  ww . j a v a 2 s  .  co m
 * @return The classes
 * @throws ClassNotFoundException
 * @throws IOException
 */
private static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    ArrayList<Class> classes = new ArrayList<Class>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        try {
            classes.addAll(findClasses(resource, packageName));
        } catch (URISyntaxException e) {
            Log.app.warn("Problem with " + resource.toExternalForm() + " - " + e.getMessage());
        }
    }
    return classes.toArray(new Class[classes.size()]);
}