List of usage examples for java.lang ClassLoader getResources
public Enumeration<URL> getResources(String name) throws IOException
From source file:org.jboss.spring.vfs.VFSResourcePatternResolvingHelper.java
public static Resource[] locateResources(String locationPattern, String rootDirPath, ClassLoader classLoader, PathMatcher pathMatcher, boolean oneMatchingRootOnly) throws IOException { String subPattern = locationPattern.substring(rootDirPath.length()); if (rootDirPath.startsWith("/")) { rootDirPath = rootDirPath.substring(1); }//from w w w . ja v a 2 s .c o m List<Resource> resources = new ArrayList<Resource>(); Enumeration<URL> urls = classLoader.getResources(rootDirPath); if (!oneMatchingRootOnly) { while (urls.hasMoreElements()) { resources.addAll(getVFSResources(urls.nextElement(), subPattern, pathMatcher)); } } else { resources.addAll(getVFSResources(classLoader.getResource(rootDirPath), subPattern, pathMatcher)); } return resources.toArray(new Resource[resources.size()]); }
From source file:tr.com.serkanozal.jcommon.util.ClasspathUtil.java
private static Set<URL> findClasspathsByLoader(ClassLoader loader) { Set<URL> urls = new HashSet<URL>(); if (loader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) loader; urls.addAll(Arrays.asList(urlLoader.getURLs())); } else {// w ww . ja v a 2s. c o m Enumeration<URL> urlEnum; try { urlEnum = loader.getResources(""); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); if (url.getProtocol().startsWith("bundleresource")) { continue; } urls.add(url); } } catch (IOException e) { e.printStackTrace(); } } return urls; }
From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java
/** * Methods to find classes and annotations *//*from w w w. j a v a 2s. c om*/ public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException { List<Class<?>> classes = new ArrayList<Class<?>>(); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // ClassLoader classLoader = ClassLoader.getSystemClassLoader(); String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } logger.info("getClasses has: " + dirs.size() + " directories."); for (File directory : dirs) { logger.info("getClasses - dir=" + directory); classes.addAll(ClassFinderTestUtils.findClasses(directory, packageName)); } } catch (Exception e) { logger.warning("getClass had: " + e.getMessage(), e); } return classes; }
From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.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 my_class/* w ww. ja v a 2s . c o m*/ * the class to find. * @return a jar file that contains the class, or null. * @throws IOException */ private static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses) throws IOException { ClassLoader loader = my_class.getClassLoader(); String class_file = my_class.getName().replaceAll("\\.", "/") + ".class"; // first search the classpath 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("!.*$", ""); } } // now look in any jars we've packaged using JarFinder. Returns null // when // no jar is found. return packagedClasses.get(class_file); }
From source file:net.dataforte.commons.resources.ClassUtils.java
/** * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS * //from www . j ava 2 s . com * @param folder * @return * @throws IOException */ public static Class<?>[] getClassesForPackage(String pckgname) 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 { ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/')); 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(pckgname.replace('.', '/')) && e.getName().endsWith(".class") && !e.getName().contains("$")) { String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6); classes.add(Class.forName(className, true, cld)); } } } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+ try { Object content = res.getContent(); Method getChildren = content.getClass().getMethod("getChildren"); List<?> files = (List<?>) getChildren.invoke(res.getContent()); Method getPathName = null; for (Object o : files) { if (getPathName == null) { getPathName = o.getClass().getMethod("getPathName"); } String pathName = (String) getPathName.invoke(o); if (pathName.endsWith(".class")) { String className = pathName.replace("/", ".").substring(0, pathName.length() - 6); classes.add(Class.forName(className, true, cld)); } } } catch (Exception e) { throw new IOException("Error while scanning " + res.toString(), e); } } else { directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8"))); } } } catch (NullPointerException x) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)", x); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)", encex); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname, ioex); } // 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) { // we are only interested in .class files if (file.endsWith(".class")) { // removes the .class extension classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6))); } } } else { throw new ClassNotFoundException( pckgname + " (" + directory.getPath() + ") does not appear to be a valid package"); } } Class<?>[] classesA = new Class[classes.size()]; classes.toArray(classesA); return classesA; }
From source file:uk.co.danielrendall.imagetiler.utils.PackageFinder.java
public static PackageFinder create() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); List<ClassInfo> tileClasses = new ArrayList<ClassInfo>(); List<ClassInfo> strategyClasses = new ArrayList<ClassInfo>(); assert classLoader != null; try {/*from ww w . ja v a 2 s.c o m*/ Log.app.info("Finding packages.properties files"); Enumeration<URL> resources = classLoader.getResources("packages.properties"); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); Log.app.info("Found file " + resource.toExternalForm()); Properties props = new Properties(); props.load(resource.openStream()); String author = props.getProperty("imagetiler.author"); String url = props.getProperty("imagetiler.url"); String tiles = props.getProperty("imagetiler.tiles"); String strategy = props.getProperty("imagetiler.strategy"); if (StringUtils.isNotBlank(tiles)) { Log.app.debug("Adding tiles in package '" + tiles + "'"); addAllClasses(SVGTile.class, tileClasses, tiles, author, url); } if (StringUtils.isNotBlank(strategy)) { Log.app.debug("Adding strategies in package '" + strategy + "'"); addAllClasses(ScannerStrategy.class, strategyClasses, strategy, author, url); } } } catch (Exception e) { Log.app.warn("Couldn't get tile classes", e); } return new PackageFinder(Collections.unmodifiableList(tileClasses), Collections.unmodifiableList(strategyClasses)); }
From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.java
/** * Returns the full path to the Jar containing the class. It always return a JAR. * * @param klass/* w ww . ja v a2 s . c o m*/ * class. * * @return path to the Jar containing the class. */ @SuppressWarnings("rawtypes") public static String jarFinderGetJar(Class klass) { Preconditions.checkNotNull(klass, "klass"); ClassLoader loader = klass.getClassLoader(); if (loader != null) { String class_file = klass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements();) { URL url = (URL) itr.nextElement(); String path = url.getPath(); if (path.startsWith("file:")) { path = path.substring("file:".length()); } path = URLDecoder.decode(path, "UTF-8"); if ("jar".equals(url.getProtocol())) { path = URLDecoder.decode(path, "UTF-8"); return path.replaceAll("!.*$", ""); } else if ("file".equals(url.getProtocol())) { String klassName = klass.getName(); klassName = klassName.replace(".", "/") + ".class"; path = path.substring(0, path.length() - klassName.length()); File baseDir = new File(path); File testDir = new File(System.getProperty("test.build.dir", "target/test-dir")); testDir = testDir.getAbsoluteFile(); if (!testDir.exists()) { testDir.mkdirs(); } File tempJar = File.createTempFile("hadoop-", "", testDir); tempJar = new File(tempJar.getAbsolutePath() + ".jar"); createJar(baseDir, tempJar); return tempJar.getAbsolutePath(); } } } catch (IOException e) { throw new RuntimeException(e); } } return null; }
From source file:org.apache.xml.security.utils.ClassLoaderUtils.java
/** * Load a given resources. <p/> This method will try to load the resources * using the following methods (in order): * <ul>// w ww . ja va 2 s . c o 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) { if (log.isDebugEnabled()) { log.debug(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) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (!urls.hasMoreElements()) { try { urls = cluClassloader.getResources(resourceName); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = cluClassloader.getResources(resourceName.substring(1)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } if (!urls.hasMoreElements()) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { try { urls = cl.getResources(resourceName); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(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.liferay.portal.util.InitUtil.java
public static synchronized void init() { if (_initialized) { return;/*w w w. j a v a2 s . c om*/ } StopWatch stopWatch = null; if (_PRINT_TIME) { stopWatch = new StopWatch(); stopWatch.start(); } // Set the default locale used by Liferay. This locale is no longer set // at the VM level. See LEP-2584. String userLanguage = SystemProperties.get("user.language"); String userCountry = SystemProperties.get("user.country"); String userVariant = SystemProperties.get("user.variant"); LocaleUtil.setDefault(userLanguage, userCountry, userVariant); // Set the default time zone used by Liferay. This time zone is no // longer set at the VM level. See LEP-2584. String userTimeZone = SystemProperties.get("user.timezone"); TimeZoneUtil.setDefault(userTimeZone); // Shared class loader try { Thread currentThread = Thread.currentThread(); PortalClassLoaderUtil.setClassLoader(currentThread.getContextClassLoader()); } catch (Exception e) { e.printStackTrace(); } // Log4J if (GetterUtil.getBoolean(SystemProperties.get("log4j.configure.on.startup"), true)) { ClassLoader classLoader = InitUtil.class.getClassLoader(); Log4JUtil.configureLog4J(classLoader.getResource("META-INF/portal-log4j.xml")); try { Log _log = LogFactoryUtil.getLog(InitUtil.class); String configName = "META-INF/portal-log4j-ext.xml"; Enumeration<URL> configs = classLoader.getResources(configName); if (_log.isDebugEnabled() && !configs.hasMoreElements()) { _log.debug("No " + configName + " has been found"); } while (configs.hasMoreElements()) { URL config = configs.nextElement(); Log4JUtil.configureLog4J(config); } } catch (Exception e) { e.printStackTrace(); } } // Shared log try { LogFactoryUtil.setLogFactory(new Log4jLogFactoryImpl()); } catch (Exception e) { e.printStackTrace(); } // Cache registry CacheRegistryUtil.setCacheRegistry(new CacheRegistryImpl()); // Configuration factory ConfigurationFactoryUtil.setConfigurationFactory(new ConfigurationFactoryImpl()); // Data source factory DataSourceFactoryUtil.setDataSourceFactory(new DataSourceFactoryImpl()); // DB factory DBFactoryUtil.setDBFactory(new DBFactoryImpl()); // Java properties JavaProps.isJDK5(); // ROME XmlReader.setDefaultEncoding(StringPool.UTF8); if (_PRINT_TIME) { System.out.println("InitAction takes " + stopWatch.getTime() + " ms"); } _initialized = true; }
From source file:org.cauldron.data.Conversions.java
/** * Initialize type conversion information. Read first from the internal * defaults, then from all overrides on the classpath. * /*from ww w . j a v a 2 s . com*/ * @throws DataException To wrap any exception that occurs while reading * resource files. */ private static synchronized void initialize() throws DataException { log = LogFactory.getLog(Conversions.class); byPair = new ConcurrentHashMap(); byTarget = new HashMap(); ClassLoader cl = Conversions.class.getClassLoader(); InputStream input = cl.getResourceAsStream(CONVERTER_DEFAULTS); if (input == null) throw new DataException("Internal error: resource " + CONVERTER_DEFAULTS + " not found"); try { getConversions(input); Enumeration e = cl.getResources(CONVERTER_OVERRIDES); while (e.hasMoreElements()) { URL url = (URL) e.nextElement(); input = url.openStream(); getConversions(input); } } catch (IOException e) { throw new DataException("I/O error reading type conversions", e); } catch (SAXException e) { throw new DataException("Parse error reading type conversions", e); } }