Example usage for java.lang ClassLoader getResources

List of usage examples for java.lang ClassLoader getResources

Introduction

In this page you can find the example usage for java.lang ClassLoader getResources.

Prototype

public Enumeration<URL> getResources(String name) throws IOException 

Source Link

Document

Finds all the resources with the given name.

Usage

From source file:com.springframework.core.io.support.SpringFactoriesLoader.java

/**
 * Load the fully qualified class names of factory implementations of the
 * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
 * class loader./*w ww.  j a v a 2 s.c om*/
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading resources; can be
 * {@code null} to use the default
 * @see #loadFactories
 * @throws IllegalArgumentException if an error occurs while loading factory names
 */
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    try {
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION)
                : ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        List<String> result = new ArrayList<String>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    } catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName()
                + "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}

From source file:com.cloudera.sqoop.util.Jars.java

/**
 * Return the jar file path that contains a particular class.
 * Method mostly cloned from o.a.h.mapred.JobConf.findContainingJar().
 *///from   w w  w  .  j  a  va2 s.  co  m
public static String getJarPathForClass(Class<? extends Object> classObj) {
    ClassLoader loader = classObj.getClassLoader();
    String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> 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());
                }
                // 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:io.fabric8.maven.core.extenvvar.ExternalEnvVarHandler.java

/**
 * Finds all of the environment json schemas and combines them together
 *///from ww  w  .j  ava  2 s  . co  m
private static JsonSchema loadEnvironmentSchemas(ClassLoader classLoader, String... folderPaths)
        throws IOException {
    JsonSchema answer = null;
    Enumeration<URL> resources = classLoader.getResources(ENVIRONMENT_SCHEMA_FILE);
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        JsonSchema schema = loadSchema(url);
        answer = combineSchemas(answer, schema);
    }
    for (String folderPath : folderPaths) {
        File file = new File(folderPath, ENVIRONMENT_SCHEMA_FILE);
        if (file.isFile()) {
            JsonSchema schema = loadSchema(file);
            answer = combineSchemas(answer, schema);
        }
    }
    return answer;
}

From source file:cz.lbenda.common.ClassLoaderHelper.java

/** Stream of class which is in given packages
 * @param basePackage base package// w  ww.j ava2 s  . com
 * @param classLoader class loader where is classes found
 * @return stream of class names */
