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.liferay.portal.service.impl.PortletLocalServiceImpl.java

private PortletCategory _readLiferayDisplayXML(String servletContextName, String xml) throws Exception {

    PortletCategory portletCategory = new PortletCategory();

    if (xml == null) {
        xml = ContentUtil.get("com/liferay/portal/deploy/dependencies/liferay-display.xml");
    }//from w ww  . j  a  va 2s .c  o m

    Document document = SAXReaderUtil.read(xml, true);

    Element rootElement = document.getRootElement();

    Set<String> portletIds = new HashSet<String>();

    _readLiferayDisplay(servletContextName, rootElement, portletCategory, portletIds);

    if (servletContextName == null) {
        ClassLoader classLoader = getClass().getClassLoader();
        String resourceName = "WEB-INF/liferay-display-ext.xml";
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
            _log.debug("No " + resourceName + " has been found");
        }
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (_log.isDebugEnabled()) {
                _log.debug("Loading " + resourceName + " from: " + resource);
            }

            if (resource == null) {
                continue;
            }

            InputStream is = new UrlResource(resource).getInputStream();
            try {
                String xmlExt = IOUtils.toString(is, "UTF-8");
                Document extDoc = SAXReaderUtil.read(xmlExt, true);

                Element extRootElement = extDoc.getRootElement();

                _readLiferayDisplay(servletContextName, extRootElement, portletCategory, portletIds);
            } catch (Exception e) {
                _log.error("Problem while loading file " + resource, e);
            } finally {
                is.close();
            }
        }

    }
    // Portlets that do not belong to any categories should default to the
    // Undefined category

    Set<String> undefinedPortletIds = new HashSet<String>();

    for (Portlet portlet : _getPortletsPool().values()) {
        String portletId = portlet.getPortletId();

        PortletApp portletApp = portlet.getPortletApp();

        if ((servletContextName != null) && (portletApp.isWARFile())
                && (portletId.endsWith(
                        PortletConstants.WAR_SEPARATOR + PortalUtil.getJsSafePortletId(servletContextName))
                        && (!portletIds.contains(portletId)))) {

            undefinedPortletIds.add(portletId);
        } else if ((servletContextName == null) && (!portletApp.isWARFile())
                && (portletId.indexOf(PortletConstants.WAR_SEPARATOR) == -1)
                && (!portletIds.contains(portletId))) {

            undefinedPortletIds.add(portletId);
        }
    }

    if (!undefinedPortletIds.isEmpty()) {
        PortletCategory undefinedCategory = new PortletCategory("category.undefined");

        portletCategory.addCategory(undefinedCategory);

        undefinedCategory.getPortletIds().addAll(undefinedPortletIds);
    }

    return portletCategory;
}

From source file:org.seasar.struts.hotdeploy.impl.ModuleConfigLoaderImpl.java

protected List splitAndResolvePaths(String paths) throws ServletException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    if (loader == null) {
        loader = this.getClass().getClassLoader();
    }//from  w w  w .  jav  a 2  s.co  m

    ArrayList resolvedUrls = new ArrayList();

    URL resource;
    String path = null;

    try {
        // Process each specified resource path
        while (paths.length() > 0) {
            resource = null;

            int comma = paths.indexOf(',');

            if (comma >= 0) {
                path = paths.substring(0, comma).trim();
                paths = paths.substring(comma + 1);
            } else {
                path = paths.trim();
                paths = "";
            }

            if (path.length() < 1) {
                break;
            }

            if (path.charAt(0) == '/') {
                resource = getServletContext().getResource(path);
            }

            if (resource == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to locate " + path + " in the servlet context, " + "trying classloader.");
                }

                Enumeration e = loader.getResources(path);

                if (!e.hasMoreElements()) {
                    String msg = getActionServlet().getInternal().getMessage("configMissing", path);

                    log.error(msg);
                    throw new UnavailableException(msg);
                } else {
                    while (e.hasMoreElements()) {
                        resolvedUrls.add(e.nextElement());
                    }
                }
            } else {
                resolvedUrls.add(resource);
            }
        }
    } catch (MalformedURLException e) {
        handleConfigException(path, e);
    } catch (IOException e) {
        handleConfigException(path, e);
    }

    return resolvedUrls;
}

