List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:Main.java
/** * Load a given resources. <p/> This method will try to load the resources * using the following methods (in order): * <ul>/*from w w w . j a va 2s . co m*/ * <li>From Thread.currentThread().getContextClassLoader() * <li>From ClassLoaderUtil.class.getClassLoader() * <li>callingClass.getClassLoader() * </ul> * * @param resourceName The name of the resource to load * @param callingClass The Class object of the calling object */ public static List<URL> getResources(String resourceName, Class callingClass) { List<URL> ret = new ArrayList<URL>(); Enumeration<URL> urls = new Enumeration<URL>() { public boolean hasMoreElements() { return false; } public URL nextElement() { return null; } }; try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); } catch (IOException e) { //ignore } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName.substring(1)); } catch (IOException e) { // ignore } } ClassLoader cluClassloader = Main.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (!urls.hasMoreElements()) { try { urls = cluClassloader.getResources(resourceName); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = cluClassloader.getResources(resourceName.substring(1)); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements()) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { try { urls = cl.getResources(resourceName); } catch (IOException e) { // ignore } } } if (!urls.hasMoreElements()) { URL url = callingClass.getResource(resourceName); if (url != null) { ret.add(url); } } while (urls.hasMoreElements()) { ret.add(urls.nextElement()); } if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResources('/' + resourceName, callingClass); } return ret; }
From source file:com.sunchenbin.store.feilong.core.lang.ClassLoaderUtil.java
/** * Load resources./* w w w.j av a2 s.c o m*/ * * @param resourceName * the resource name * @param callingClass * the calling class * @return the resources * @throws IOException * Signals that an I/O exception has occurred. * @see java.lang.ClassLoader#getResources(String) */ public static Enumeration<URL> getResources(String resourceName, Class<?> callingClass) throws IOException { ClassLoader classLoader = getClassLoaderByCurrentThread(); Enumeration<URL> urls = classLoader.getResources(resourceName); if (urls == null) { classLoader = getClassLoaderByClass(ClassLoaderUtil.class); urls = classLoader.getResources(resourceName); if (urls == null) { classLoader = getClassLoaderByClass(callingClass); urls = classLoader.getResources(resourceName); } } if (urls == null) { LOGGER.warn("resourceName:[{}] in all ClassLoader not found!", resourceName); } else { LOGGER.debug("In ClassLoader :[{}] found the resourceName:[{}]", JsonUtil.format(getClassLoaderInfoMapForLog(classLoader)), resourceName); } return urls; }
From source file:org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.java
private static Class<?> getStartClass() { ClassLoader classLoader = SpringFunctionInitializer.class.getClassLoader(); if (System.getenv("MAIN_CLASS") != null) { return ClassUtils.resolveClassName(System.getenv("MAIN_CLASS"), classLoader); }/* w w w . j a v a 2 s . c o m*/ try { Class<?> result = getStartClass(Collections.list(classLoader.getResources("META-INF/MANIFEST.MF"))); if (result == null) { result = getStartClass(Collections.list(classLoader.getResources("meta-inf/manifest.mf"))); } logger.info("Main class: " + result); return result; } catch (Exception ex) { logger.error("Failed to find main class", ex); return null; } }
From source file:org.jfunktor.common.vfs.VirtualFileSystem.java
/** * This method extract the contents of fromPath in the classpath to the * destination toPath which is the location relative to the app execution * directory//from w w w. j a v a 2 s . c om * * @param fromPath * @param toPath * @return */ public static boolean extractContentsTo(String fromPath, String toPath, ClassLoader loader) throws IOException, VFSException { // the fromPath is assumed to be from the classpath // so lets use Classloader to pick it, there might be more than one Enumeration<URL> resources = loader.getResources(fromPath); File topathRelative = new File(toPath); URL toPathURL = topathRelative.toURI().toURL(); boolean result = true; if (!resources.hasMoreElements()) { log.debug("Ignoring fromPath " + fromPath + " since no valid resource path found within classpath"); } while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (!extractContentsTo(resource, toPathURL)) { result = false; } } return result; }
From source file:com.fmguler.ven.support.LiquibaseConverter.java
/** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param packageName The base package/* ww w. ja va 2 s . c o 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 resources = classLoader.getResources(path); List dirs = new ArrayList(); while (resources.hasMoreElements()) { URL resource = (URL) resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList classes = new ArrayList(); Iterator it = dirs.iterator(); while (it.hasNext()) { File directory = (File) it.next(); classes.addAll(findClasses(directory, packageName)); } return (Class[]) classes.toArray(new Class[classes.size()]); }
From source file:com.yahoo.storm.yarn.StormOnYarn.java
/** * Find a jar that contains a class of the same name, if any. * It will return a jar file, even if that is not the first thing * on the class path that has a class with the same name. * /*from w ww . j a v a 2 s .c o m*/ * @param my_class the class to find. * @return a jar file that contains the class, or null. * @throws IOException on any error */ public static String findContainingJar(Class<?> my_class) throws IOException { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) { URL url = itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (toReturn.startsWith("file:")) { toReturn = toReturn.substring("file:".length()); } // URLDecoder is a misnamed class, since it actually decodes // x-www-form-urlencoded MIME type rather than actual // URL encoding (which the file path has). Therefore it would // decode +s to ' 's which is incorrect (spaces are actually // either unencoded or encoded as "%20"). Replace +s first, so // that they are kept sacred during the decoding process. toReturn = toReturn.replaceAll("\\+", "%2B"); toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } throw new IOException("Fail to locat a JAR for class: " + my_class.getName()); }
From source file:org.carrot2.util.resource.ClassLoaderLocator.java
/** * /*from w ww. j av a2 s.c om*/ */ static IResource[] getAll(ClassLoader loader, String resource) { final ArrayList<IResource> result = Lists.newArrayList(); try { /* * '/'-starting resources are not found for class loaders pointing to URLs * on disk (Windows at least). Make them relative. */ while (resource.startsWith("/")) resource = resource.substring(1); final Enumeration<URL> e = loader.getResources(resource); while (e.hasMoreElements()) { URL resourceURL = e.nextElement(); result.add(new URLResource(resourceURL)); } } catch (IOException e) { // Fall through. } return result.toArray(new IResource[result.size()]); }
From source file:com.acciente.commons.loader.ClassFinder.java
public static Set find(ClassLoader oClassLoader, String[] asPackageNames, Pattern oClassPattern) throws IOException { Set oClassNameSet = new HashSet(); for (int i = 0; i < asPackageNames.length; i++) { String sPackageName = asPackageNames[i]; Enumeration oResources = oClassLoader.getResources(sPackageName.replace('.', '/')); if (!oResources.hasMoreElements()) { __oLog.info("classloader scan for package: " + sPackageName + " found no resources!"); }//from w w w . j av a 2s . c o m while (oResources.hasMoreElements()) { String sResourceURL = URLDecoder.decode(((URL) oResources.nextElement()).toString(), "UTF-8"); if (sResourceURL.startsWith(URL_PREFIX_JARFILE)) { int iDelimPos = sResourceURL.indexOf(URL_DELIM_JARFILE); if (iDelimPos != -1) { File oJarFile = new File(sResourceURL.substring(URL_PREFIX_JARFILE.length() - 1, iDelimPos + ".jar".length())); __oLog.info("scanning jar: " + oJarFile); findInJar(oJarFile, sPackageName, oClassPattern, oClassNameSet); } } else if (sResourceURL.startsWith(URL_PREFIX_FILE)) { File oDirectory = new File(sResourceURL.substring(URL_PREFIX_FILE.length() - 1)); __oLog.info("scanning dir: " + oDirectory); findInDirectory(oDirectory, sPackageName, oClassPattern, oClassNameSet); } } } // if the classloader is a ReloadingClassLoader the above loop would have processed the classed reachable via // the parent classloader, now we process the classes reachable via this classloader if (oClassLoader instanceof ReloadingClassLoader) { __oLog.info("reloading classloader detected, scanning..."); ReloadingClassLoader oReloadingClassLoader = (ReloadingClassLoader) oClassLoader; for (Iterator oClassDefLoaderIter = oReloadingClassLoader.getClassDefLoaders() .iterator(); oClassDefLoaderIter.hasNext();) { ClassDefLoader oClassDefLoader = (ClassDefLoader) oClassDefLoaderIter.next(); Set oAddClassNameSet = oClassDefLoader.findClassNames(asPackageNames, oClassPattern); oClassNameSet.addAll(oAddClassNameSet); } } return oClassNameSet; }
From source file:org.jvnet.hudson.test.MavenUtil.java
/** * Create MavenRequest given only a TaskListener. Used by HudsonTestCase. * /*from ww w. jav a2 s .c o m*/ * @param listener * @return MavenRequest * @throws MavenEmbedderException * @throws IOException */ public static MavenRequest createMavenRequest(TaskListener listener) throws MavenEmbedderException, IOException { Properties systemProperties = new Properties(); MavenRequest mavenRequest = new MavenRequest(); // make sure ~/.m2 exists to avoid http://www.nabble.com/BUG-Report-tf3401736.html File m2Home = new File(MavenEmbedder.userHome, ".m2"); m2Home.mkdirs(); if (!m2Home.exists()) throw new AbortException("Failed to create " + m2Home); mavenRequest.setUserSettingsFile(new File(m2Home, "settings.xml").getAbsolutePath()); mavenRequest.setGlobalSettingsFile(new File("conf/settings.xml").getAbsolutePath()); mavenRequest.setUpdateSnapshots(false); // TODO olamy check this sould be userProperties mavenRequest.setSystemProperties(systemProperties); EmbedderLoggerImpl logger = new EmbedderLoggerImpl(listener, debugMavenEmbedder ? org.codehaus.plexus.logging.Logger.LEVEL_DEBUG : org.codehaus.plexus.logging.Logger.LEVEL_INFO); mavenRequest.setMavenLoggerManager(logger); ClassLoader mavenEmbedderClassLoader = new MaskingClassLoader(MavenUtil.class.getClassLoader()); {// are we loading the right components.xml? (and not from Maven that's running Jetty, if we are running in "mvn hudson-dev:run" or "mvn hpi:run"? Enumeration<URL> e = mavenEmbedderClassLoader.getResources("META-INF/plexus/components.xml"); while (e.hasMoreElements()) { URL url = e.nextElement(); LOGGER.fine("components.xml from " + url); } } mavenRequest.setProcessPlugins(false); mavenRequest.setResolveDependencies(false); mavenRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0); return mavenRequest; }
From source file:net.dataforte.commons.resources.ClassUtils.java
/** * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS * // w ww.j ava 2 s . c om * @param folder * @return * @throws IOException */ public static URL[] getResources(String folder) throws IOException { List<URL> urls = new ArrayList<URL>(); ArrayList<File> directories = new ArrayList<File>(); try { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new IOException("Can't get class loader."); } // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(folder); while (resources.hasMoreElements()) { URL res = resources.nextElement(); String resProtocol = res.getProtocol(); if (resProtocol.equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) res.openConnection(); JarFile jar = conn.getJarFile(); for (JarEntry e : Collections.list(jar.entries())) { if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) { urls.add(new URL( joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name } } } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+ try { Object content = res.getContent(); Method getChildren = content.getClass().getMethod("getChildren"); List<?> files = (List<?>) getChildren.invoke(res.getContent()); Method toUrl = null; for (Object o : files) { if (toUrl == null) { toUrl = o.getClass().getMethod("toURL"); } urls.add((URL) toUrl.invoke(o)); } } catch (Exception e) { throw new IOException("Error while scanning " + res.toString(), e); } } else if (resProtocol.equalsIgnoreCase("file")) { directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } else { throw new IOException("Unknown protocol for resource: " + res.toString()); } } } catch (NullPointerException x) { throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)"); } // For every directory identified capture all the .class files for (File directory : directories) { if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); for (String file : files) { urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file))); } } else { throw new IOException( folder + " (" + directory.getPath() + ") does not appear to be a valid folder"); } } URL[] urlsA = new URL[urls.size()]; urls.toArray(urlsA); return urlsA; }