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.springframework.core.SpringFactoriesLoader.java

private static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader,
        String factoriesLocation) {

    String factoryClassName = factoryClass.getName();

    try {//from  ww  w  .  j av a 2 s. co  m
        List<String> result = new ArrayList<String>();
        Enumeration<URL> urls = classLoader.getResources(factoriesLocation);
        while (urls.hasMoreElements()) {
            URL url = (URL) urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName()
                + "] factories from location [" + factoriesLocation + "]", ex);
    }

}

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

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null)
        return result;
    try {/*from   w  w  w. j ava2s .com*/
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION)
                : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                List<String> factoryClassNames = Arrays
                        .asList(StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
                result.addAll((String) entry.getKey(), factoryClassNames);
            }
        }
        cache.put(classLoader, result);
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException(
                "Unable to load factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

From source file:org.apache.cloudstack.framework.serializer.OnwireClassRegistry.java

static Set<Class<?>> getClasses(ClassLoader loader, String packageName) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    String path = packageName.replace('.', '/');
    try {// w ww. jav  a 2  s.co  m
        Enumeration<URL> resources = loader.getResources(path);
        if (resources != null) {
            while (resources.hasMoreElements()) {
                String filePath = resources.nextElement().getFile();
                // WINDOWS HACK
                if (filePath.indexOf("%20") > 0)
                    filePath = filePath.replaceAll("%20", " ");
                if (filePath != null) {
                    if ((filePath.indexOf("!") > 0) && (filePath.indexOf(".jar") > 0)) {
                        String jarPath = filePath.substring(0, filePath.indexOf("!"))
                                .substring(filePath.indexOf(":") + 1);
                        // WINDOWS HACK
                        if (jarPath.indexOf(":") >= 0)
                            jarPath = jarPath.substring(1);
                        classes.addAll(getFromJARFile(jarPath, path));
                    } else {
                        classes.addAll(getFromDirectory(new File(filePath), packageName));
                    }
                }
            }
        }
    } catch (IOException e) {
        s_logger.debug("Encountered IOException", e);
    } catch (ClassNotFoundException e) {
    }
    return classes;
}

From source file:com.sfxie.extension.spring4.properties.PropertiesLoaderUtils.java

/**
 * Load all properties from the specified class path resource
 * (in ISO-8859-1 encoding), using the given class loader.
 * <p>Merges properties if more than one resource of the same name
 * found in the class path./*from   w  w  w . j  a va2 s .c o  m*/
 * @param resourceName the name of the class path resource
 * @param classLoader the ClassLoader to use for loading
 * (or {@code null} to use the default class loader)
 * @return the populated Properties instance
 * @throws IOException if loading failed
 */
public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException {
    Assert.notNull(resourceName, "Resource name must not be null");
    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = ClassUtils.getDefaultClassLoader();
    }
    Enumeration<URL> urls = (classLoaderToUse != null ? classLoaderToUse.getResources(resourceName)
            : ClassLoader.getSystemResources(resourceName));
    Properties props = new Properties();
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        URLConnection con = url.openConnection();
        ResourceUtils.useCachesIfNecessary(con);
        InputStream is = con.getInputStream();
        try {
            if (resourceName != null && resourceName.endsWith(XML_FILE_EXTENSION)) {
                props.loadFromXML(is);
            } else {
                props.load(is);
            }
        } finally {
            is.close();
        }
    }
    return props;
}

From source file:io.lightlink.utils.ClasspathScanUtils.java

public static List<String> getResourcesFromPackage(String packageName) throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> packageURLs;
    ArrayList<String> names = new ArrayList<String>();

    packageName = packageName.replace(".", "/");
    packageURLs = classLoader.getResources(packageName);

    while (packageURLs.hasMoreElements()) {
        URL packageURL = packageURLs.nextElement();
        // loop through files in classpath

        if (packageURL.getProtocol().equals("jar")) {
            String jarFileName;/*from w  w w. j a va2  s  . c o m*/
            JarFile jf;
            Enumeration<JarEntry> jarEntries;
            String entryName;

            // build jar file name, then loop through zipped entries
            jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
            jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
            jf = new JarFile(jarFileName);
            jarEntries = jf.entries();
            while (jarEntries.hasMoreElements()) {
                entryName = jarEntries.nextElement().getName();
                if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
                    entryName = entryName.substring(packageName.length());
                    names.add(entryName);
                }
            }

        } else {

            findFromDirectory(packageURL, names);
        }
    }

    return names;
}