From source file:org.apache.solr.util.SolrCLI.java

/**
 * Scans Jar files on the classpath for Tool implementations to activate.
 *//*from www  . j a  v a 2s .  co m*/
@SuppressWarnings("unchecked")
private static List<Class<Tool>> findToolClassesInPackage(String packageName) {
    List<Class<Tool>> toolClasses = new ArrayList<Class<Tool>>();
    try {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        Set<String> classes = new TreeSet<String>();
        while (resources.hasMoreElements()) {
            URL resource = (URL) resources.nextElement();
            classes.addAll(findClasses(resource.getFile(), packageName));
        }

        for (String classInPackage : classes) {
            Class<?> theClass = Class.forName(classInPackage);
            if (Tool.class.isAssignableFrom(theClass))
                toolClasses.add((Class<Tool>) theClass);
        }
    } catch (Exception e) {
        // safe to squelch this as it's just looking for tools to run
        log.debug("Failed to find Tool impl classes in " + packageName + " due to: " + e);
    }
    return toolClasses;
}

From source file:org.apache.struts.action.ActionServlet.java

/**
 * <p>Takes a comma-delimited string and splits it into paths, then
 * resolves those paths using the ServletContext and appropriate
 * ClassLoader.  When loading from the classloader, multiple resources per
 * path are supported to support, for example, multiple jars containing
 * the same named config file.</p>
 *
 * @param paths A comma-delimited string of paths
 * @return A list of resolved URL's for all found resources
 * @throws ServletException if a servlet exception is thrown
 *//*from w ww.ja va 2  s.co m*/
protected List splitAndResolvePaths(String paths) throws ServletException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    if (loader == null) {
        loader = this.getClass().getClassLoader();
    }

    ArrayList resolvedUrls = new ArrayList();

    URL resource;
    String path = null;

    try {
        // Process each specified resource path
        while (paths.length() > 0) {
            resource = null;

            int comma = paths.indexOf(',');

            if (comma >= 0) {
                path = paths.substring(0, comma).trim();
                paths = paths.substring(comma + 1);
            } else {
                path = paths.trim();
                paths = "";
            }

            if (path.length() < 1) {
                break;
            }

            if (path.charAt(0) == '/') {
                resource = getServletContext().getResource(path);
            }

            if (resource == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to locate " + path + " in the servlet context, " + "trying classloader.");
                }

                Enumeration e = loader.getResources(path);

                if (!e.hasMoreElements()) {
                    String msg = internal.getMessage("configMissing", path);

                    log.error(msg);
                    throw new UnavailableException(msg);
                } else {
                    while (e.hasMoreElements()) {
                        resolvedUrls.add(e.nextElement());
                    }
                }
            } else {
                resolvedUrls.add(resource);
            }
        }
    } catch (MalformedURLException e) {
        handleConfigException(path, e);
    } catch (IOException e) {
        handleConfigException(path, e);
    }

    return resolvedUrls;
}

From source file:org.apache.hadoop.hive.ql.exec.Utilities.java

/**
 * Returns the full path to the Jar containing the class. It always return a JAR.
 *
 * @param klass/*ww  w  . jav 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("!.*$", "");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Constructs a classpath to use for Java compilation.
 * //from  w w w  .j ava  2  s  . c  o  m
 * <p>This method will make a best-effort to create the classpath,
 * ignoring errors that occur during the collection.  This method
 * is not expected to throw exceptions, muddling on instead.
 *
 * @return a <code>Set&lt;String&gt;</code> value
 */
