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:uk.co.danielrendall.imagetiler.registry.PluginRegistryBuilder.java

private VendorRegistryInfo getVendorRegistryInfo(ClassLoader classLoader, String pluginType) {
    String propertiesFileName = pluginTypeToPropertiesName.get(pluginType);
    Class baseClass = propertyFileToBaseClass.get(propertiesFileName);
    VendorRegistry vendorRegistry = new VendorRegistry();
    Log.app.info("Finding " + propertiesFileName + " files");
    try {//  w w w. j  a  v a  2  s .  c  o m
        Enumeration<URL> resources = classLoader.getResources(propertiesFileName);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            Log.app.info("Found file " + resource.toExternalForm());
            Properties props = new Properties();
            try {
                props.load(resource.openStream());
                PackageProperties packageProperties = new PackageProperties(props);
                if (StringUtils.isBlank(packageProperties.getPackage())) {
                    Log.app.warn("Ignoring " + resource.toExternalForm() + " as no package specified");
                } else if (StringUtils.isBlank(packageProperties.getVendor())) {
                    Log.app.warn("Ignoring " + resource.toExternalForm() + " as no vendor specified");
                } else {
                    try {
                        ClassRegistryInfo classRegistryInfo = getClassRegistryInfo(classLoader, baseClass,
                                packageProperties);
                        vendorRegistry.add(classRegistryInfo);
                    } catch (Exception e) {
                        Log.app.warn("Couldn't get tile classes for package " + packageProperties.getPackage(),
                                e);
                    }
                }
            } catch (IOException e) {
                Log.app.warn("Couldn't get properties from " + resource.toString(), e);
            }
        }
    } catch (IOException e) {
        Log.app.warn("Couldn't enumerate properties files " + propertiesFileName, e);
    }
    VendorRegistryInfo vendorRegistryInfo = new VendorRegistryInfo(pluginType, baseClass, vendorRegistry);
    return vendorRegistryInfo;
}

From source file:de.smartics.maven.plugin.jboss.modules.parser.ModulesXmlLocator.java

/**
 * Discovers all module descriptors on the class path.
 *
 * @param classLoader the class loader whose class path is searched.
 * @param rootDirectories additional root directories to check first.
 * @return the discovered module descriptors.
 * @throws IOException if resources cannot be loaded from the class path.
 */// www .j  av  a2 s .  c o  m
public List<ModulesDescriptor> discover(final ClassLoader classLoader, final List<File> rootDirectories)
        throws IOException {
    final List<ModulesDescriptor> modules = new ArrayList<ModulesDescriptor>();

    for (final File rootDirectory : rootDirectories) {
        loadModules(modules, rootDirectory);
    }

    final ClassPathListing listing = new JarAndFileClassPathListing();
    final ClassPathContext context = new ClassPathContext(classLoader, null);
    final Enumeration<URL> urls = classLoader.getResources("jboss-modules");
    while (urls.hasMoreElements()) {
        final List<String> fileList = listing.list(context, "jboss-modules");
        final URL url = urls.nextElement();
        loadModules(modules, url, fileList);
    }

    if (targetSlot != null) {
        for (final ModulesDescriptor module : modules) {
            module.applyDefaultSlot(targetSlot);
        }
    }

    return modules;
}

From source file:mondrian.util.ServiceDiscovery.java

/**
 * Returns a list of classes that implement the service.
 *
 * @return List of classes that implement the service
 *//*from   ww  w  .  java 2  s  . c o  m*/
