List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:org.sourcepit.tools.shared.resources.internal.harness.SharedResourcesUtils.java
private static Properties loadResourcesProperties(ClassLoader classLoader, String templatesLocation) { final Properties resourceProperties = new Properties(); final String pathToResourceProperties = createFullResourcesPath(templatesLocation, "resources.properties"); try {// w w w . ja v a 2s. c o m Enumeration<URL> resources = classLoader.getResources(pathToResourceProperties); while (resources.hasMoreElements()) { InputStream in = null; try { final URL url = (URL) resources.nextElement(); in = url.openStream(); resourceProperties.load(in); } finally { IOUtils.closeQuietly(in); } } } catch (IOException e) { throw new IllegalStateException(e); } return resourceProperties; }
From source file:org.deeplearning4j.hadoop.util.HdfsUtils.java
public static String findJar(Class<?> my_class) { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; try {//from ww w .j a v a 2 s . c om 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.maven.MavenUtil.java
/** * Creates a fresh {@link MavenEmbedder} instance. * * @param listener/*from w ww .j av a2 s . com*/ * This is where the log messages from Maven will be recorded. * @param mavenHome * Directory of the Maven installation. We read {@code conf/settings.xml} * from here. Can be null. * @param profiles * Profiles to activate/deactivate. Can be null. * @param systemProperties * The system properties that the embedded Maven sees. See {@link MavenEmbedder#setSystemProperties(Properties)}. * @param privateRepository * Optional private repository to use as the local repository. * @param alternateSettings * Optional alternate settings.xml file. */ public static MavenEmbedder createEmbedder(TaskListener listener, File mavenHome, String profiles, Properties systemProperties, String privateRepository, File alternateSettings) throws MavenEmbedderException, IOException { MavenEmbedder maven = new MavenEmbedder(mavenHome); ClassLoader cl = MavenUtil.class.getClassLoader(); maven.setClassLoader(new MaskingClassLoader(cl)); EmbedderLoggerImpl logger = new EmbedderLoggerImpl(listener); if (debugMavenEmbedder) logger.setThreshold(MavenEmbedderLogger.LEVEL_DEBUG); maven.setLogger(logger); { Enumeration<URL> e = cl.getResources("META-INF/plexus/components.xml"); while (e.hasMoreElements()) { URL url = e.nextElement(); LOGGER.fine("components.xml from " + url); } } // 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 + "\nSee https://hudson.dev.java.net/cannot-create-.m2.html"); if (privateRepository != null) maven.setLocalRepositoryDirectory(new File(privateRepository)); maven.setProfiles(profiles); if (alternateSettings != null) maven.setAlternateSettings(alternateSettings); maven.setSystemProperties(systemProperties); maven.start(); return maven; }
From source file:org.structr.common.LicensingTest.java
/** * Get classes in given package and subpackages, accessible from the * context class loader/* w w w.ja v a2 s .c o m*/ * * @param packageName The base package * @return The classes * @throws ClassNotFoundException * @throws IOException */ protected static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } List<Class> classList = new ArrayList<>(); for (File directory : dirs) { classList.addAll(findClasses(directory, packageName)); } return classList; }
From source file:org.apache.hive.hcatalog.templeton.tool.TempletonUtils.java
/** * Find a jar that contains a class of the same name and which * file name matches the given pattern./*from www . j a v a2 s . com*/ * * @param clazz the class to find. * @param fileNamePattern regex pattern that must match the jar full path * @return a jar file that contains the class, or null */ public static String findContainingJar(Class<?> clazz, String fileNamePattern) { ClassLoader loader = clazz.getClassLoader(); String classFile = clazz.getName().replaceAll("\\.", "/") + ".class"; try { for (final Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) { final URL url = itr.nextElement(); if ("jar".equals(url.getProtocol())) { String toReturn = url.getPath(); if (fileNamePattern == null || toReturn.matches(fileNamePattern)) { toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:org.apache.hama.bsp.BSPJob.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.j av a 2 s . c o m 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()); } toReturn = URLDecoder.decode(toReturn, "UTF-8"); return toReturn.replaceAll("!.*$", ""); } } } catch (IOException e) { throw new RuntimeException(e); } return null; }
From source file:Main.java
public static List<Class<?>> getClassesForPackage(final String iPackageName, final ClassLoader iClassLoader) throws ClassNotFoundException { // 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 List<Class<?>> classes = new ArrayList<Class<?>>(); ArrayList<File> directories = new ArrayList<File>(); try {/*from w w w .java 2s .c o m*/ // Ask for all resources for the path final String packageUrl = iPackageName.replace('.', '/'); Enumeration<URL> resources = iClassLoader.getResources(packageUrl); if (!resources.hasMoreElements()) { resources = iClassLoader.getResources(packageUrl + CLASS_EXTENSION); if (resources.hasMoreElements()) { throw new IllegalArgumentException( iPackageName + " does not appear to be a valid package but a class"); } } else { while (resources.hasMoreElements()) { URL res = resources.nextElement(); if (res.getProtocol().equalsIgnoreCase("jar")) { JarURLConnection conn = (JarURLConnection) res.openConnection(); JarFile jar = conn.getJarFile(); for (JarEntry e : Collections.list(jar.entries())) { if (e.getName().startsWith(iPackageName.replace('.', '/')) && e.getName().endsWith(CLASS_EXTENSION) && !e.getName().contains("$")) { String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6); classes.add(Class.forName(className)); } } } else directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } } } catch (NullPointerException x) { throw new ClassNotFoundException( iPackageName + " does not appear to be " + "a valid package (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( iPackageName + " 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 " + iPackageName); } // 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 File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { classes.addAll(findClasses(file, iPackageName)); } else { String className; if (file.getName().endsWith(CLASS_EXTENSION)) { className = file.getName().substring(0, file.getName().length() - CLASS_EXTENSION.length()); classes.add(Class.forName(iPackageName + '.' + className)); } } } } else { throw new ClassNotFoundException( iPackageName + " (" + directory.getPath() + ") does not appear to be a valid package"); } } return classes; }
From source file:org.dhatim.util.ClassUtil.java
public static List<URL> getResources(String resourcePath, ClassLoader callerClassLoader) throws IOException { Set<URL> resources = new LinkedHashSet<URL>(); if (resourcePath.startsWith("/")) { resourcePath = resourcePath.substring(1); }//w w w. j ava 2s. c o m ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { resources.addAll(CollectionsUtil.toList(contextClassLoader.getResources(resourcePath))); } if (callerClassLoader != null) { resources.addAll(CollectionsUtil.toList(callerClassLoader.getResources(resourcePath))); } return new ArrayList<URL>(resources); }
From source file:ml.shifu.guagua.hadoop.util.HDPUtils.java
/** * Find a real file that contains file name in class path. * /*from w ww .jav a 2s . c o m*/ * @param file * name * @return real file name */ public static String findContainingFile(String fileName) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Enumeration<URL> itr = null; // Try to find the class in registered jars if (loader instanceof URLClassLoader) { itr = ((URLClassLoader) loader).findResources(fileName); } // Try system classloader if not URLClassLoader or no resources found in URLClassLoader if (itr == null || !itr.hasMoreElements()) { itr = loader.getResources(fileName); } for (; itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); if ("file".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.assertj.assertions.generator.util.ClassUtil.java
private static Set<Class<?>> getPackageClassesFromClasspathFiles(String packageName, ClassLoader classLoader) { try {//from w w w . j av a 2 s. c o m String packagePath = packageName.replace('.', File.separatorChar); // Ask for all resources for the path Enumeration<URL> resources = classLoader.getResources(packagePath); Set<Class<?>> classes = newLinkedHashSet(); while (resources.hasMoreElements()) { File directory = new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")); if (directory.canRead()) { classes.addAll(getClassesInDirectory(directory, packageName, classLoader)); } } return classes; } catch (UnsupportedEncodingException encex) { throw new RuntimeException( packageName + " does not appear to be a valid package (Unsupported encoding)", encex); } catch (IOException ioex) { throw new RuntimeException("IOException was thrown when trying to get all classes for " + packageName, ioex); } }