List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:org.nuxeo.runtime.test.NXRuntimeTestCase.java
public static URL getResource(String name) { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); String callerName = Thread.currentThread().getStackTrace()[2].getClassName(); final String relativePath = callerName.replace('.', '/').concat(".class"); final String fullPath = loader.getResource(relativePath).getPath(); final String basePath = fullPath.substring(0, fullPath.indexOf(relativePath)); Enumeration<URL> resources; try {// ww w. j a v a 2s. c o m resources = loader.getResources(name); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (resource.getPath().startsWith(basePath)) { return resource; } } } catch (IOException e) { return null; } return loader.getResource(name); }
From source file:com.streamsets.datacollector.cluster.BaseClusterProvider.java
@VisibleForTesting static Properties readDataCollectorProperties(ClassLoader cl) throws IOException { Properties properties = new Properties(); while (cl != null) { Enumeration<URL> urls = cl.getResources(DATA_COLLECTOR_LIBRARY_PROPERTIES); if (urls != null) { while (urls.hasMoreElements()) { URL url = urls.nextElement(); LOG.trace("Loading data collector library properties: {}", url); try (InputStream inputStream = url.openStream()) { properties.load(inputStream); }/*from w w w . j a v a 2s. c o m*/ } } cl = cl.getParent(); } LOG.trace("Final properties: {} ", properties); return properties; }
From source file:io.spring.gradle.testkit.junit.rules.TestKit.java
public GradleRunner withProjectResource(String projectResourceName) throws IOException, URISyntaxException { ClassLoader classLoader = getClass().getClassLoader(); Enumeration<URL> resources = classLoader.getResources(projectResourceName); if (!resources.hasMoreElements()) { throw new IOException("Cannot find resource " + projectResourceName + " with " + classLoader); }/*from w ww . j a va 2 s . c o m*/ URL resourceUrl = resources.nextElement(); File projectDir = Paths.get(resourceUrl.toURI()).toFile(); return withProjectDir(projectDir); }
From source file:org.xenei.classpathutils.ClassPathUtils.java
/** * Find all classes accessible from the class loader which belong to the * given package and sub packages./* w w w. ja v a 2s . c o m*/ * * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to * support use of JAR files * * @param classLoader * The class loader to load the classes from. * @param packageName * The package name to locate the classes in. * @param filter * The filter for the classes. * @return A collection of Class objects */ public static Collection<Class<?>> getClasses(final ClassLoader classLoader, final String packageName, final ClassPathFilter filter) { if (classLoader == null) { LOG.error("Class loader may not be null."); return Collections.emptyList(); } if (packageName == null) { LOG.error("Package name may not be null."); return Collections.emptyList(); } String dirName = packageName.replace('.', '/'); Enumeration<URL> resources; try { resources = classLoader.getResources(dirName); } catch (final IOException e1) { LOG.error(e1.toString()); return Collections.emptyList(); } final Set<Class<?>> classes = new HashSet<Class<?>>(); final Set<String> directories = new HashSet<String>(); if (resources.hasMoreElements()) { while (resources.hasMoreElements()) { final URL resource = resources.nextElement(); String dir = resource.getPath(); if (!directories.contains(dir)) { directories.add(dir); try { for (final String clazz : findClasses(dir, packageName, filter)) { try { LOG.debug("Adding class {}", clazz); classes.add(Class.forName(clazz, false, classLoader)); } catch (final ClassNotFoundException e) { LOG.warn(e.toString()); } } } catch (final IOException e) { LOG.warn(e.toString()); } } } } else { if (packageName.length() > 0) { // there are no resources at that path so see if it is a class try { classes.add(Class.forName(packageName, false, classLoader)); } catch (final ClassNotFoundException e) { LOG.warn(String.format("'%s' was neither a package name nor a class name", packageName)); } } } return classes; }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Finds all classes defined in a given package. * * @author paouelle/*from w w w .j av a 2s. co m*/ * * @param pkg the package from which to find all defined classes * @param cl the classloader to find the classes with * @return the non-<code>null</code> collection of all classes defined in the * given package * @throws NullPointerException if <code>pkg</code> or <code>cl</code> is * <code>null</code> */ public static Collection<Class<?>> findClasses(String pkg, ClassLoader cl) { org.apache.commons.lang3.Validate.notNull(pkg, "invalid null pkg"); final String scannedPath = pkg.replace('.', File.separatorChar); final Enumeration<URL> resources; try { resources = cl.getResources(scannedPath); } catch (IOException e) { throw new IllegalArgumentException("Unable to get resources from path '" + scannedPath + "'. Are you sure the given '" + pkg + "' package exists?", e); } final List<Class<?>> classes = new LinkedList<>(); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); if ("jar".equals(url.getProtocol())) { ReflectionUtils.findClassesFromJar(classes, url, scannedPath, cl); } else if ("file".equals(url.getProtocol())) { final File file = new File(url.getFile()); ReflectionUtils.findClassesFromFile(classes, file, pkg, cl); } else { throw new IllegalArgumentException("package is provided by an unknown url: " + url); } } return classes; }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Finds all resources defined in a given package. * * @author paouelle// www.ja v a2 s . c o m * * @param pkg the package from which to find all defined resources * @param cl the classloader to find the resources with * @return the non-<code>null</code> collection of all resources defined in the * given package * @throws NullPointerException if <code>pkg</code> or <code>cl</code> is * <code>null</code> */ public static Collection<URL> findResources(String pkg, ClassLoader cl) { org.apache.commons.lang3.Validate.notNull(pkg, "invalid null pkg"); final String scannedPath = pkg.replace('.', File.separatorChar); final Enumeration<URL> resources; try { resources = cl.getResources(scannedPath); } catch (IOException e) { throw new IllegalArgumentException("Unable to get resources from path '" + scannedPath + "'. Are you sure the given '" + pkg + "' package exists?", e); } final List<URL> urls = new LinkedList<>(); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); if ("jar".equals(url.getProtocol())) { ReflectionUtils.findResourcesFromJar(urls, url, scannedPath, cl); } else if ("file".equals(url.getProtocol())) { final File file = new File(url.getFile()); ReflectionUtils.findResourcesFromFile(urls, file, scannedPath, cl); } else { throw new IllegalArgumentException("package is provided by an unknown url: " + url); } } return urls; }
From source file:org.xenei.classpathutils.ClassPathUtils.java
/** * Find all classes accessible from the class loader which belong to the * given package and sub packages.// w ww .j av a 2 s. co m * * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to * support use of JAR files * * @param classLoader * The class loader to load the classes from. * @param packageName * The package name to locate the classes in. * @param filter * The filter for the classes. * @return A collection of URL objects */ public static Collection<URL> getResources(final ClassLoader classLoader, final String packageName, final ClassPathFilter filter) { if (classLoader == null) { LOG.error("Class loader may not be null."); return Collections.emptyList(); } if (packageName == null) { LOG.error("Package name may not be null."); return Collections.emptyList(); } String dirName = packageName.replace('.', '/'); Enumeration<URL> resources; try { resources = classLoader.getResources(dirName); } catch (final IOException e1) { LOG.error(e1.toString()); return Collections.emptyList(); } final Set<URL> classes = new HashSet<URL>(); final Set<String> directories = new HashSet<String>(); if (resources.hasMoreElements()) { while (resources.hasMoreElements()) { final URL resource = resources.nextElement(); String dir = resource.getPath(); if (!directories.contains(dir)) { directories.add(dir); try { for (final String clazz : findResources(dir, packageName, filter)) { LOG.debug("Adding class {}", clazz); URL url = classLoader.getResource(clazz); if (url != null) { classes.add(url); } else { LOG.warn(String.format("Unable to locate: %s", clazz)); } } } catch (final IOException e) { LOG.warn(e.toString()); } } } } else { if (packageName.length() > 0) { // there are no resources at that path so see if it is a class LOG.debug("Adding class {}", packageName); URL url = classLoader.getResource(packageName); if (url != null) { classes.add(url); } else { LOG.warn(String.format("Unable to locate: %s", packageName)); classes.add(classLoader.getResource(packageName)); } } } return classes; }
From source file:org.apache.openejb.util.classloader.URLClassLoaderFirst.java
public static boolean shouldSkipJsf(final ClassLoader loader, final String name) { if (!name.startsWith("javax.faces.")) { return false; }//from w ww.ja va 2 s. c o m // using annotation to test to avoid to load more classes with deps final String testClass; if ("javax.faces.bean.RequestScoped".equals(name)) { testClass = "javax.faces.bean.SessionScoped"; } else { testClass = "javax.faces.bean.RequestScoped"; } final String classname = testClass.replace('.', '/') + ".class"; try { final Enumeration<URL> resources = loader.getResources(classname); final Collection<URL> thisJSf = Collections.list(resources); return thisJSf.isEmpty() || thisJSf.size() <= 1; } catch (final IOException e) { return true; } }
From source file:com.quartzdesk.executor.common.spring.metadata.BuildPropertiesFactoryBean.java
@Override protected Map<String, String> createInstance() throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resourceUrls = classLoader.getResources(propertiesPath); while (resourceUrls.hasMoreElements()) { URL resourceUrl = resourceUrls.nextElement(); if (resourceUrl.toString().contains(moduleName)) { InputStream ins = null; try { ins = resourceUrl.openStream(); return new UTF8Map(ins); } finally { IOUtils.close(ins);/* ww w .j a v a2 s . co m*/ } } } throw new IllegalStateException( "Build properties resource not found at: " + propertiesPath + ". Used module name: " + moduleName); }
From source file:inti.ws.spring.resource.config.ConfigParserProvider.java
public Map<String, ConfigParser<? extends WebResource>> getConfigParsers(ClassLoader classLoader) throws Exception { Enumeration<URL> parserLocations = classLoader.getResources("META-INF/inti.ws.spring.resource/parser.json"); URL url;/* w w w . j a va 2 s.c o m*/ ConfigParserSettings settings = null; InputStream inputStream; JsonNode node; Entry<String, JsonNode> field; Iterator<Entry<String, JsonNode>> fields; Map<String, ConfigParser<? extends WebResource>> parsers = new HashMap<>(); ConfigParser<? extends WebResource> parser; while (parserLocations.hasMoreElements()) { url = parserLocations.nextElement(); LOGGER.debug("getConfigParsers - scanning url={}", url); inputStream = url.openStream(); try { node = mapper.readTree(inputStream); fields = node.fields(); while (fields.hasNext()) { field = fields.next(); settings = mapper.convertValue(field.getValue(), ConfigParserSettings.class); parser = context.getBean(settings.getConfigurator()); parser.setConfigParserSettings(settings); if (parsers.containsKey(field.getKey())) { throw new RuntimeException( "name collision detected: '" + field.getKey() + "' already engaged."); } LOGGER.debug("getConfigParsers - found parser for key={}: {}", field.getKey(), parser); parsers.put(field.getKey(), parser); } } finally { inputStream.close(); } } return parsers; }