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.cloud.stream.config.BinderFactoryConfiguration.java

@Bean
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) {
    Map<String, BinderType> binderTypes = new HashMap<>();
    ClassLoader classLoader = configurableApplicationContext.getClassLoader();
    // the above can never be null since it will default to ClassUtils.getDefaultClassLoader(..)
    try {//from   w  ww .  j av a2  s.  c  om
        Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders");
        if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) {
            this.logger.debug("Failed to locate 'META-INF/spring.binders' resources on the classpath."
                    + " Assuming standard boot 'META-INF/spring.factories' configuration is used");
        } else {
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                UrlResource resource = new UrlResource(url);
                for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) {
                    binderTypes.put(binderType.getDefaultName(), binderType);
                }
            }
        }

    } catch (IOException | ClassNotFoundException e) {
        throw new BeanCreationException("Cannot create binder factory:", e);
    }
    return new DefaultBinderTypeRegistry(binderTypes);
}

From source file:io.trivium.Registry.java

public void reload() {
    final String PREFIX = "META-INF/services/";
    ClassLoader tvmLoader = ClassLoader.getSystemClassLoader();
    //types/* ww w .j a  v a 2  s .  c o m*/
    try {
        Enumeration<URL> resUrl = tvmLoader.getResources(PREFIX + "io.trivium.extension.Fact");
        while (resUrl.hasMoreElements()) {
            URL url = resUrl.nextElement();
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            List<String> lines = IOUtils.readLines(is, "UTF-8");
            is.close();
            for (String line : lines) {
                Class<? extends Fact> clazz = (Class<? extends Fact>) Class.forName(line);
                Fact prototype = clazz.newInstance();
                if (!types.containsKey(prototype.getTypeRef())) {
                    types.put(prototype.getTypeRef(), clazz);
                }
                logger.log(Level.FINE, "registered type {0}", prototype.getFactName());
            }
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "dynamically loading types failed", ex);
    }

    //bindings
    try {
        Enumeration<URL> resUrl = tvmLoader.getResources(PREFIX + "io.trivium.extension.Binding");
        while (resUrl.hasMoreElements()) {
            URL url = resUrl.nextElement();
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            List<String> lines = IOUtils.readLines(is, "UTF-8");
            is.close();
            for (String line : lines) {
                Class<? extends Binding> clazz = (Class<? extends Binding>) Class.forName(line);
                Binding prototype = clazz.newInstance();
                if (!bindings.containsKey(prototype.getTypeRef())) {
                    bindings.put(prototype.getTypeRef(), clazz);
                    //register prototype
                    bindingInstances.put(prototype.getTypeRef(), prototype);
                }
                logger.log(Level.FINE, "registered binding {0}", prototype.getName());
            }
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "dynamically loading bindings failed", ex);
    }

    //tasks
    try {
        Enumeration<URL> resUrl = tvmLoader.getResources(PREFIX + "io.trivium.extension.Task");
        while (resUrl.hasMoreElements()) {
            URL url = resUrl.nextElement();
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            List<String> lines = IOUtils.readLines(is, "UTF-8");
            is.close();
            for (String line : lines) {
                Class<? extends Task> clazz = (Class<? extends Task>) Class.forName(line);
                Task prototype = clazz.newInstance();
                if (!tasks.containsKey(prototype.getTypeRef())) {
                    tasks.put(prototype.getTypeRef(), clazz);
                }
                logger.log(Level.FINE, "registered binding {0}", prototype.getName());
            }
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "dynamically loading bindings failed", ex);
    }

    //testcases
    try {
        Enumeration<URL> resUrl = tvmLoader.getResources(PREFIX + "io.trivium.test.TestCase");
        while (resUrl.hasMoreElements()) {
            URL url = resUrl.nextElement();
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            List<String> lines = IOUtils.readLines(is, "UTF-8");
            is.close();
            for (String line : lines) {
                Class<? extends TestCase> clazz = (Class<? extends TestCase>) Class.forName(line);
                TestCase prototype = clazz.newInstance();
                if (!testcases.containsKey(prototype.getTypeRef())) {
                    testcases.put(prototype.getTypeRef(), prototype);
                }
                logger.log(Level.FINE, "registered testcase {0}", prototype.getTypeRef());
            }
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "dynamically loading test cases failed", ex);
    }
}

From source file:org.pentaho.pat.server.util.ResolverUtil.java

