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:org.apache.oozie.service.ShareLibService.java

/**
 * Find containing jar containing./*from  w  w w .  j  a v  a 2 s  . co  m*/
 *
 * @param clazz the clazz
 * @return the string
 */
@VisibleForTesting
protected String findContainingJar(Class clazz) {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    try {
        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());
                    // 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");
                    toReturn = toReturn.replaceAll("!.*$", "");
                    return toReturn;
                }
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    return null;
}

From source file:org.apache.hadoop.mapred.JobConf.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.
 * //from   ww w  . ja v  a  2s. co  m
 * @param my_class the class to find.
 * @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());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.sonar.classloader.ClassloaderBuilderTest.java

/**
 * - sibling contains A and B/*from w w  w  .  j a  va 2s  .  c o m*/
 * - child contains C and excludes A from sibling -> sees only B and C
 */
@Test
public void sibling_mask() throws Exception {
    Map<String, ClassLoader> newClassloaders = sut.newClassloader("sib1")
            .addURL("sib1", new File("tester/a.jar").toURL()).addURL("sib1", new File("tester/b.jar").toURL())

            .newClassloader("the-child").addURL("the-child", new File("tester/c.jar").toURL())
            .addSibling("the-child", "sib1", Mask.builder().exclude("A.class", "a.txt").build()).build();

    ClassLoader sib1 = newClassloaders.get("sib1");
    assertThat(canLoadClass(sib1, "A")).isTrue();
    assertThat(canLoadClass(sib1, "B")).isTrue();
    assertThat(canLoadResource(sib1, "a.txt")).isTrue();
    assertThat(canLoadResource(sib1, "b.txt")).isTrue();

    ClassLoader child = newClassloaders.get("the-child");
    assertThat(canLoadClass(child, "A")).isFalse();
    assertThat(canLoadClass(child, "B")).isTrue();
    assertThat(canLoadClass(child, "C")).isTrue();
    assertThat(canLoadResource(child, "a.txt")).isFalse();
    assertThat(canLoadResource(child, "b.txt")).isTrue();
    assertThat(canLoadResource(child, "c.txt")).isTrue();
    assertThat(Collections.list(child.getResources("a.txt"))).hasSize(0);
    assertThat(Collections.list(child.getResources("b.txt"))).hasSize(1);
    assertThat(Collections.list(child.getResources("c.txt"))).hasSize(1);
}

From source file:org.sonar.classloader.ClassloaderBuilderTest.java

/**
 * - sibling contains A and B but exports only B
 * - child contains C -> sees only B and C
 *///from ww w . j  ava  2 s  . c o m
@Test
public void sibling_export_mask() throws Exception {
    Map<String, ClassLoader> newClassloaders = sut.newClassloader("sib1")
            .addURL("sib1", new File("tester/a.jar").toURL()).addURL("sib1", new File("tester/b.jar").toURL())
            .setExportMask("sib1", Mask.builder().include("B.class", "b.txt").build())

            .newClassloader("the-child").addURL("the-child", new File("tester/c.jar").toURL())
            .addSibling("the-child", "sib1", Mask.ALL).build();

    ClassLoader sib1 = newClassloaders.get("sib1");
    assertThat(canLoadClass(sib1, "A")).isTrue();
    assertThat(canLoadClass(sib1, "B")).isTrue();
    assertThat(canLoadResource(sib1, "a.txt")).isTrue();
    assertThat(canLoadResource(sib1, "b.txt")).isTrue();

    ClassLoader child = newClassloaders.get("the-child");
    assertThat(canLoadClass(child, "A")).isFalse();
    assertThat(canLoadClass(child, "B")).isTrue();
    assertThat(canLoadClass(child, "C")).isTrue();
    assertThat(canLoadResource(child, "a.txt")).isFalse();
    assertThat(canLoadResource(child, "b.txt")).isTrue();
    assertThat(canLoadResource(child, "c.txt")).isTrue();
    assertThat(Collections.list(child.getResources("a.txt"))).hasSize(0);
    assertThat(Collections.list(child.getResources("b.txt"))).hasSize(1);
    assertThat(Collections.list(child.getResources("c.txt"))).hasSize(1);
}

From source file:org.topazproject.otm.impl.SessionFactoryImpl.java