public List<Class<T>> getImplementor() {
    // Use linked hash set to eliminate duplicates but still return results
    // in the order they were added.
    Set<Class<T>> uniqueClasses = new LinkedHashSet<Class<T>>();

    ClassLoader cLoader = Thread.currentThread().getContextClassLoader();
    if (cLoader == null) {
        cLoader = this.getClass().getClassLoader();
    }
    try {
        // Enumerate the files because I may have more than one .jar file
        // that contains an implementation for the interface, and therefore,
        // more than one list of entries.
        String lookupName = "META-INF/services/" + theInterface.getName();
        Enumeration<URL> urlEnum = cLoader.getResources(lookupName);
        while (urlEnum.hasMoreElements()) {
            URL resourceURL = urlEnum.nextElement();
            InputStream is = null;
            try {
                is = resourceURL.openStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                // read each class and parse it
                String clazz;
                while ((clazz = reader.readLine()) != null) {
                    parseImplementor(clazz, cLoader, uniqueClasses);
                }
            } catch (IOException e) {
                logger.warn("Error while finding service file " + resourceURL + " for " + theInterface, e);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
    } catch (IOException e) {
        logger.warn("Error while finding service files for " + theInterface, e);
    }
    List<Class<T>> rtn = new ArrayList<Class<T>>();
    rtn.addAll(uniqueClasses);
    return rtn;
}

From source file:org.ajax4jsf.resource.ResourceBuilderImpl.java

/**
 * @throws FacesException//w ww  .  ja  v  a 2s .c o m
 */
protected void registerResources() throws FacesException {
    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> e = loader.getResources("META-INF/resources-config.xml");
        while (e.hasMoreElements()) {
            URL resource = e.nextElement();
            registerConfig(resource);
        }
    } catch (IOException e) {
        throw new FacesException(e);
    }
}

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

@Test
public void getResources_multiple_versions_with_parent_first_strategy() throws Exception {
    Map<String, ClassLoader> newClassloaders = sut.newClassloader("the-parent")
            .addURL("the-parent", new File("tester/a.jar").toURL())

            .newClassloader("the-child").addURL("the-child", new File("tester/a_v2.jar").toURL())
            .setParent("the-child", "the-parent", Mask.ALL).build();

    ClassLoader parent = newClassloaders.get("the-parent");
    assertThat(Collections.list(parent.getResources("a.txt"))).hasSize(1);

    ClassLoader child = newClassloaders.get("the-child");
    List<URL> childResources = Collections.list(child.getResources("a.txt"));
    assertThat(childResources).hasSize(2);
    assertThat(IOUtils.toString(childResources.get(0))).startsWith("version 1 of a.txt");
    assertThat(IOUtils.toString(childResources.get(1))).startsWith("version 2 of a.txt");
}

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

@Test
public void getResources_from_parent_and_siblings() throws Exception {
    Map<String, ClassLoader> newClassloaders = sut.newClassloader("the-parent")
            .addURL("the-parent", new File("tester/a.jar").toURL())

            .newClassloader("the-sib").addURL("the-sib", new File("tester/b.jar").toURL())

            .newClassloader("the-child").addURL("the-child", new File("tester/c.jar").toURL())
            .setParent("the-child", "the-parent", Mask.ALL).addSibling("the-child", "the-sib", Mask.ALL)
            .build();/*from   ww w  . ja  v a  2 s . c  o  m*/

    ClassLoader parent = newClassloaders.get("the-parent");
    assertThat(Collections.list(parent.getResources("a.txt"))).hasSize(1);
    assertThat(Collections.list(parent.getResources("b.txt"))).hasSize(0);
    assertThat(Collections.list(parent.getResources("c.txt"))).hasSize(0);

    ClassLoader child = newClassloaders.get("the-child");
    assertThat(Collections.list(child.getResources("a.txt"))).hasSize(1);
    assertThat(Collections.list(child.getResources("b.txt"))).hasSize(1);
    assertThat(Collections.list(child.getResources("c.txt"))).hasSize(1);
}

From source file:org.lpe.common.util.system.LpeSystemUtils.java

/**
 * Extracts files from a directory in the classpath to a temp directory and
 * returns the File instance of the destination directory.
 * /*from  ww w  .  j  a  v a  2s  .c om*/
 * @param srcDirName
 *            a directory name in the classpath
 * @param destName
 *            the name of the destination folder in the temp folder
 * @param fileType
 *            a string describing the file types, if a log message is needed
 * @param timeStamp
 *            if <code>true</code>, it will add a time stamp to the name of
 *            the target directory (recommended)
 * @param classloader
 *            classloader to use
 * 
 * @return the name of the target directory
 * 
 * @throws IOException
 *             ...
 * @throws URISyntaxException
 *             ...
 */
public static String extractFilesFromClasspath(String srcDirName, String destName, String fileType,
        ClassLoader classloader, boolean timeStamp) throws IOException, URISyntaxException {

    if (timeStamp) {
        // remove dots and colons from timestamp as they are not allowed for
        // windows directory names
        String clearedTimeStamp = (LpeStringUtils.getTimeStamp() + "-" + Thread.currentThread().getId())
                .replace('.', '_');

        clearedTimeStamp = clearedTimeStamp.replace(':', '_');
        clearedTimeStamp = clearedTimeStamp.replace(' ', '_');

        destName = destName + "_" + clearedTimeStamp;
    }
    final String targetDirName = LpeFileUtils.concatFileName(getSystemTempDir(), destName);

    // create a temp lib directory
    File targetDirFile = new File(targetDirName);
    if (!targetDirFile.exists()) {
        boolean ok = targetDirFile.mkdir();
        if (!ok) {
            logger.warn("Could not create directory {}", targetDirFile.getAbsolutePath());
        }
    }

    logger.debug("Copying {} to {}.", fileType, targetDirName);

    Enumeration<URL> urls = classloader.getResources(srcDirName); // getSystemResources(srcDirName);

    if (urls.hasMoreElements()) {
        logger.debug("There are some urls for resource '{}' provided by the classloader.", srcDirName);
    } else {
        logger.debug("There are no urls for resource '{}' provided by the classloader.", srcDirName);
    }

    while (urls.hasMoreElements()) {

        final URL url = urls.nextElement();

        if (fileType != null && fileType.trim().length() > 0) {
            logger.debug("Loading {} from {}...", fileType, url);
        }

        Iterator<File> libs = null;
        String unpackedJarDir = null;
        if (url.getProtocol().equals("bundleresource")) {
            continue;
        } else if (url.getProtocol().equals("jar")) {
            try {
                unpackedJarDir = LpeFileUtils.concatFileName(targetDirName, "temp");

                extractJARtoTemp(url, srcDirName, unpackedJarDir);

                final String unpackedNativeDir = LpeFileUtils.concatFileName(unpackedJarDir, srcDirName);
                final File unpackedNativeDirFile = new File(unpackedNativeDir);
                libs = FileUtils.iterateFiles(unpackedNativeDirFile, null, false);
            } catch (IllegalArgumentException iae) {
                // ignore
                LOGGER.warn("Jar not found, could not extract jar. {}", iae);

            }
        } else {
            // File nativeLibDir = new
            // File(url.toString().replaceAll("\\\\", "/"));
            File nativeLibDir = new File(url.toURI());
            libs = FileUtils.iterateFiles(nativeLibDir, null, false);
        }

        while (libs != null && libs.hasNext()) {
            final File libFile = libs.next();
            logger.debug("Copying resouce file {}...", libFile.getName());
            FileUtils.copyFileToDirectory(libFile, targetDirFile);
        }

        // clean up temp dir
        if (unpackedJarDir != null) {
            File dirToRemove = new File(unpackedJarDir);
            if (dirToRemove.isDirectory() && dirToRemove.exists()) {
                LpeFileUtils.removeDir(unpackedJarDir);
            }
        }

    }

    return targetDirName;
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

@Override
public Enumeration<URL> getResources(String name) throws IOException {
    final Enumeration<URL> localResources = findResources(name);
    final ClassLoader parent = getParent();
    // noinspection unchecked
    final Enumeration<URL> globalResources = parent != null ? parent.getResources(name)
            : asEnumeration(emptyIterator());
    return new Enumeration<URL>() {

        private boolean _local = true;

        @Override//  w ww . j a  va 2 s  .  c  o m
        public boolean hasMoreElements() {
            if (_local && !localResources.hasMoreElements()) {
                _local = false;
            }
            return _local ? localResources.hasMoreElements() : globalResources.hasMoreElements();
        }

        @Override
        public URL nextElement() {
            if (_local && localResources.nextElement() == null) {
                _local = false;
            }
            return _local ? localResources.nextElement() : globalResources.nextElement();
        }
    };
}

From source file:org.suren.autotest.web.framework.selenium.SeleniumEngine.java

/**
 * engine/*from  w  w  w. j  a  v  a  2s . c  o m*/
 * @param enginePro
 * @throws MalformedURLException 
 */
private void loadDefaultEnginePath(ClassLoader classLoader, Properties enginePro) throws MalformedURLException {
    Enumeration<URL> resurceUrls = null;
    URL defaultResourceUrl = null;
    try {
        resurceUrls = classLoader.getResources(ENGINE_CONFIG_FILE_NAME);
        defaultResourceUrl = classLoader.getResource(ENGINE_CONFIG_FILE_NAME);
    } catch (IOException e) {
        logger.error("Engine properties loading error.", e);
    }

    if (resurceUrls == null) {
        return;
    }

    //?jar
    while (resurceUrls.hasMoreElements()) {
        URL url = resurceUrls.nextElement();

        try {
            loadFromURL(enginePro, url);
        } catch (IOException e) {
            logger.error("loading engine error.", e);
        }
    }

    try {
        //?
        loadFromURL(enginePro, defaultResourceUrl);
    } catch (IOException e) {
        logger.error("loading engine error.", e);
    }

    loadDriverFromMapping(classLoader, enginePro);
}

From source file:com.liferay.portal.model.ExtletModelHintsImpl.java

public void afterPropertiesSet() {
    _hintCollections = new HashMap<String, Map<String, String>>();
    _defaultHints = new HashMap<String, Map<String, String>>();
    _modelFields = new HashMap<String, Object>();
    _models = new TreeSet<String>();

    try {/*from   w ww .  j a v  a  2s. c o m*/
        /*
         * LOAD THE ORIGINAL HINTS
         */
        ClassLoader classLoader = getClass().getClassLoader();

        String[] configs = StringUtil.split(PropsUtil.get(PropsKeys.MODEL_HINTS_CONFIGS));

        for (int i = 0; i < configs.length; i++) {
            read(classLoader, configs[i]);
        }

        /*
         * LOAD EXTLET MODEL EXTENSION
         */
        String resourceName = EXTLET_MODEL_RESOURCE_NAME;
        Enumeration<URL> resources = classLoader.getResources(resourceName);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            if (_log.isDebugEnabled()) {
                _log.debug("Loading extlet-model-hints.xml from: " + resource);
            }
            InputStream is = new UrlResource(resource).getInputStream();

            if (is != null) {
                read(classLoader, is);
            }
        }

    } catch (Exception e) {
        _log.error(e, e);
    }
}