public static List<String> classInPackage(String basePackage, ClassLoader classLoader) {
    List<String> result = new ArrayList<>();
    try {
        for (Enumeration<URL> resources = classLoader.getResources(basePackage.replace(".", "/")); resources
                .hasMoreElements();) {
            URL url = resources.nextElement();
            if (String.valueOf(url).startsWith("file:")) {
                File file = new File(url.getFile());
                int prefixLength = url.getFile().length() - basePackage.length();
                List<File> files = subClasses(file);
                files.stream().forEach(f -> {
                    String fName = f.getAbsolutePath();
                    result.add(fName.substring(prefixLength, fName.length() - 6).replace("/", "."));
                });
            } else {
                URLConnection urlCon = url.openConnection();
                if (urlCon instanceof JarURLConnection) {
                    JarURLConnection jarURLConnection = (JarURLConnection) urlCon;
                    try (JarFile jar = jarURLConnection.getJarFile()) {
                        jar.stream().forEach(entry -> {
                            String entryName = entry.getName();
                            if (entryName.endsWith(".class") && entryName.startsWith(basePackage)) {
                                result.add(entryName.substring(0, entryName.length() - 6));
                            }
                        });
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.apache.sqoop.connector.ConnectorManagerUtils.java

/**
 * Get a list of URLs of connectors that are installed.
 *
 * @return List of URLs.// w w w  . ja va 2  s .  co m
 */
public static List<URL> getConnectorConfigs() {
    List<URL> connectorConfigs = new ArrayList<URL>();

    try {
        // Check ConnectorManager classloader.
        Enumeration<URL> appPathConfigs = ConnectorManager.class.getClassLoader()
                .getResources(ConfigurationConstants.FILENAME_CONNECTOR_PROPERTIES);
        while (appPathConfigs.hasMoreElements()) {
            connectorConfigs.add(appPathConfigs.nextElement());
        }

        // Check thread context classloader.
        ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
        if (ctxLoader != null) {
            Enumeration<URL> ctxPathConfigs = ctxLoader
                    .getResources(ConfigurationConstants.FILENAME_CONNECTOR_PROPERTIES);

            while (ctxPathConfigs.hasMoreElements()) {
                URL configUrl = ctxPathConfigs.nextElement();
                if (!connectorConfigs.contains(configUrl)) {
                    connectorConfigs.add(configUrl);
                }
            }
        }
    } catch (IOException ex) {
        throw new SqoopException(ConnectorError.CONN_0001, ex);
    }

    return connectorConfigs;
}

From source file:org.suren.autotest.web.framework.util.EncryptorUtil.java

/**
 * @return ???//from   w  w w. j a  v a 2 s .  c o m
 */
public static String getSecretKey() {
    ClassLoader clsLoader = EncryptorUtil.class.getClassLoader();
    Enumeration<URL> urls = null;
    try {
        urls = clsLoader.getResources(ENCRYPT_FILE);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (urls == null || !urls.hasMoreElements()) {
        throw new RuntimeException("Can not found encrypt.properties!");
    }

    try (InputStream input = urls.nextElement().openStream()) {
        if (input == null) {
            throw new RuntimeException("Can not found encrypt.properties!");
        }

        Properties encryptPro = new Properties();
        encryptPro.load(input);

        if (!encryptPro.containsKey(ENCRYPT_KEY)) {
            throw new RuntimeException("Can not found " + ENCRYPT_KEY + " from encrypt.properties!");
        }

        return encryptPro.getProperty(ENCRYPT_KEY);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:cc.aileron.commons.util.ClassPattrnFinderUtils.java

/**
 * ??????/* w  w  w.  j a v  a2 s .  co m*/
 * 
 * @param targetPackage
 * @param pattern
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws ResourceNotFoundException
 */
private static final List<Class<?>> tryGetClassNameList(final String targetPackage, final Pattern pattern)
        throws IOException, URISyntaxException, ResourceNotFoundException {
    final List<Class<?>> result = new ArrayList<Class<?>>();

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    final String path = targetPackage.replace('.', '/') + "/";
    final Enumeration<URL> urls = classLoader.getResources(path);
    while (urls.hasMoreElements()) {
        final URL url = urls.nextElement();
        final Resource resource = ResourceConvertUtils.convertUrl(url);
        for (final FileObject file : resource.toFileObject().getChildren()) {
            final String name = file.getName().getBaseName().split("\\.")[0];
            if (!file.getType().equals(FileType.FILE) || !file.getName().getExtension().equals("class")) {
                continue;
            }
            if (pattern != null && !pattern.matcher(name).matches()) {
                continue;
            }

            final Class<?> classObject = getClass(targetPackage + "." + name);
            if (classObject != null) {
                result.add(classObject);
            }
        }
    }
    return result;
}

From source file:hm.binkley.util.ServiceBinder.java

private static <T> Enumeration<URL> configs(final Class<T> service, final ClassLoader classLoader) {
    try {/*from  w  w w.ja v  a 2s  . com*/
        return classLoader.getResources(PREFIX + service.getName());
    } catch (final IOException e) {
        return fail(service, "Cannot load configuration", e);
    }
}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static List<URL> getChildResources(String path) throws IOException, ClassNotFoundException {
    List<URL> result = new LinkedList<URL>();

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> p = classLoader.getResources(path);
    while (p.hasMoreElements()) {
        URL resource = p.nextElement();
        //System.out.println("resource: " + resource.toString());
        if (resource.getProtocol().equalsIgnoreCase("FILE")) {
            result.addAll(loadDirectory(resource.getFile()));
        } else if (resource.getProtocol().equalsIgnoreCase("JAR")) {
            result.addAll(loadJar(path, resource));
        } else if (resource.getProtocol().equalsIgnoreCase("VFS")) {
            result.addAll(loadVfs(resource));
        } else {/*from w w  w .  j  a va  2 s.co m*/
            throw new ClassNotFoundException(
                    "Unknown protocol on class resource: " + resource.toExternalForm());
        }
    }

    return result;
}

From source file:net.ymate.platform.commons.util.ResourceUtils.java

/**
 * /*from w  ww .j  av a2s  .  co  m*/
 * @param resourceName
 * @param callingClass
 * @param aggregate
 * @return
 * @throws IOException
 */
public static Iterator<URL> getResources(String resourceName, Class<?> callingClass, boolean aggregate)
        throws IOException {
    AggregateIterator<URL> iterator = new AggregateIterator<URL>();
    iterator.addEnumeration(Thread.currentThread().getContextClassLoader().getResources(resourceName));
    if ((!iterator.hasNext()) || (aggregate)) {
        iterator.addEnumeration(ClassUtils.getDefaultClassLoader().getResources(resourceName));
    }
    if ((!iterator.hasNext()) || (aggregate)) {
        ClassLoader cl = callingClass.getClassLoader();
        if (cl != null) {
            iterator.addEnumeration(cl.getResources(resourceName));
        }
    }
    if ((!iterator.hasNext()) && (resourceName != null)
            && (((resourceName.length() == 0) || (resourceName.charAt(0) != '/')))) {
        return getResources('/' + resourceName, callingClass, aggregate);
    }
    return iterator;
}