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:com.liferay.portal.service.impl.LayoutTemplateLocalServiceImpl.java

public List<ObjectValuePair<String, Boolean>> init(String servletContextName, ServletContext servletContext,
        String[] xmls, PluginPackage pluginPackage) {

    List<ObjectValuePair<String, Boolean>> layoutTemplateIds = new ArrayList<ObjectValuePair<String, Boolean>>();

    try {//from  w  w w.  j a  va2 s. c  om
        for (int i = 0; i < xmls.length; i++) {
            Set<ObjectValuePair<String, Boolean>> curLayoutTemplateIds = _readLayoutTemplates(
                    servletContextName, servletContext, xmls[i], pluginPackage);

            Iterator<ObjectValuePair<String, Boolean>> itr = curLayoutTemplateIds.iterator();

            while (itr.hasNext()) {
                ObjectValuePair<String, Boolean> ovp = itr.next();

                if (!layoutTemplateIds.contains(ovp)) {
                    layoutTemplateIds.add(ovp);
                }
            }
        }

        Set<ObjectValuePair<String, Boolean>> curLayoutTemplateIds = new HashSet<ObjectValuePair<String, Boolean>>();

        ClassLoader classLoader = getClass().getClassLoader();
        // load xmls
        String resourceName = "WEB-INF/liferay-layout-templates-ext.xml";
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
            _log.debug("No " + resourceName + " has been found");
        }
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (_log.isDebugEnabled()) {
                _log.debug("Loading " + resourceName + " from: " + resource);
            }

            if (resource == null) {
                continue;
            }

            InputStream is = new UrlResource(resource).getInputStream();
            try {
                String xmlExt = IOUtils.toString(is, "UTF-8");
                curLayoutTemplateIds.addAll(
                        _readLayoutTemplates(servletContextName, servletContext, xmlExt, pluginPackage));
            } catch (Exception e) {
                _log.error("Problem while loading file " + resource, e);
            } finally {
                is.close();
            }
        }

        Iterator<ObjectValuePair<String, Boolean>> itr = curLayoutTemplateIds.iterator();

        while (itr.hasNext()) {
            ObjectValuePair<String, Boolean> ovp = itr.next();

            if (!layoutTemplateIds.contains(ovp)) {
                layoutTemplateIds.add(ovp);
            }
        }
    } catch (Exception e) {
        _log.error(e, e);
    }

    return layoutTemplateIds;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Loads properties from all resource with given name.
 *
 * @param name/*from  w w  w. j  a  v  a 2  s . c  o  m*/
 *            the resource name
 * @return properties loaded from all found resources
 * @throws java.io.IOException
 *             if an error occurred when reading properties file
 *
 * @see java.lang.ClassLoader#getResources(String)
 * @see java.util.Properties#load(java.io.InputStream)
 */
public static Properties loadPropertiesResources(String name) throws IOException {
    Properties rProps = new Properties();

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> rEnum = loader.getResources(name);

    while (rEnum.hasMoreElements()) {
        InputStream ins = rEnum.nextElement().openStream();

        try {
            rProps.load(ins);
        } finally {
            close(ins);
        }
    }

    return rProps;
}

From source file:com.liferay.portal.model.ModelHintsImpl.java

