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.agilejava.docbkx.maven.AbstractTransformerMojo.java

/**
 * Creates a <code>CatalogManager</code>, used to resolve DTDs and other entities.
 *
 * @return A <code>CatalogManager</code> to be used for resolving DTDs and other entities.
 *///www  .j  a  va  2  s .c om
protected CatalogManager createCatalogManager() {
    CatalogManager manager = new CatalogManager();
    manager.setIgnoreMissingProperties(true);
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    StringBuffer builder = new StringBuffer();
    boolean first = true;
    for (int i = 0; i < catalogs.length; i++) {
        final String catalog = catalogs[i];
        try {
            Enumeration enumeration = classLoader.getResources(catalog);
            while (enumeration.hasMoreElements()) {
                if (!first) {
                    builder.append(';');
                } else {
                    first = false;
                }
                URL resource = (URL) enumeration.nextElement();
                builder.append(resource.toExternalForm());
            }
        } catch (IOException ioe) {
            getLog().warn("Failed to search for catalog files: " + catalog);
            // Let's be a little tolerant here.
        }
    }

    String catalogFiles = builder.toString();
    if (catalogFiles.length() == 0) {
        getLog().warn("Failed to find catalog files.");
    } else {
        if (getLog().isDebugEnabled()) {
            getLog().debug("Catalogs to load: " + catalogFiles);
        }
        manager.setCatalogFiles(catalogFiles);
    }
    return manager;
}

From source file:com.streamsets.datacollector.stagelibrary.ClassLoaderStageLibraryTask.java

@VisibleForTesting
void loadStages() {
    if (LOG.isDebugEnabled()) {
        for (ClassLoader cl : stageClassLoaders) {
            LOG.debug("About to load stages from library '{}'", StageLibraryUtils.getLibraryName(cl));
        }//from ww w  . jav a  2  s. c  o  m
    }

    try {
        RuntimeEL.loadRuntimeConfiguration(runtimeInfo);
    } catch (IOException e) {
        throw new RuntimeException(Utils.format("Could not load runtime configuration, '{}'", e.toString()), e);
    }

    try {
        int libs = 0;
        int stages = 0;
        long start = System.currentTimeMillis();
        LocaleInContext.set(Locale.getDefault());
        for (ClassLoader cl : stageClassLoaders) {
            libs++;
            StageLibraryDefinition libDef = StageLibraryDefinitionExtractor.get().extract(cl);
            LOG.debug("Loading stages from library '{}'", libDef.getName());
            try {
                Enumeration<URL> resources = cl.getResources(STAGES_DEFINITION_RESOURCE);
                while (resources.hasMoreElements()) {
                    Map<String, String> stagesInLibrary = new HashMap<>();
                    URL url = resources.nextElement();
                    try (InputStream is = url.openStream()) {
                        List<String> stageList = json.readValue(is, List.class);
                        stageList = removeIgnoreStagesFromList(libDef, stageList);
                        for (String className : stageList) {
                            stages++;
                            Class<? extends Stage> klass = (Class<? extends Stage>) cl.loadClass(className);
                            StageDefinition stage = StageDefinitionExtractor.get().extract(libDef, klass,
                                    Utils.formatL("Library='{}'", libDef.getName()));
                            String key = createKey(libDef.getName(), stage.getName());
                            LOG.debug("Loaded stage '{}' (library:name)", key);
                            if (stagesInLibrary.containsKey(key)) {
                                throw new IllegalStateException(Utils.format(
                                        "Library '{}' contains more than one definition for stage '{}', class '{}' and class '{}'",
                                        libDef.getName(), key, stagesInLibrary.get(key),
                                        stage.getStageClass()));
                            }
                            stagesInLibrary.put(key, stage.getClassName());
                            this.stageList.add(stage);
                            stageMap.put(key, stage);
                            computeDependsOnChain(stage);
                        }
                    }
                }
            } catch (IOException | ClassNotFoundException ex) {
                throw new RuntimeException(
                        Utils.format("Could not load stages definition from '{}', {}", cl, ex.toString()), ex);
            }
        }
        LOG.debug("Loaded '{}' libraries with a total of '{}' stages in '{}ms'", libs, stages,
                System.currentTimeMillis() - start);
    } finally {
        LocaleInContext.set(null);
    }
}

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

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

    if (loader == null) {
        loader = this.getClass().getClassLoader();
    }//  w w  w. ja  va 2  s. c o 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) {
        throw new ServletException(path, e);
    } catch (IOException e) {
        throw new ServletException(path, e);
    }

    return resolvedUrls;
}