From source file:org.apache.abdera2.common.Discover.java

public static Enumeration<URL> locateResources(String id, ClassLoader loader, Class<?> callingClass)
        throws IOException {
    Enumeration<URL> urls = loader.getResources(id);
    if (urls == null && id.startsWith("/"))
        urls = loader.getResources(id.substring(1));
    if (urls == null)
        urls = locateResources(id, Discover.class.getClassLoader(), callingClass);
    if (urls == null)
        urls = locateResources(id, callingClass.getClassLoader(), callingClass);
    return urls;//from   www  .  j av a2  s.c o m
}

From source file:org.flowable.app.engine.AppEngines.java

/**
 * Initializes all App engines that can be found on the classpath for resources <code>flowable.app.cfg.xml</code> and for resources <code>flowable-app-context.xml</code> (Spring style
 * configuration)./*from w  w w  . j  a va  2 s  . c  o  m*/
 */
public static synchronized void init() {
    if (!isInitialized()) {
        if (appEngines == null) {
            // Create new map to store CMMN engines if current map is null
            appEngines = new HashMap<>();
        }
        ClassLoader classLoader = AppEngines.class.getClassLoader();
        Enumeration<URL> resources = null;
        try {
            resources = classLoader.getResources("flowable.app.cfg.xml");
        } catch (IOException e) {
            throw new FlowableException("problem retrieving flowable.cmmn.cfg.xml resources on the classpath: "
                    + System.getProperty("java.class.path"), e);
        }

        // Remove duplicated configuration URL's using set. Some
        // classloaders may return identical URL's twice, causing duplicate startups
        Set<URL> configUrls = new HashSet<>();
        while (resources.hasMoreElements()) {
            configUrls.add(resources.nextElement());
        }
        for (Iterator<URL> iterator = configUrls.iterator(); iterator.hasNext();) {
            URL resource = iterator.next();
            LOGGER.info("Initializing app engine using configuration '{}'", resource);
            initAppEngineFromResource(resource);
        }

        try {
            resources = classLoader.getResources("flowable-app-context.xml");
        } catch (IOException e) {
            throw new FlowableException(
                    "problem retrieving flowable-app-context.xml resources on the classpath: "
                            + System.getProperty("java.class.path"),
                    e);
        }

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            LOGGER.info("Initializing app engine using Spring configuration '{}'", resource);
            initAppEngineFromSpringResource(resource);
        }

        setInitialized(true);
    } else {
        LOGGER.info("App engines already initialized");
    }
}

From source file:org.flowable.cmmn.engine.CmmnEngines.java

/**
 * Initializes all CMMN engines that can be found on the classpath for resources <code>flowable.cmmn.cfg.xml</code> and for resources <code>flowable-cmmn-context.xml</code> (Spring style
 * configuration)./*w  w w . ja va  2  s .  co  m*/
 */
public static synchronized void init() {
    if (!isInitialized()) {
        if (cmmnEngines == null) {
            // Create new map to store CMMN engines if current map is null
            cmmnEngines = new HashMap<>();
        }
        ClassLoader classLoader = CmmnEngines.class.getClassLoader();
        Enumeration<URL> resources = null;
        try {
            resources = classLoader.getResources("flowable.cmmn.cfg.xml");
        } catch (IOException e) {
            throw new FlowableException("problem retrieving flowable.cmmn.cfg.xml resources on the classpath: "
                    + System.getProperty("java.class.path"), e);
        }

        // Remove duplicated configuration URL's using set. Some
        // classloaders may return identical URL's twice, causing duplicate startups
        Set<URL> configUrls = new HashSet<>();
        while (resources.hasMoreElements()) {
            configUrls.add(resources.nextElement());
        }
        for (Iterator<URL> iterator = configUrls.iterator(); iterator.hasNext();) {
            URL resource = iterator.next();
            LOGGER.info("Initializing cmmn engine using configuration '{}'", resource);
            initCmmnEngineFromResource(resource);
        }

        try {
            resources = classLoader.getResources("flowable-cmmn-context.xml");
        } catch (IOException e) {
            throw new FlowableException(
                    "problem retrieving flowable-cmmn-context.xml resources on the classpath: "
                            + System.getProperty("java.class.path"),
                    e);
        }

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            LOGGER.info("Initializing cmmn engine using Spring configuration '{}'", resource);
            initCmmnEngineFromSpringResource(resource);
        }

        setInitialized(true);
    } else {
        LOGGER.info("Cmmn engines already initialized");
    }
}