public void afterPropertiesSet() {
    _hintCollections = new HashMap<String, Map<String, String>>();
    _defaultHints = new HashMap<String, Map<String, String>>();
    _modelFields = new HashMap<String, Object>();
    _models = new TreeSet<String>();

    try {//from w  w w.  ja va2 s.com
        ClassLoader classLoader = getClass().getClassLoader();

        String[] configs = StringUtil.split(PropsUtil.get(PropsKeys.MODEL_HINTS_CONFIGS));

        for (int i = 0; i < configs.length; i++) {
            if (!configs[i].startsWith("classpath*:")) {
                read(classLoader, configs[i]);
            } else {
                String configName = configs[i].substring("classpath*:".length());
                Enumeration<URL> resources = classLoader.getResources(configName);
                if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
                    _log.debug("No " + configName + " has been found");
                }
                while (resources.hasMoreElements()) {
                    URL resource = resources.nextElement();
                    if (_log.isDebugEnabled()) {
                        _log.debug("Loading " + configName + " from: " + resource);
                    }
                    InputStream is = new UrlResource(resource).getInputStream();

                    if (is != null) {
                        read(classLoader, resource.toString(), is);
                    }
                }
            }
        }

    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.portal.service.impl.ThemeLocalServiceImpl.java

public List<String> init(String servletContextName, ServletContext servletContext, String themesPath,
        boolean loadFromServletContext, String[] xmls, PluginPackage pluginPackage) {

    List<String> themeIdsList = new ArrayList<String>();

    try {/*from w  w w. j a  v  a 2 s .  c  o m*/
        for (int i = 0; i < xmls.length; i++) {
            Set<String> themeIds = _readThemes(servletContextName, servletContext, themesPath,
                    loadFromServletContext, xmls[i], pluginPackage);

            for (String themeId : themeIds) {
                if (!themeIdsList.contains(themeId)) {
                    themeIdsList.add(themeId);
                }
            }
        }

        Set<String> themeIds = new HashSet<String>();
        ClassLoader classLoader = getClass().getClassLoader();
        // load xmls
        String resourceName = "WEB-INF/liferay-look-and-feel-ext.xml";
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
            _log.debug("No " + resourceName + " has been found");
        }
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (_log.isDebugEnabled()) {
                _log.debug("Loading " + resourceName + " from: " + resource);
            }

            if (resource == null) {
                continue;
            }

            InputStream is = new UrlResource(resource).getInputStream();
            try {
                String xmlExt = IOUtils.toString(is, "UTF-8");
                themeIds.addAll(_readThemes(servletContextName, servletContext, themesPath,
                        loadFromServletContext, xmlExt, pluginPackage));
            } catch (Exception e) {
                _log.error("Problem while loading file " + resource, e);
            } finally {
                is.close();
            }
        }

        for (String themeId : themeIds) {
            if (!themeIdsList.contains(themeId)) {
                themeIdsList.add(themeId);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    _themesPool.clear();

    return themeIdsList;
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all class location resources with the given path via the ClassLoader.
 * Called by {@link #findAllClassPathResources(String)}.
 * @param path the absolute path within the classpath (never a leading slash)
 * @return a mutable Set of matching Resource instances
 * @since 4.1.1// w ww . ja  va2s.  c om
 */
protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
    Set<Resource> result = new LinkedHashSet<>(16);
    ClassLoader cl = getClassLoader();
    Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
    while (resourceUrls.hasMoreElements()) {
        URL url = resourceUrls.nextElement();
        result.add(convertClassLoaderURL(url));
    }
    if ("".equals(path)) {
        // The above result is likely to be incomplete, i.e. only containing file system references.
        // We need to have pointers to each of the jar files on the classpath as well...
        addAllClassLoaderJarRoots(cl, result);
    }
    return result;
}

From source file:com.ocpsoft.pretty.faces.el.resolver.FacesConfigBeanNameResolver.java

/**
 * Returns a set of faces-config.xml files. This set includes the default
 * configuration file, all additional files mentioned via the
 * <code>javax.faces.CONFIG_FILES</code> init parameter and all files found
 * in META-INF folders./*from   ww w .  java 2  s  . c  o  m*/
 * 
 * @param servletContext
 *           The ServletContext
 * @param classLoader
 *           The classloader used to find files in META-INF directories
 * @return A set of URLs
 */
private Set<URL> getFacesConfigFiles(ServletContext servletContext, ClassLoader classLoader) {

    // set of URLs to process
    Set<URL> result = new HashSet<URL>();

    try {

        // get default faces-config.xml
        URL defaultFacesConfig = servletContext.getResource(WEB_INF_FACES_CONFIG_XML);
        if (defaultFacesConfig != null) {
            result.add(defaultFacesConfig);
        }

        // get additional configuration files from init parameter
        result.addAll(getConfigFilesFromInitParameter(servletContext));

        // Find configuration files META-INF directories
        try {
            Enumeration<URL> resources = classLoader.getResources(META_INF_FACES_CONFIG_XML);
            while (resources.hasMoreElements()) {
                result.add(resources.nextElement());
            }
        } catch (IOException e) {
            log.error("Failed to load faces-config.xml files from META-INF directories", e);
        }

    } catch (MalformedURLException e) {
        // should not happen, because URLs are hard-coded
        throw new IllegalArgumentException(e);
    }

    return result;
}

From source file:org.apache.camel.impl.DefaultPackageScanClassResolver.java

/**
 * Strategy to get the resources by the given classloader.
 * <p/>// ww  w.  j a v a 2 s  . c  om
 * Notice that in WebSphere platforms there is a {@link WebSpherePackageScanClassResolver}
 * to take care of WebSphere's odditiy of resource loading.
 *
 * @param loader  the classloader
 * @param packageName   the packagename for the package to load
 * @return  URL's for the given package
 * @throws IOException is thrown by the classloader
 */
protected Enumeration<URL> getResources(ClassLoader loader, String packageName) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("Getting resource URL for package: " + packageName + " with classloader: " + loader);
    }

    // If the URL is a jar, the URLClassloader.getResources() seems to require a trailing slash.  The
    // trailing slash is harmless for other URLs  
    if (!packageName.endsWith("/")) {
        packageName = packageName + "/";
    }
    return loader.getResources(packageName);
}

From source file:org.sonar.classloader.ClassloaderBuilderTest.java

/**
 * - parent contains B and version 1 of A
 * - child contains version 2 of A -> sees B and version 2 of A
 *///  w w  w.j  av  a  2  s  .  com
@Test
public void self_first_ordering() throws Exception {

    Map<String, ClassLoader> newClassloaders = sut.newClassloader("the-parent")
            .addURL("the-parent", new File("tester/a.jar").toURL())
            .addURL("the-parent", new File("tester/b.jar").toURL())

            .newClassloader("the-child").addURL("the-child", new File("tester/a_v2.jar").toURL())
            .setParent("the-child", "the-parent", Mask.ALL)
            .setLoadingOrder("the-child", ClassloaderBuilder.LoadingOrder.SELF_FIRST).build();

    ClassLoader parent = newClassloaders.get("the-parent");
    assertThat(canLoadMethod(parent, "A", "version1")).isTrue();
    assertThat(canLoadMethod(parent, "A", "version2")).isFalse();
    assertThat(IOUtils.toString(parent.getResource("a.txt"))).startsWith("version 1 of a.txt");

    ClassLoader child = newClassloaders.get("the-child");
    assertThat(canLoadClass(child, "B")).isTrue();
    assertThat(canLoadMethod(child, "A", "version1")).isFalse();
    assertThat(canLoadMethod(child, "A", "version2")).isTrue();
    assertThat(IOUtils.toString(child.getResource("a.txt"))).startsWith("version 2 of a.txt");
    assertThat(Collections.list(child.getResources("b.txt"))).hasSize(1);
    ArrayList<URL> resources = Collections.list(child.getResources("a.txt"));
    assertThat(resources).hasSize(2);
    assertThat(IOUtils.toString(resources.get(0))).startsWith("version 2 of a.txt");
    assertThat(IOUtils.toString(resources.get(1))).startsWith("version 1 of a.txt");
}

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
    String pckgname = pkg;//from w  w w .  ja va2 s.  c om
    ArrayList<File> directories = new ArrayList<File>();
    try {
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cl.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)");
        }
        throw new ClassNotFoundException(
                pckgname + " might not be a valid package because the encoding is unsupported.");
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("IOException was thrown when trying to get all resources for " + pckgname);
        }
        throw new ClassNotFoundException(
                "An IOException error was thrown when trying to get all of the resources for " + pckgname);
    }

    ArrayList<Class> classes = new ArrayList<Class>();
    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (log.isDebugEnabled()) {
            log.debug("  Adding JAXB classes from directory: " + directory.getName());
        }
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    // TODO Java2 Sec
                    String className = pckgname + '.' + file.substring(0, file.length() - 6);
                    try {
                        Class clazz = forName(className, false, getContextClassLoader());
                        // Don't add any interfaces or JAXWS specific classes.
                        // Only classes that represent data and can be marshalled
                        // by JAXB should be added.
                        if (!clazz.isInterface()
                                && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null
                                        || ClassUtils.getDefaultPublicConstructor(clazz) != null)
                                && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz)
                                && !Exception.class.isAssignableFrom(clazz)) {

                            // Ensure that all the referenced classes are loadable too
                            clazz.getDeclaredMethods();
                            clazz.getDeclaredFields();

                            if (log.isDebugEnabled()) {
                                log.debug("Adding class: " + file);
                            }
                            classes.add(clazz);

                            // REVIEW:
                            // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present.
                            // This is a hack until we can determine how to get this information.

                            // The arrayName and loadable name are different.  Get the loadable
                            // name, load the array class, and add it to our list
                            //className += "[]";
                            //String loadableName = ClassUtils.getLoadableClassName(className);

                            //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader());
                        }
                        //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                        //does not extend Exception
                    } catch (Throwable e) {
                        if (log.isDebugEnabled()) {
                            log.debug("Tried to load class " + className
                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                            log.debug("  The reason that class could not be loaded:" + e.toString());
                            log.trace(JavaUtils.stackToString(e));
                        }
                    }

                }
            }
        }
    }

    return classes;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
    String pckgname = pkg;/*from w ww .j a va 2 s .c o  m*/
    ArrayList<File> directories = new ArrayList<File>();
    try {
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cl.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)");
        }
        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr2", pckgname));
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("IOException was thrown when trying to get all resources for " + pckgname);
        }
        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr3", pckgname));
    }

    ArrayList<Class> classes = new ArrayList<Class>();
    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (log.isDebugEnabled()) {
            log.debug("  Adding JAXB classes from directory: " + directory.getName());
        }
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    // TODO Java2 Sec
                    String className = pckgname + '.' + file.substring(0, file.length() - 6);
                    try {
                        Class clazz = forName(className, false, getContextClassLoader());
                        // Don't add any interfaces or JAXWS specific classes.  
                        // Only classes that represent data and can be marshalled 
                        // by JAXB should be added.
                        if (!clazz.isInterface()
                                && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null
                                        || ClassUtils.getDefaultPublicConstructor(clazz) != null)
                                && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz)
                                && !java.lang.Exception.class.isAssignableFrom(clazz)) {

                            // Ensure that all the referenced classes are loadable too
                            clazz.getDeclaredMethods();
                            clazz.getDeclaredFields();

                            if (log.isDebugEnabled()) {
                                log.debug("Adding class: " + file);
                            }
                            classes.add(clazz);

                            // REVIEW:
                            // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present.
                            // This is a hack until we can determine how to get this information.

                            // The arrayName and loadable name are different.  Get the loadable
                            // name, load the array class, and add it to our list
                            //className += "[]";
                            //String loadableName = ClassUtils.getLoadableClassName(className);

                            //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader());
                        }
                        //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                        //does not extend Exception
                    } catch (Throwable e) {
                        if (log.isDebugEnabled()) {
                            log.debug("Tried to load class " + className
                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                            log.debug("  The reason that class could not be loaded:" + e.toString());
                            log.trace(JavaUtils.stackToString(e));
                        }
                    }

                }
            }
        }
    }

    return classes;
}