public void preloadFromClasspath(String res, ClassLoader cl) throws OtmException {
    try {// ww w . jav a  2 s . co  m
        Enumeration<URL> rs = cl.getResources(res);
        while (rs.hasMoreElements())
            new ResourceProcessor(rs.nextElement()).run();
    } catch (IOException e) {
        throw new OtmException("Unable to load resources", e);
    }
}

From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java

private boolean registerInterpreterFromResource(ClassLoader cl, String interpreterDir, String interpreterJson)
        throws IOException, RepositoryException {
    URL[] urls = recursiveBuildLibList(new File(interpreterDir));
    ClassLoader tempClassLoader = new URLClassLoader(urls, cl);

    Enumeration<URL> interpreterSettings = tempClassLoader.getResources(interpreterJson);
    if (!interpreterSettings.hasMoreElements()) {
        return false;
    }/*from www  .j  a v  a 2 s.  c  o  m*/
    for (URL url : Collections.list(interpreterSettings)) {
        try (InputStream inputStream = url.openStream()) {
            logger.debug("Reading {} from {}", interpreterJson, url);
            List<RegisteredInterpreter> registeredInterpreterList = getInterpreterListFromJson(inputStream);
            registerInterpreters(registeredInterpreterList, interpreterDir);
        }
    }
    return true;
}

From source file:org.apache.slider.common.tools.SliderUtils.java

/**
 * Find a containing JAR//from   ww w  .j  a  v a 2 s  .c o  m
 * @param my_class class to find
 * @return the file or null if it is not found
 * @throws IOException any IO problem, including the class not having a
 * classloader
 */
public static File findContainingJar(Class my_class) throws IOException {
    ClassLoader loader = my_class.getClassLoader();
    if (loader == null) {
        throw new IOException("Class " + my_class + " does not have a classloader!");
    }
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    Enumeration<URL> urlEnumeration = loader.getResources(class_file);
    if (urlEnumeration == null) {
        throw new IOException("Unable to find resources for class " + my_class);
    }

    for (; urlEnumeration.hasMoreElements();) {
        URL url = urlEnumeration.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");
            String jarFilePath = toReturn.replaceAll("!.*$", "");
            return new File(jarFilePath);
        } else {
            log.info("could not locate JAR containing {} URL={}", my_class, url);
        }
    }
    return null;
}

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

/**
 * Returns an input stream for a resource/filename.  Logic will first attempt to find
 * a filename that matches the resourceName (search is case-insensitive).  If a file
 * is found, the stream is for the file.
 *
 * If a file is not found, an attempt is made to find the resource on the classpath.
 *
 * @param task - If not null then the ZEIDON_HOME directory will be searched if all
 *                other attempts fail.//from  w w  w . java 2s  .  c  om
 * @param resourceName - Name of resource to open.
 * @param classLoader - ClassLoader used to find resources.  If null then the system
 *                class loader is used.
 *
 * @return the InputStream or null if it wasn't found.
 */