public void findInPackage(String packageName, Test... tests) {
    packageName = packageName.replace('.', '/');
    final ClassLoader loader = getClassLoader();
    Enumeration<URL> urls;
    try {/*from  w  w  w.j  av  a2  s  .  c o m*/
        urls = loader.getResources(packageName);
    } catch (IOException ioe) {
        LOG.trace("Could not read package: " + packageName, ioe); //$NON-NLS-1$
        return;
    }
    while (urls.hasMoreElements()) {
        try {
            URL eurl = urls.nextElement();
            String urlPath = eurl.toURI().toString();

            if (urlPath.indexOf('!') > 0) {
                urlPath = urlPath.substring(0, urlPath.indexOf('!'));
                if (urlPath.startsWith("jar:")) { //$NON-NLS-1$
                    urlPath = urlPath.substring(4);
                }
                eurl = new URL(urlPath);
            }
            String criteria = "";
            for (int i = 0; i < tests.length; i++) {
                if (tests[i] != null) {
                    criteria = criteria.concat(tests[i].toString()).concat(";");
                }
            }
            LOG.trace("Scanning for classes in [" + urlPath //$NON-NLS-1$
                    + "] matching criteria: " + criteria); //$NON-NLS-1$

            // is it a file?
            final File file = new File(URLDecoder.decode(eurl.getFile(), "UTF-8")); //$NON-NLS-1$
            // File file = new File(eurl.getFile());
            if (file.exists() && file.isDirectory()) {
                loadImplementationsInDirectory(packageName, file, tests);
            } else {
                loadImplementationsInJar(packageName, eurl, tests);
            }
        } catch (IOException e) {
            LOG.trace("could not read entries", e); //$NON-NLS-1$
        } catch (URISyntaxException se) {
            LOG.trace("could not read entries", se); //$NON-NLS-1$
        }
    }
}

From source file:org.amplafi.hivemind.util.CustomModuleDescriptorProvider.java

private List<Resource> getDescriptorResources(String resourcePath, ClassResolver resolver) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Processing modules visible to " + resolver);
    }//  w  w  w.  ja v  a  2s  .  com

    List<Resource> descriptors = new ArrayList<Resource>();

    ClassLoader loader = resolver.getClassLoader();
    Enumeration<URL> urls;

    try {
        urls = loader.getResources(resourcePath);
    } catch (IOException ex) {
        throw new ApplicationRuntimeException("UnableToFindModules(" + resolver + ", " + ex + ")", ex);
    }

    Pattern pattern = excludePattern == null ? null : Pattern.compile(excludePattern);

    while (urls.hasMoreElements()) {
        URL descriptorURL = urls.nextElement();

        String protocol = descriptorURL.getProtocol();

        if (excludeFiles && protocol.equals("file")) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ExcludeFiles therefore excluding " + descriptorURL);
            }
            continue;
        }

        if (excludeJars && protocol.equals("jar")) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ExcludeJars therefore excluding " + descriptorURL);
            }
            continue;
        }

        if (pattern != null && pattern.matcher(descriptorURL.toString()).matches()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("ExcludePattern therefore excluding " + descriptorURL);
            }
            continue;
        }

        LOG.debug("Will process hivemind main file: " + descriptorURL);
        descriptors.add(new URLResource(descriptorURL));
    }

    return descriptors;
}

From source file:uk.co.danielrendall.imagetiler.registry.PluginRegistryBuilder.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  . j a  v  a 2 s. c om
 * @return The classes
 * @throws ClassNotFoundException
 * @throws java.io.IOException
 */
private List<Class> getClasses(ClassLoader classLoader, String packageName)
        throws ClassNotFoundException, IOException {
    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;
}

From source file:com.liferay.portal.configuration.ExtletConfigurationImpl.java

/**
 * Find all extlet-portal.properties in all jars and override actual content
 *///from   w  w w.j a  v a2  s .c om
public void addExtletProperties() {
    ClassLoader classLoader = getClass().getClassLoader();
    String resourceName = EXTLET_PORTAL_PROPERTIES;

    try {
        // load all resource file from the classpath (all jars).
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            try {
                if (_log.isDebugEnabled()) {
                    _log.debug("Loading extlet-portal.properties from: " + resource);
                }
                InputStream is = new UrlResource(resource).getInputStream();

                if (is != null) {
                    addPropertiesToLiferay(is);
                }
                if (_log.isDebugEnabled()) {
                    _log.debug("Loading OK: " + resource);
                }
            } catch (Exception e2) {
                if (_log.isWarnEnabled()) {
                    _log.warn("Problem while loading " + resource, e2);
                }
            }
        }
    } catch (Exception e2) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem while loading classLoader resources: " + resourceName, e2);
        }
    }
}

From source file:architecture.ee.jdbc.sqlquery.factory.impl.AbstractSqlQueryFactory.java