From source file:org.geoserver.gwc.GWCTest.java

@Test
public void testGetPluggabledAdvertisedCachedFormats() throws IOException {
    List<URL> urls;//  w  w w  .j ava2  s .c  o m
    try {
        // load the default and test resources separately so they are named differently and we
        // don't get the ones for testing listed in the UI when running from eclipse
        String defaultResource = "org/geoserver/gwc/advertised_formats.properties";
        String testResource = "org/geoserver/gwc/advertised_formats_unittesting.properties";
        ClassLoader classLoader = GWC.class.getClassLoader();
        urls = newArrayList(forEnumeration(classLoader.getResources(defaultResource)));
        urls.addAll(newArrayList(forEnumeration(classLoader.getResources(testResource))));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // from src/main/resources/org/geoserver/gwc/advertised_formats.properties
    Set<String> defaultFormats = ImmutableSet.of("image/png", "image/png8", "image/jpeg", "image/gif",
            "image/vnd.jpeg-png");

    // see src/test/resources/org/geoserver/gwc/advertised_formats.properties
    Set<String> expectedVector = union(defaultFormats,
            ImmutableSet.of("test/vector1", "test/vector2", "application/json;type=utfgrid"));
    Set<String> expectedRaster = union(defaultFormats,
            ImmutableSet.of("test/raster1", "test/raster2;type=test"));
    Set<String> expectedGroup = union(defaultFormats,
            ImmutableSet.of("test/group1", "test/group2", "application/json;type=utfgrid"));

    assertEquals(expectedVector, GWC.getAdvertisedCachedFormats(PublishedType.VECTOR, urls));
    assertEquals(expectedVector, GWC.getAdvertisedCachedFormats(PublishedType.REMOTE, urls));

    assertEquals(expectedRaster, GWC.getAdvertisedCachedFormats(PublishedType.RASTER, urls));
    assertEquals(expectedRaster, GWC.getAdvertisedCachedFormats(PublishedType.WMS, urls));

    assertEquals(expectedGroup, GWC.getAdvertisedCachedFormats(PublishedType.GROUP, urls));
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

protected List getCompileDependencyResources(MavenProject project, String resourcePath)
        throws MavenReportException {
    try {// w ww  .  j  a v  a 2s. c o  m
        ClassLoader cl = createCompileClassLoader(project);
        Enumeration e = cl.getResources(resourcePath);
        List urls = new ArrayList();
        while (e.hasMoreElements()) {
            URL url = (URL) e.nextElement();
            urls.add(url);
        }
        return Collections.unmodifiableList(urls);
    } catch (IOException e) {
        throw new MavenReportException("Unable to get resources for path " + "\"" + resourcePath + "\"", e);
    }

}

From source file:com.sonicle.webtop.core.app.ServiceManager.java

private Map<String, ServiceManifest> discoverServices() throws IOException {
    ClassLoader cl = LangUtils.findClassLoader(getClass());

    // Scans classpath looking for service descriptor files
    Enumeration<URL> enumResources = null;
    try {/* w  w w . j a  v  a  2s .co m*/
        enumResources = cl.getResources(SERVICES_DESCRIPTOR_RESOURCE);
    } catch (IOException ex) {
        throw ex;
    }

    // Parses and splits descriptor files into a single manifest file for each service
    HashMap<String, ServiceManifest> manifests = new HashMap();
    while (enumResources.hasMoreElements()) {
        URL url = enumResources.nextElement();
        try {
            Collection<ServiceManifest> parsed = parseDescriptor(url);
            for (ServiceManifest manifest : parsed) {
                String key = manifest.getId();
                if (!manifests.containsKey(key)) {
                    manifests.put(manifest.getId(), manifest);

                } else if (manifest.getVersion().compareTo(manifests.get(key).getVersion()) > 0) {
                    logger.warn("[{}] Version {} replaced by {}", manifest.getId(),
                            manifests.get(key).getVersion(), manifest.getVersion());
                    manifests.put(manifest.getId(), manifest);
                }
            }
        } catch (ConfigurationException ex) {
            logger.error("Error while reading descriptor [{}]", url.toString(), ex);
        }
    }

    List<String> orderdKeys = manifests.keySet().stream().sorted((s1, s2) -> {
        if (StringUtils.startsWith(s1, CoreManifest.ID)) {
            return -1;
        } else {
            return s1.compareTo(s2);
        }
    }).collect(Collectors.toList());

    LinkedHashMap<String, ServiceManifest> map = new LinkedHashMap<>(orderdKeys.size());
    for (String key : orderdKeys) {
        map.put(key, manifests.get(key));
    }
    return map;
}

From source file:org.apache.openejb.cdi.OptimizedLoaderService.java

private boolean isFiltered(final Collection<Extension> extensions, final Extension next) {
    final ClassLoader containerLoader = ParentClassLoaderFinder.Helper.get();
    final Class<? extends Extension> extClass = next.getClass();
    if (extClass.getClassLoader() != containerLoader) {
        return false;
    }/*from  ww w  .  ja v a  2  s  .  c om*/

    final String name = extClass.getName();
    switch (name) {
    case "org.apache.bval.cdi.BValExtension":
        for (final Extension e : extensions) {
            final String en = e.getClass().getName();

            // org.hibernate.validator.internal.cdi.ValidationExtension but allowing few evolutions of packages
            if (en.startsWith("org.hibernate.validator.") && en.endsWith("ValidationExtension")) {
                log.info("Skipping BVal CDI integration cause hibernate was found in the application");
                return true;
            }
        }
        break;
    case "org.apache.batchee.container.cdi.BatchCDIInjectionExtension": // see org.apache.openejb.batchee.BatchEEServiceManager
        return "true".equals(SystemInstance.get().getProperty("tomee.batchee.cdi.use-extension", "false"));
    case "org.apache.commons.jcs.jcache.cdi.MakeJCacheCDIInterceptorFriendly":
        final String spi = "META-INF/services/javax.cache.spi.CachingProvider";
        try {
            final Enumeration<URL> appResources = Thread.currentThread().getContextClassLoader()
                    .getResources(spi);
            if (appResources != null && appResources.hasMoreElements()) {
                final Collection<URL> containerResources = Collections.list(containerLoader.getResources(spi));
                do {
                    if (!containerResources.contains(appResources.nextElement())) {
                        log.info(
                                "Skipping JCS CDI integration cause another provide was found in the application");
                        return true;
                    }
                } while (appResources.hasMoreElements());
            }
        } catch (final Exception e) {
            // no-op
        }
        break;
    default:
    }
    return false;
}

From source file:org.jahia.data.templates.JahiaTemplatesPackage.java

/**
 * Returns a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and
 * at the end the list of class loaders of modules this module depends on.
 *
 * @return a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and
 *         at the end the list of class loaders of modules this module depends on
 *//*w w  w .j a v  a 2s . c o m*/
public ClassLoader getChainedClassLoader() {

    if (chainedClassLoader != null) {
        return chainedClassLoader;
    }

    final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
    classLoaders.add(Jahia.class.getClassLoader());
    final ClassLoader classLoader = getClassLoader();
    if (classLoader != null) {
        classLoaders.add(classLoader);
    }
    for (JahiaTemplatesPackage dependentPack : getDependencies()) {
        if (dependentPack != null && dependentPack.getClassLoader() != null) {
            classLoaders.add(dependentPack.getClassLoader());
        }
    }

    chainedClassLoader = new ClassLoader() {

        @Override
        public URL getResource(String name) {
            URL url = null;
            for (ClassLoader loader : classLoaders) {
                url = loader.getResource(name);
                if (url != null)
                    return url;
            }
            return url;
        }

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

            final List<Enumeration<URL>> urlsEnums = new ArrayList<Enumeration<URL>>();
            for (ClassLoader loader : classLoaders) {
                Enumeration<URL> urls = loader.getResources(name);
                if (urls != null && urls.hasMoreElements()) {
                    // we only add enumerations that have elements, make things simpler
                    urlsEnums.add(urls);
                }
            }

            if (urlsEnums.size() == 0) {
                return java.util.Collections.emptyEnumeration();
            }

            return new Enumeration<URL>() {

                int i = 0;
                Enumeration<URL> currentEnum = urlsEnums.get(i);

                @Override
                public boolean hasMoreElements() {
                    if (currentEnum.hasMoreElements()) {
                        return true;
                    }
                    int j = i;
                    do {
                        j++;
                    } while (j < (urlsEnums.size() - 1) && !urlsEnums.get(j).hasMoreElements());
                    if (j <= (urlsEnums.size() - 1)) {
                        return urlsEnums.get(j).hasMoreElements();
                    } else {
                        return false;
                    }
                }

                @Override
                public URL nextElement() {
                    if (currentEnum.hasMoreElements()) {
                        return currentEnum.nextElement();
                    }
                    do {
                        i++;
                        currentEnum = urlsEnums.get(i);
                    } while (!currentEnum.hasMoreElements() && i < (urlsEnums.size() - 1));
                    if (currentEnum.hasMoreElements()) {
                        return currentEnum.nextElement();
                    } else {
                        throw new NoSuchElementException();
                    }
                }
            };
        }

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            for (ClassLoader classLoader : classLoaders) {
                try {
                    Class<?> clazz = classLoader.loadClass(name);
                    if (resolve) {
                        resolveClass(clazz);
                    }
                    return clazz;
                } catch (ClassNotFoundException e) {
                    // keep moving through the classloaders
                }
            }
            throw new ClassNotFoundException(name);
        }
    };

    return chainedClassLoader;
}