public static ZeidonInputStream getInputStream(Task task, String resourceName, ClassLoader classLoader) {
    // If the resourceName contains a '|' then it is a list of resources.  We'll return the first
    // one that is valid.
    String[] resourceList = PIPE_DELIMITER.split(resourceName);
    if (resourceList.length > 1) {
        for (String resource : resourceList) {
            ZeidonInputStream stream = getInputStream(task, resource.trim(), classLoader);
            if (stream != null)
                return stream;
        }

        // If we get here then none of the resources in the list were found so return null.
        return null;
    }

    try {
        //
        // Default is to assume resourceName is a filename.
        //
        File file = getFile(resourceName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        if (classLoader == null) {
            if (task != null)
                classLoader = task.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = new JoeUtils().getClass().getClassLoader();
            if (classLoader == null)
                classLoader = resourceName.getClass().getClassLoader();
            if (classLoader == null)
                classLoader = ClassLoader.getSystemClassLoader();
        }

        //
        // Try loading as a resource (e.g. from a .jar).
        //
        int count = 0;
        ZeidonInputStream stream = null;
        URL prevUrl = null;
        String md5hash = null;
        for (Enumeration<URL> url = classLoader.getResources(resourceName); url.hasMoreElements();) {
            URL element = url.nextElement();
            if (task != null)
                task.log().debug("Found resource at " + element);
            else
                LOG.debug("--Found resource at " + element);

            count++;
            if (count > 1) {
                // We'll allow duplicate resources if they have the same MD5 hash.
                if (md5hash == null)
                    md5hash = computeHash(prevUrl);

                if (!md5hash.equals(computeHash(element)))
                    throw new ZeidonException("Found multiple different resources that match resourceName %s",
                            resourceName);

                if (task != null)
                    task.log().warn(
                            "Multiple, identical resources found of %s.  This usually means your classpath has duplicates",
                            resourceName);
                else
                    LOG.warn("Multiple, identical resources found of " + resourceName
                            + " This usually means your classpath has duplicates");

            }

            stream = ZeidonInputStream.create(element);
            prevUrl = element;
        }

        if (stream != null)
            return stream;

        //
        // Try loading as a lower-case resource name.
        //
        String name = FilenameUtils.getName(resourceName);
        if (StringUtils.isBlank(name))
            return null;

        String path = FilenameUtils.getPath(resourceName);
        String newName;
        if (StringUtils.isBlank(path))
            newName = name.toLowerCase();
        else
            newName = path + name.toLowerCase();

        stream = ZeidonInputStream.create(classLoader, newName);
        if (stream != null)
            return stream;

        // If task is null then we don't know anything else to try.
        if (task == null)
            return null;

        //
        // Try loading with ZEIDON_HOME prefix.
        //
        newName = task.getObjectEngine().getHomeDirectory() + "/" + resourceName;
        file = getFile(newName);
        if (file.exists())
            return ZeidonInputStream.create(file);

        return null;
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependFilename(resourceName);
    }
}

From source file:net.ymate.platform.plugin.impl.DefaultPluginParser.java

public Map<String, PluginMeta> doParser() throws PluginParserException {
    Map<String, PluginMeta> _returnValue = new HashMap<String, PluginMeta>();
    try {//from  w  w w . j  ava  2  s . c o  m
        // ?CLASSPATH???Jar
        List<String> _excludePluginIds = new ArrayList<String>();
        Iterator<URL> _configURLs = ResourceUtils
                .getResources(__pluginFactory.getPluginConfig().getPluginManifestFile(), this.getClass(), true);
        while (_configURLs.hasNext()) {
            URL _configURL = _configURLs.next();
            List<PluginMeta> _metas = __doManifestFileProcess(__pluginFactory.getPluginClassLoader(), null,
                    _configURL);
            // ?CLASSPATH???
            for (PluginMeta _meta : _metas) {
                if (__pluginFactory.getPluginConfig().isIncludeClassPath()) {
                    _returnValue.put(_meta.getId(), _meta);
                }
                _excludePluginIds.add(_meta.getId());
            }
        }
        // ??PLUGIN_HOME?
        if (StringUtils.isNotBlank(__pluginFactory.getPluginConfig().getPluginHomePath())) {
            File _pluginDirFile = new File(__pluginFactory.getPluginConfig().getPluginHomePath());
            if (_pluginDirFile.exists() && _pluginDirFile.isDirectory()) {
                File[] _subDirFiles = _pluginDirFile.listFiles();
                for (File _subDirFile : _subDirFiles != null ? _subDirFiles : new File[0]) {
                    if (_subDirFile.isDirectory()) {
                        ClassLoader _currentLoader = __doCreatePluginClassLoader(_subDirFile.getPath());
                        // ???
                        File _manifestFile = new File(_subDirFile,
                                __pluginFactory.getPluginConfig().getPluginManifestFile());
                        if (_manifestFile.exists() && _manifestFile.isFile()) {
                            List<PluginMeta> _metas = __doManifestFileProcess(_currentLoader,
                                    _subDirFile.getPath(), _manifestFile.toURI().toURL());
                            for (PluginMeta _meta : _metas) {
                                _returnValue.put(_meta.getId(), _meta);
                            }
                        } else {
                            // ???JAR?
                            Enumeration<URL> _pluginConfigURLs = _currentLoader
                                    .getResources(__pluginFactory.getPluginConfig().getPluginManifestFile());
                            while (_pluginConfigURLs.hasMoreElements()) {
                                List<PluginMeta> _metas = __doManifestFileProcess(_currentLoader,
                                        _subDirFile.getPath(), _pluginConfigURLs.nextElement());
                                for (PluginMeta _meta : _metas) {
                                    if (_excludePluginIds.contains(_meta.getId())) {
                                        // CLASSPATH?Jar?????
                                        break;
                                    }
                                    _returnValue.put(_meta.getId(), _meta);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new PluginParserException(RuntimeUtils.unwrapThrow(e));
    }
    return _returnValue;
}