From source file:org.flowable.idm.engine.IdmEngines.java

/**
 * Initializes all idm engines that can be found on the classpath for resources <code>flowable.idm.cfg.xml</code> and for resources <code>flowable-idm-context.xml</code> (Spring style
 * configuration)./*from   www  .  j  ava2  s.c  o m*/
 */
public static synchronized void init() {
    if (!isInitialized()) {
        if (idmEngines == null) {
            // Create new map to store idm engines if current map is null
            idmEngines = new HashMap<>();
        }
        ClassLoader classLoader = IdmEngines.class.getClassLoader();
        Enumeration<URL> resources = null;
        try {
            resources = classLoader.getResources("flowable.idm.cfg.xml");
        } catch (IOException e) {
            throw new FlowableException("problem retrieving flowable.idm.cfg.xml resources on the classpath: "
                    + System.getProperty("java.class.path"), e);
        }

        // Remove duplicated configuration URL's using set. Some
        // classloaders may return identical URL's twice, causing duplicate startups
        Set<URL> configUrls = new HashSet<>();
        while (resources.hasMoreElements()) {
            configUrls.add(resources.nextElement());
        }
        for (Iterator<URL> iterator = configUrls.iterator(); iterator.hasNext();) {
            URL resource = iterator.next();
            LOGGER.info("Initializing idm engine using configuration '{}'", resource.toString());
            initIdmEngineFromResource(resource);
        }

        try {
            resources = classLoader.getResources("flowable-idm-context.xml");
        } catch (IOException e) {
            throw new FlowableException(
                    "problem retrieving flowable-idm-context.xml resources on the classpath: "
                            + System.getProperty("java.class.path"),
                    e);
        }

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            LOGGER.info("Initializing idm engine using Spring configuration '{}'", resource.toString());
            initIdmEngineFromSpringResource(resource);
        }

        setInitialized(true);
    } else {
        LOGGER.info("Idm engines already initialized");
    }
}

From source file:org.activiti.form.engine.FormEngines.java

/**
 * Initializes all dmn engines that can be found on the classpath for resources <code>activiti.dmn.cfg.xml</code> and for resources <code>activiti-dmn-context.xml</code> (Spring style
 * configuration)./*from w ww .j av  a  2 s. c  o  m*/
 */
public synchronized static void init() {
    if (!isInitialized()) {
        if (formEngines == null) {
            // Create new map to store dmn engines if current map is null
            formEngines = new HashMap<String, FormEngine>();
        }
        ClassLoader classLoader = FormEngines.class.getClassLoader();
        Enumeration<URL> resources = null;
        try {
            resources = classLoader.getResources("activiti.form.cfg.xml");
        } catch (IOException e) {
            throw new ActivitiException("problem retrieving activiti.form.cfg.xml resources on the classpath: "
                    + System.getProperty("java.class.path"), e);
        }

        // Remove duplicated configuration URL's using set. Some
        // classloaders may return identical URL's twice, causing duplicate startups
        Set<URL> configUrls = new HashSet<URL>();
        while (resources.hasMoreElements()) {
            configUrls.add(resources.nextElement());
        }
        for (Iterator<URL> iterator = configUrls.iterator(); iterator.hasNext();) {
            URL resource = iterator.next();
            log.info("Initializing form engine using configuration '{}'", resource.toString());
            initFormEngineFromResource(resource);
        }

        try {
            resources = classLoader.getResources("activiti-form-context.xml");
        } catch (IOException e) {
            throw new ActivitiException(
                    "problem retrieving activiti-form-context.xml resources on the classpath: "
                            + System.getProperty("java.class.path"),
                    e);
        }

        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            log.info("Initializing form engine using Spring configuration '{}'", resource.toString());
            initFormEngineFromSpringResource(resource);
        }

        setInitialized(true);
    } else {
        log.info("Form engines already initialized");
    }
}