protected void loadResourceLocations() {

    List<FileObject> list = new ArrayList<FileObject>();
    Repository repository = Bootstrap.getBootstrapComponent(Repository.class);
    /**/*from   w w  w .  java  2  s  .  c o m*/
     * log.debug("searching sql in jar ...");
     * if(!isEmpty(this.sqlLocations)){ for(Resource sqlLocation :
     * sqlLocations ){ if(sqlLocation == null) continue;
     * 
     * 
     * // log.debug(sqlLocation.toString()); } }
     **/

    /*
     * String value =
     * repository.getSetupApplicationProperties().getStringProperty(
     * "resources.sql", ""); String[] resources = StringUtils.split(value);
     * if( resources.length > 0 ){ log.debug(
     * "using custom sql resources instade of " + resourceLocations ); for(
     * String path : resources ){ try { FileObject f =
     * VFSUtils.resolveFile(path); if (f.exists()) { list.add(f); } } catch
     * (Throwable e) { log.warn(path + " not found.", e); } } }else{ for
     * (String path : resourceLocations) { try { FileObject f =
     * VFSUtils.resolveFile(path); if (f.exists()) { list.add(f); } } catch
     * (Throwable e) { log.warn(path + " not found.", e); } } }
     */

    try {
        log.debug("searching sql ...");
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> paths = cl.getResources("sql/");
        do {
            if (!paths.hasMoreElements())
                break;
            URL url = paths.nextElement();
            String pathToUse = "jar:" + url.getPath();
            log.debug("target:" + pathToUse);
            FileObject fo = VFSUtils.resolveFile(pathToUse);
            FileObject[] selected = findSqlFiles(fo);
            for (FileObject f : selected) {
                if (!list.contains(f)) {
                    list.add(f);
                }
            }
        } while (true);
    } catch (Throwable e) {
        log.warn(e);
    }

    for (FileObject fo : list) {
        try {
            log.debug("sql : " + fo.getName());
            if (!configuration.isResourceLoaded(fo.getName().getURI())) {
                buildSqlFromInputStream(fo.getContent().getInputStream(), configuration);
                configuration.addLoadedResource(fo.getName().getURI());
            }
        } catch (FileSystemException e) {
            log.warn(e);
        }
    }

}

From source file:org.castor.jaxb.resolver.JAXBPackageResolverCommand.java

/**
 * The one and only purpose resolver commands are good for ;-) . It can be
 * called with className and clazz set, so the command decides which suites
 * it best or at least one of the two arguments set.
 * /*from   w ww  .j  a v  a2s . c  om*/
 * @param packageName
 *            the name of the package to resolve
 * @param properties
 *            the Properties to be used at resolve
 * 
 * @return a Map of className and XMLClassDescriptor
 * 
 * @throws ResolverException
 *             in case that resolving fails fatally
 */
public Map<String, XMLClassDescriptor> resolve(final String packageName, final Map properties)
        throws ResolverException {

    String className;
    String fileName;
    String dirName;
    String packageToken;
    Class clazz;
    Enumeration<URL> resources;
    Map<String, XMLClassDescriptor> result = new HashMap<String, XMLClassDescriptor>();

    if ((packageName == null) || (packageName.length() == 0)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Package to load descriptors from is null or empty - nothing done.");
        }
        return result;
    }

    try {
        StringTokenizer packages = new StringTokenizer(packageName, ":");
        ClassLoader classLoader = getClass().getClassLoader();
        while (packages.hasMoreTokens()) {
            packageToken = packages.nextToken();
            dirName = packageToken.replace('.', '/');

            resources = classLoader.getResources(dirName);

            List<File> dirs = new ArrayList<File>();
            while (resources.hasMoreElements()) {
                URL resourceUrl = resources.nextElement();
                dirs.add(new File(resourceUrl.toURI()));
            }

            for (File dir : dirs) {
                for (File file : dir.listFiles()) {

                    if (file.getName().endsWith(".class")) {
                        fileName = file.getName();
                        className = new StringBuffer().append(packageName).append('.')
                                .append(fileName.substring(0, fileName.length() - 6)).toString();

                        clazz = Class.forName(className);

                        XMLClassDescriptor descriptor = classDescriptorBuilder
                                .buildClassDescriptor(classInfoBuilder.buildClassInfo(clazz), false);

                        result.put(className, descriptor);
                    }
                }
            }
        }

        return result;
    } catch (IOException e) {

        throw new ResolverException("Exception occurred when resolving package: " + packageName, e);
    } catch (URISyntaxException e) {

        throw new ResolverException("Exception occurred when resolving package: " + packageName, e);
    } catch (ClassNotFoundException e) {

        throw new ResolverException("Exception occurred when resolving package: " + packageName, e);
    }
}

From source file:org.drools.compiler.integrationtests.KieContainerTest.java

@Test
public void testClassLoaderGetResources() throws IOException {
    KieServices kieServices = KieServices.Factory.get();
    String drl1 = "package org.drools.testdrl;\n" + "rule R1 when\n" + "   $m : Object()\n" + "then\n"
            + "end\n";
    Resource resource1 = kieServices.getResources().newReaderResource(new StringReader(drl1), "UTF-8");
    resource1.setTargetPath("org/drools/testdrl/rules1.drl");

    String drl2 = "package org.drools.testdrl;\n" + "rule R2 when\n" + "   $m : Object()\n" + "then\n"
            + "end\n";
    Resource resource2 = kieServices.getResources().newReaderResource(new StringReader(drl2), "UTF-8");
    resource2.setTargetPath("org/drools/testdrl/rules2.drl");

    String java3 = "package org.drools.testjava;\n" + "public class Message {}";
    Resource resource3 = kieServices.getResources().newReaderResource(new StringReader(java3), "UTF-8");
    resource3.setTargetPath("org/drools/testjava/Message.java");
    resource3.setResourceType(ResourceType.JAVA);

    String kmodule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<kmodule xmlns=\"http://www.drools.org/xsd/kmodule\">\n"
            + "  <kbase name=\"testKbase\" packages=\"org.drools.testdrl\">\n"
            + "    <ksession name=\"testKsession\"/>\n" + "  </kbase>\n" + "</kmodule>";

    // Create an in-memory jar for version 1.0.0
    ReleaseId releaseId = kieServices.newReleaseId("org.kie", "test-delete", "1.0.0");
    createAndDeployJar(kieServices, kmodule, releaseId, resource1, resource2, resource3);

    KieContainer kieContainer = kieServices.newKieContainer(releaseId);

    ClassLoader classLoader = kieContainer.getClassLoader();
    assertEnumerationSize(1, classLoader.getResources("org/drools/testjava")); // no trailing "/"

    assertEnumerationSize(1, classLoader.getResources("org/drools/testdrl/")); // trailing "/" to test both variants
    // make sure the package resource correctly lists all its child resources (files in this case)
    URL url = classLoader.getResources("org/drools/testdrl").nextElement();
    List<String> lines = IOUtils.readLines(url.openStream());
    Assertions.assertThat(lines).contains("rules1.drl", "rules1.drl.properties", "rules2.drl",
            "rules2.drl.properties");

    assertUrlEnumerationContainsMatch("^mfs\\:/$", classLoader.getResources(""));
}

From source file:org.hippoecm.frontend.editor.layout.LayoutProvider.java

public LayoutProvider(IModel<ClassLoader> loaderModel) {
    this.classLoaderModel = loaderModel;

    layouts = new TreeMap<String, LayoutEntry>();
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from www.  j  a v  a2s .c  om*/
    dbf.setValidating(false);

    final ClassLoader loader = classLoaderModel.getObject();
    if (loader == null) {
        log.error("No class-loader could be obtained from the user session, skip reading layout extensions.");
        return;
    }

    try {
        for (Enumeration<URL> iter = loader.getResources("hippoecm-layouts.xml"); iter.hasMoreElements();) {
            URL configurationURL = iter.nextElement();
            InputStream stream = configurationURL.openStream();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(stream);

            Element element = document.getDocumentElement();
            if (!"layouts".equals(element.getNodeName())) {
                throw new RuntimeException("unable to parse layout: no layout node found");
            }

            NodeList nodes = element.getElementsByTagName("layout");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element padElement = (Element) nodes.item(i);

                NodeList plugins = padElement.getElementsByTagName("plugin");
                if (plugins.getLength() != 1) {
                    throw new RuntimeException(
                            "Invalid layout, 0 or more than 1 plugin child nodes found at " + configurationURL);
                }

                Element pluginElement = (Element) plugins.item(0);
                Node childNode = pluginElement.getFirstChild();
                String plugin = childNode.getNodeValue();
                addLayoutEntry(plugin, null);

                NodeList variants = padElement.getElementsByTagName("variant");
                for (int j = 0; j < variants.getLength(); j++) {
                    Element variantElement = (Element) variants.item(j);
                    Node variantNode = variantElement.getFirstChild();
                    String variant = variantNode.getNodeValue();
                    addLayoutEntry(plugin, variant);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error while reading layouts extension", e);
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException("Parser configuration error:", ex);
    } catch (SAXException ex) {
        throw new RuntimeException("SAX error:", ex);
    }
}