List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:net.sf.jasperreports.engine.util.JRLoader.java
protected static void collectResources(String resourceName, ClassLoader classLoader, Map<URL, ClassLoaderResource> resources) { if (classLoader == null) { return;/*from w w w. ja v a 2 s.c om*/ } try { // creating a list of parent classloaders, with the highest in the // hierarchy first LinkedList<ClassLoader> classloaders = new LinkedList<ClassLoader>(); ClassLoader ancestorLoader = classLoader; while (ancestorLoader != null) { classloaders.addFirst(ancestorLoader); try { ancestorLoader = ancestorLoader.getParent(); } catch (SecurityException e) { // if we're not allowed to get the parent, stop here. // resources will be listed with the first classloader that // we're allowed to access. // one case when this happens is applets. // FIXME revisit logging on SecurityException for applet ancestorLoader = null; } } for (ClassLoader ancestor : classloaders) { Enumeration<URL> urls = ancestor.getResources(resourceName); if (urls != null) // class loaders should never return null on getResources, according to specs, but we've seen cases, so we protect our code here { while (urls.hasMoreElements()) { URL url = urls.nextElement(); // if this is the first time we see this resource, add it // with the current classloader. // this way a resource will be added with the most first // ancestor classloader that has it. if (!resources.containsKey(url)) { if (log.isDebugEnabled()) { log.debug("Found resource " + resourceName + " at " + url + " in classloader " + ancestor); } ClassLoaderResource resource = new ClassLoaderResource(url, ancestor); resources.put(url, resource); } } } } } catch (IOException e) { throw new JRRuntimeException(e); } }
From source file:de.alpharogroup.lang.ClassExtensions.java
/** * Gets a list with urls from the given path for all resources. * * @param path// w ww.ja va 2 s . c om * The base path. * @return The resources. * @throws IOException * Signals that an I/O exception has occurred. */ public static List<URL> getResources(final String path) throws IOException { final ClassLoader classLoader = ClassExtensions.getClassLoader(); final List<URL> list = Collections.list(classLoader.getResources(path)); return list; }
From source file:eu.europeana.enrichment.common.Utils.java
private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException { // This will hold a list of directories matching the pckgname. There may // be// www . j a v a 2 s. co m // more than one if a package is split over multiple jars/paths Queue<File> directories = new LinkedList<File>(); try { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (NullPointerException x) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)"); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname); } Set<String> classes = new HashSet<String>(); // For every directory identified capture all the .class files while (!directories.isEmpty()) { File directory = directories.poll(); if (directory.exists()) { // Get the list of the files contained in the package File[] files = directory.listFiles(); for (File file : files) { // we are only interested in .class files if (file.getCanonicalPath().endsWith(".class")) { String fileName = file.getPath().substring(directory.getPath().length() + 1); pckgname = file.getPath() .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1); pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator)) .replaceAll("\\" + File.separator, "."); // if (!fileName.matches("(.+)\\$\\d\\.class")) // removes the .class extension classes.add(fileName.substring(0, fileName.length() - 6)); } // Add subdirs if (file.isDirectory()) { directories.add(file); } } } else { throw new ClassNotFoundException( pckgname + " (" + directory.getPath() + ") does not appear to be a valid package"); } } return classes; }
From source file:eu.annocultor.common.Utils.java
private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException { // 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 Queue<File> directories = new LinkedList<File>(); try {//from w ww. j a v a 2s.c o m ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (NullPointerException x) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)"); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname); } Set<String> classes = new HashSet<String>(); // For every directory identified capture all the .class files while (!directories.isEmpty()) { File directory = directories.poll(); if (directory.exists()) { // Get the list of the files contained in the package File[] files = directory.listFiles(); for (File file : files) { // we are only interested in .class files if (file.getCanonicalPath().endsWith(".class")) { String fileName = file.getPath().substring(directory.getPath().length() + 1); pckgname = file.getPath() .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1); pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator)) .replaceAll("\\" + File.separator, "."); // if (!fileName.matches("(.+)\\$\\d\\.class")) // removes the .class extension classes.add(fileName.substring(0, fileName.length() - 6)); } // Add subdirs if (file.isDirectory()) { directories.add(file); } } } else { throw new ClassNotFoundException( pckgname + " (" + directory.getPath() + ") does not appear to be a valid package"); } } return classes; }
From source file:net.sf.jasperreports.engine.util.JRLoader.java
protected static void collectResources(String resourceName, ClassLoader classLoader, Set<URL> resources) { if (classLoader != null) { try {// w w w .j a va 2s. co m Enumeration<URL> urls = classLoader.getResources(resourceName); if (urls != null) { while (urls.hasMoreElements()) // class loaders should never return null on getResources, according to specs, but we've seen cases, so we protect our code here { URL url = urls.nextElement(); resources.add(url); } } } catch (IOException e) { throw new JRRuntimeException(e); } } }
From source file:ml.shifu.guagua.hadoop.util.HDPUtils.java
@SuppressWarnings("rawtypes") public static String findContainingJar(Class my_class) { ClassLoader loader = my_class.getClassLoader(); if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); }// w ww . j a va 2s . co m String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try { Enumeration<URL> itr = null; // Try to find the class in registered jars if (loader instanceof URLClassLoader) { itr = ((URLClassLoader) loader).findResources(class_file); } // Try system classloader if not URLClassLoader or no resources found in URLClassLoader if (itr == null || !itr.hasMoreElements()) { itr = loader.getResources(class_file); } for (; itr.hasMoreElements();) { URL 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("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:org.apache.pig.impl.util.JarManager.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. * * @param my_class//from ww w. ja va2s . c om * the class to find * @return a jar file that contains the class, or null * @throws IOException */ public static String findContainingJar(Class my_class) { ClassLoader loader = PigContext.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try { Enumeration<URL> itr = null; //Try to find the class in registered jars if (loader instanceof URLClassLoader) { itr = ((URLClassLoader) loader).findResources(class_file); } //Try system classloader if not URLClassLoader or no resources found in URLClassLoader if (itr == null || !itr.hasMoreElements()) { itr = loader.getResources(class_file); } for (; itr.hasMoreElements();) { URL 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("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:org.apache.openejb.util.classloader.URLClassLoaderFirst.java
public static boolean shouldSkipSlf4j(final ClassLoader loader, final String name) { if (name == null || !name.startsWith("org.slf4j.")) { return false; }/*from ww w . j a v a 2 s. co m*/ try { // using getResource here just returns randomly the container one so we need getResources final Enumeration<URL> resources = loader.getResources(SLF4J_BINDER_CLASS); while (resources.hasMoreElements()) { final URL resource = resources.nextElement(); if (!resource.equals(SLF4J_CONTAINER)) { // applicative slf4j return false; } } } catch (final Throwable e) { // no-op } return true; }
From source file:org.mrgeo.utils.ClassLoaderUtil.java
public static Collection<String> getMostJars() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try {//from w w w . ja v a 2s .com // this seems to populate more jars. Odd. getChildResources("META-INF/services"); getChildResources(""); getChildResources("/"); } catch (Exception e1) { e1.printStackTrace(); } Thief t = new Thief(classLoader); Package[] packages = t.getPackages(); TreeSet<String> result = new TreeSet<String>(); for (Package p : packages) { Enumeration<URL> urls; try { String path = p.getName().replace(".", "/"); urls = classLoader.getResources(path); while (urls.hasMoreElements()) { URL resource = urls.nextElement(); if (resource.getProtocol().equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) resource.openConnection(); JarFile jarFile = conn.getJarFile(); result.add(jarFile.getName()); } } } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:org.springframework.cloud.function.context.AbstractSpringFunctionAdapterInitializer.java
private static Class<?> getStartClass() { ClassLoader classLoader = AbstractSpringFunctionAdapterInitializer.class.getClassLoader(); Class<?> mainClass = null; if (System.getenv("MAIN_CLASS") != null) { mainClass = ClassUtils.resolveClassName(System.getenv("MAIN_CLASS"), classLoader); } else if (System.getProperty("MAIN_CLASS") != null) { mainClass = ClassUtils.resolveClassName(System.getProperty("MAIN_CLASS"), classLoader); } else {/* w w w . ja v a 2 s . c om*/ 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"))); } Assert.notNull(result, "Failed to locate main class"); mainClass = result; } catch (Exception ex) { throw new IllegalStateException("Failed to discover main class. An attempt was made to discover " + "main class as 'MAIN_CLASS' environment variable, system property as well as " + "entry in META-INF/MANIFEST.MF (in that order).", ex); } } logger.info("Main class: " + mainClass); return mainClass; }