private Set<String> getClassPath() {
    // get the classloader that was used to load this class
    ClassLoader classLoader = getClass().getClassLoader();
    // this collection will hold all the paths we find, duplicates discarded, in the order they appear
    Set<String> paths = new LinkedHashSet<String>();
    //        //Collect all URLs from the URL Class Loaders.
    //        do {
    //            if(classLoader instanceof URLClassLoader) {
    //                URLClassLoader urlClassLoader = (URLClassLoader)classLoader;
    //                for(URL url : urlClassLoader.getURLs()) {
    //                    try {
    //                        paths.add(url.toURI().getPath());
    //                    } catch (URISyntaxException ignore) {
    //                    }
    //                }
    //            }
    //            // traverse the classloader tree upwards until no more remain
    //        } while((classLoader = classLoader.getParent()) != null);
    //        // reset the classloader to the current
    //        classLoader = getClass().getClassLoader();
    //iterate through the manifests of all the jars to find the
    // values of their Class-Path attribute value and add them to the
    // set.
    try {
        Enumeration<URL> resourceEnumeration = classLoader.getResources("META-INF/MANIFEST.MF");
        while (resourceEnumeration.hasMoreElements()) {
            URL resourceURL = resourceEnumeration.nextElement();
            InputStream is = null;
            try {
                // open the resource
                is = resourceURL.openStream();
                Manifest manifest = new Manifest(is);
                String theClasspath = manifest.getMainAttributes().getValue("Class-Path");
                if (theClasspath != null && !theClasspath.trim().isEmpty()) {
                    //manifest classpath is space separated URLs
                    for (String path : theClasspath.split(" ")) {
                        try {
                            URL pathURL = new URL(path);
                            paths.add(pathURL.toURI().getPath());
                        } catch (MalformedURLException ignore) {
                        } catch (URISyntaxException ignore) {
                        }
                    }
                }
            } catch (IOException ignore) {
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
    } catch (IOException ignore) {
    }
    return paths;
}

From source file:mondrian.olap.Util.java

/**
 * Similar to {@link ClassLoader#getResource(String)}, except the lookup
 *  is in reverse order.<br>/*from  w ww .  ja  v a 2 s.  co  m*/
 *  i.e. returns the resource from the supplied classLoader or the
 *  one closest to it in the hierarchy, instead of the closest to the root
 *  class loader
 * @param classLoader The class loader to fetch from
 * @param name The resource name
 * @return A URL object for reading the resource, or null if the resource
 * could not be found or the invoker doesn't have adequate privileges to get
 * the resource.
 * @see ClassLoader#getResource(String)
 * @see ClassLoader#getResources(String)
 */
public static URL getClosestResource(ClassLoader classLoader, String name) {
    URL resource = null;
    try {
        // The last resource will be from the nearest ClassLoader.
        Enumeration<URL> resourceCandidates = classLoader.getResources(name);
        while (resourceCandidates.hasMoreElements()) {
            resource = resourceCandidates.nextElement();
        }
    } catch (IOException ioe) {
        // ignore exception - it's OK if file is not found
        // just keep getResource contract and return null
        Util.discard(ioe);
    }
    return resource;
}

From source file:com.liferay.portal.tools.service.builder.ServiceBuilder.java

public static Set<String> readResourceActionModels(String implDir, String[] resourceActionsConfigs)
        throws Exception {

    Set<String> resourceActionModels = new HashSet<>();

    ClassLoader classLoader = ServiceBuilder.class.getClassLoader();

    for (String config : resourceActionsConfigs) {
        if (config.startsWith("classpath*:")) {
            String name = config.substring("classpath*:".length());

            Enumeration<URL> enu = classLoader.getResources(name);

            while (enu.hasMoreElements()) {
                URL url = enu.nextElement();

                InputStream inputStream = url.openStream();

                _readResourceActionModels(implDir, inputStream, resourceActionModels);
            }/*from w w w  . j a  v  a2 s  . com*/
        } else {
            Enumeration<URL> urls = classLoader.getResources(config);

            if (urls.hasMoreElements()) {
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();

                    try (InputStream inputStream = url.openStream()) {
                        _readResourceActionModels(implDir, inputStream, resourceActionModels);
                    }
                }
            } else {
                File file = new File(config);

                if (!file.exists()) {
                    file = new File(implDir, config);
                }

                if (!file.exists()) {
                    continue;
                }

                try (InputStream inputStream = new FileInputStream(file)) {
                    _readResourceActionModels(implDir, inputStream, resourceActionModels);
                }
            }
        }
    }

    return resourceActionModels;
}