From source file:com.liferay.portal.service.impl.PortletLocalServiceImpl.java

private Set<String> _readPortletExtXML(ServletContext servletContext, Map<String, Portlet> portletsPool,
        Set<String> servletURLPatterns, PluginPackage pluginPackage) throws Exception {

    Set<String> result = new HashSet();

    ClassLoader classLoader = getClass().getClassLoader();
    // load xmls// w  ww  . ja  v a2s  .c  o  m
    String resourceName = "WEB-INF/portlet-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");
            result.addAll(
                    _readPortletXML(servletContext, xmlExt, portletsPool, servletURLPatterns, pluginPackage));
        } catch (Exception e) {
            _log.error("Problem while loading file " + resource, e);
        } finally {
            is.close();
        }
    }

    return result;

}

From source file:com.liferay.portal.service.impl.PortletLocalServiceImpl.java

private Set<String> _readLiferayPortletExtXML(Map<String, Portlet> portletsPool) throws Exception {

    Set<String> result = new HashSet();
    ClassLoader classLoader = getClass().getClassLoader();
    // load xmls/*from w w w . j  a va2s  .c  o  m*/
    String resourceName = "WEB-INF/liferay-portlet-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");
            result.addAll(_readLiferayPortletXML(xmlExt, portletsPool));
        } catch (Exception e) {
            _log.error("Problem while loading file " + resource, e);
        } finally {
            is.close();
        }
    }

    return result;
}