List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:org.mrgeo.utils.HadoopUtils.java
public static String findContainingJar(Class clazz) { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; try {// ww w . j av a 2 s .c o m for (Enumeration itr = loader.getResources(classFile); 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()); } //toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:net.kamhon.ieagle.util.ReflectionUtil.java
/** * <pre>//from w w w .j ava 2 s . c o m * This method finds all classes that are located in the package identified by * the given * <code> * packageName * </code> * . * <br> * <b>ATTENTION:</b> * <br> * This is a relative expensive operation. Depending on your classpath * multiple directories,JAR, and WAR files may need to scanned. * * @param packageName is the name of the {@link Package} to scan. * @param includeSubPackages - if * <code> * true * </code> * all sub-packages of the * specified {@link Package} will be included in the search. * @return a {@link Set} will the fully qualified names of all requested * classes. * @throws IOException if the operation failed with an I/O error. * @see http://m-m-m.svn.sourceforge.net/svnroot/m-m-m/trunk/mmm-util/mmm-util-reflect/src/main/java/net/sf/mmm/util/reflect/ReflectionUtil.java * </pre> */ public static Set<String> findFileNames(String packageName, boolean includeSubPackages, String packagePattern, String... endWiths) throws IOException { Set<String> classSet = new HashSet<String>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String path = packageName.replace('.', '/'); String pathWithPrefix = path + '/'; Enumeration<URL> urls = classLoader.getResources(path); StringBuilder qualifiedNameBuilder = new StringBuilder(packageName); qualifiedNameBuilder.append('.'); int qualifiedNamePrefixLength = qualifiedNameBuilder.length(); while (urls.hasMoreElements()) { URL packageUrl = urls.nextElement(); String urlString = URLDecoder.decode(packageUrl.getFile(), "UTF-8"); String protocol = packageUrl.getProtocol().toLowerCase(); log.debug(urlString); if ("file".equals(protocol)) { File packageDirectory = new File(urlString); if (packageDirectory.isDirectory()) { if (includeSubPackages) { findClassNamesRecursive(packageDirectory, classSet, qualifiedNameBuilder, qualifiedNamePrefixLength, packagePattern); } else { for (String fileName : packageDirectory.list()) { String simpleClassName = fixClassName(fileName); if (simpleClassName != null) { qualifiedNameBuilder.setLength(qualifiedNamePrefixLength); qualifiedNameBuilder.append(simpleClassName); if (qualifiedNameBuilder.toString().matches(packagePattern)) classSet.add(qualifiedNameBuilder.toString()); } } } } } else if ("jar".equals(protocol)) { // somehow the connection has no close method and can NOT be // disposed JarURLConnection connection = (JarURLConnection) packageUrl.openConnection(); JarFile jarFile = connection.getJarFile(); Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries(); while (jarEntryEnumeration.hasMoreElements()) { JarEntry jarEntry = jarEntryEnumeration.nextElement(); String absoluteFileName = jarEntry.getName(); // if (absoluteFileName.endsWith(".class")) { //original if (endWith(absoluteFileName, endWiths)) { // modified if (absoluteFileName.startsWith("/")) { absoluteFileName.substring(1); } // special treatment for WAR files... // "WEB-INF/lib/" entries should be opened directly in // contained jar if (absoluteFileName.startsWith("WEB-INF/classes/")) { // "WEB-INF/classes/".length() == 16 absoluteFileName = absoluteFileName.substring(16); } boolean accept = true; if (absoluteFileName.startsWith(pathWithPrefix)) { String qualifiedName = absoluteFileName.replace('/', '.'); if (!includeSubPackages) { int index = absoluteFileName.indexOf('/', qualifiedNamePrefixLength + 1); if (index != -1) { accept = false; } } if (accept) { String className = fixClassName(qualifiedName); if (className != null) { if (qualifiedNameBuilder.toString().matches(packagePattern)) classSet.add(className); } } } } } } else { log.debug("unknown protocol -> " + protocol); } } return classSet; }
From source file:de.alpharogroup.lang.ClassUtils.java
/** * Gets a list with urls from the given path for all resources. * * @param path//from w w w .j ava 2s. c o m * 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 = ClassUtils.getClassLoader(); final List<URL> list = Collections.list(classLoader.getResources(path)); return list; }
From source file:org.apache.tajo.yarn.command.LaunchCommand.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 clazz the class to find.// w ww . j a v a2 s . co m * @return a jar file that contains the class, or null. * @throws IOException on any error */ private static String findContainingJar(Class<?> clazz) throws IOException { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; for (Enumeration<URL> itr = loader.getResources(classFile); 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: " + clazz.getName()); }
From source file:org.apache.bval.jsr.xml.ValidationParser.java
protected static InputStream getInputStream(final String path) throws IOException { final ClassLoader loader = Reflection.getClassLoader(ValidationParser.class); final InputStream inputStream = loader.getResourceAsStream(path); if (inputStream != null) { // spec says: If more than one META-INF/validation.xml file // is found in the classpath, a ValidationException is raised. final Enumeration<URL> urls = loader.getResources(path); if (urls.hasMoreElements()) { final String url = urls.nextElement().toString(); while (urls.hasMoreElements()) { if (!url.equals(urls.nextElement().toString())) { // complain when first duplicate found throw new ValidationException("More than one " + path + " is found in the classpath"); }/*from ww w .j a va 2s. co m*/ } } } return IOs.convertToMarkableInputStream(inputStream); }
From source file:com.splicemachine.mrio.api.SpliceTableMapReduceUtil.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. * * This is shamelessly copied from JobConf * * @param my_class the class to find./*from w ww.j av a2 s .c om*/ * @return a jar file that contains the class, or null. * @throws IOException */ private static String findContainingJar(Class my_class) { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); 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:hudson.gridmaven.MavenUtil.java
/** * Creates a fresh {@link MavenEmbedder} instance. * *//*from www. jav a 2 s .c om*/ @SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE") public static MavenEmbedder createEmbedder(MavenEmbedderRequest mavenEmbedderRequest) throws MavenEmbedderException, IOException { 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); if (mavenEmbedderRequest.getPrivateRepository() != null) mavenRequest.setLocalRepositoryPath(mavenEmbedderRequest.getPrivateRepository()); if (mavenEmbedderRequest.getProfiles() != null) { mavenRequest.setProfiles(Arrays.asList(StringUtils.split(mavenEmbedderRequest.getProfiles(), ","))); } if (mavenEmbedderRequest.getAlternateSettings() != null) { mavenRequest.setUserSettingsFile(mavenEmbedderRequest.getAlternateSettings().getAbsolutePath()); } else { mavenRequest.setUserSettingsFile(new File(m2Home, "settings.xml").getAbsolutePath()); } if (mavenEmbedderRequest.getGlobalSettings() != null) { mavenRequest.setGlobalSettingsFile(mavenEmbedderRequest.getGlobalSettings().getAbsolutePath()); } else { mavenRequest.setGlobalSettingsFile( new File(mavenEmbedderRequest.getMavenHome(), "conf/settings.xml").getAbsolutePath()); } if (mavenEmbedderRequest.getWorkspaceReader() != null) { mavenRequest.setWorkspaceReader(mavenEmbedderRequest.getWorkspaceReader()); } mavenRequest.setUpdateSnapshots(mavenEmbedderRequest.isUpdateSnapshots()); // TODO olamy check this sould be userProperties mavenRequest.setSystemProperties(mavenEmbedderRequest.getSystemProperties()); if (mavenEmbedderRequest.getTransferListener() != null) { if (debugMavenEmbedder) { mavenEmbedderRequest.getListener().getLogger().println( "use transfertListener " + mavenEmbedderRequest.getTransferListener().getClass().getName()); } mavenRequest.setTransferListener(mavenEmbedderRequest.getTransferListener()); } EmbedderLoggerImpl logger = new EmbedderLoggerImpl(mavenEmbedderRequest.getListener(), debugMavenEmbedder ? org.codehaus.plexus.logging.Logger.LEVEL_DEBUG : org.codehaus.plexus.logging.Logger.LEVEL_INFO); mavenRequest.setMavenLoggerManager(logger); ClassLoader mavenEmbedderClassLoader = mavenEmbedderRequest.getClassLoader() == null ? new MaskingClassLoader(MavenUtil.class.getClassLoader()) : mavenEmbedderRequest.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(mavenEmbedderRequest.isProcessPlugins()); mavenRequest.setResolveDependencies(mavenEmbedderRequest.isResolveDependencies()); mavenRequest.setValidationLevel(mavenEmbedderRequest.getValidationLevel()); // TODO check this MaskingClassLoader with maven 3 artifacts MavenEmbedder maven = new MavenEmbedder(mavenEmbedderClassLoader, mavenRequest); return maven; }
From source file:edu.umn.cs.spatialHadoop.core.SpatialSite.java
private static String findContainingJar(Class my_class) { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try {//from ww w . java 2 s . c o m for (Enumeration<URL> itr = loader.getResources(class_file); 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()); } toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:org.apache.kudu.mapreduce.KuduTableMapReduceUtil.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. Looks first on the classpath and then in * the <code>packagedClasses</code> map. * @param myClass the class to find.//w ww. j a v a 2 s . com * @return a jar file that contains the class, or null. * @throws IOException */ private static String findContainingJar(Class<?> myClass, Map<String, String> packagedClasses) throws IOException { ClassLoader loader = myClass.getClassLoader(); String classFile = myClass.getName().replaceAll("\\.", "/") + ".class"; // first search the classpath for (Enumeration<URL> itr = loader.getResources(classFile); 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("!.*$", ""); } } // now look in any jars we've packaged using JarFinder. Returns null when // no jar is found. return packagedClasses.get(classFile); }
From source file:org.apache.xmlgraphics.util.Service.java
/** * Returns an iterator where each element should implement the * interface (or subclass the baseclass) described by cls. The * Classes are found by searching the classpath for service files * named: 'META-INF/services/<fully qualified classname> that list * fully qualifted classnames of classes that implement the * service files classes interface. These classes must have * default constructors if returnInstances is true. * * @param cls The class/interface to search for providers of. * @param returnInstances true if the iterator should return instances rather than class names. *///from w ww . j av a2 s .c o m public static synchronized Iterator providers(Class cls, boolean returnInstances) { String serviceFile = "META-INF/services/" + cls.getName(); Map cacheMap = (returnInstances ? instanceMap : classMap); List l = (List) cacheMap.get(serviceFile); if (l != null) { return l.iterator(); } l = new java.util.ArrayList(); cacheMap.put(serviceFile, l); ClassLoader cl = null; try { cl = cls.getClassLoader(); } catch (SecurityException se) { // Ooops! can't get his class loader. } // Can always request your own class loader. But it might be 'null'. if (cl == null) { cl = Service.class.getClassLoader(); } if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } // No class loader so we can't find 'serviceFile'. if (cl == null) { return l.iterator(); } Enumeration e; try { e = cl.getResources(serviceFile); } catch (IOException ioe) { return l.iterator(); } while (e.hasMoreElements()) { try { URL u = (URL) e.nextElement(); InputStream is = u.openStream(); Reader r = new InputStreamReader(is, "UTF-8"); BufferedReader br = new BufferedReader(r); try { String line = br.readLine(); while (line != null) { try { // First strip any comment... int idx = line.indexOf('#'); if (idx != -1) { line = line.substring(0, idx); } // Trim whitespace. line = line.trim(); // If nothing left then loop around... if (line.length() == 0) { line = br.readLine(); continue; } if (returnInstances) { // Try and load the class Object obj = cl.loadClass(line).newInstance(); // stick it into our vector... l.add(obj); } else { l.add(line); } } catch (Exception ex) { // Just try the next line } line = br.readLine(); } } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(is); } } catch (Exception ex) { // Just try the next file... } catch (LinkageError le) { // Just try the next file... } } return l.iterator(); }