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.camel.impl.converter.AnnotationTypeConverterLoader.java

protected void findPackages(Set<String> packages, ClassLoader classLoader) throws IOException {
    Enumeration<URL> resources = classLoader.getResources(META_INF_SERVICES);
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        if (url != null && !visitedURLs.contains(url)) {
            // remember we have visited this url so we wont read it twice
            visitedURLs.add(url);//from   w  ww  . j  a  v a  2  s . com
            if (LOG.isDebugEnabled()) {
                LOG.info("Loading file " + META_INF_SERVICES + " to retrieve list of packages, from url: "
                        + url);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            try {
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    line = line.trim();
                    if (line.startsWith("#") || line.length() == 0) {
                        continue;
                    }
                    tokenize(packages, line);
                }
            } finally {
                IOHelper.close(reader, null, LOG);
            }
        }
    }
}

From source file:com.clican.pluto.orm.dynamic.impl.ClassLoaderUtilImpl.java

private void populateJarsFromManifest(Set<String> jars, ClassLoader loader) {
    BufferedReader reader = null;
    try {//ww w  . j  a v a  2 s  . c o  m
        Enumeration<URL> e = loader.getResources("META-INF/MANIFEST.MF");
        while (e.hasMoreElements()) {
            URL url = e.nextElement();
            if (url.getPath().contains(SURE_FIRE_BOOTER_JAR)) {
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String line = null;
                StringBuffer content = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    content.append(line.trim());
                }
                String cont = content.toString().replaceAll("Manifest-Version: 1.0Class-Path: ", "")
                        .replaceAll("Main-Class: org.apache.maven.surefire.booter.SurefireBooter", "");
                for (String file : cont.split(" ")) {
                    if (file.contains("file")) {
                        jars.add(file.replaceAll("file:", ""));
                    }
                }
                break;
            }
        }
    } catch (IOException e) {
        log.error("", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            log.error("", e);
        }

    }
}

From source file:org.pentaho.pac.server.util.ResolverUtil.java

public void findInPackage(String packageName, Test... tests) {
    packageName = packageName.replace('.', '/');
    ClassLoader loader = getClassLoader();
    Enumeration<URL> urls;
    try {/*  w ww .  java  2  s .c  o  m*/
        urls = loader.getResources(packageName);
    } catch (IOException ioe) {
        log.debug("Could not read package: " + packageName, ioe); //$NON-NLS-1$
        return;
    }
    while (urls.hasMoreElements()) {
        try {
            URL eurl = urls.nextElement();
            String urlPath = eurl.toURI().toString();

            if (urlPath.indexOf('!') > 0) {
                urlPath = urlPath.substring(0, urlPath.indexOf('!'));
                if (urlPath.startsWith("jar:")) //$NON-NLS-1$
                    urlPath = urlPath.substring(4);
                eurl = new URL(urlPath);
            }
            log.info("Scanning for classes in [" + urlPath //$NON-NLS-1$
                    + "] matching criteria: " + tests); //$NON-NLS-1$

            // is it a file?
            File file = new File(URLDecoder.decode(eurl.getFile(), "UTF-8")); //$NON-NLS-1$
            // File file = new File(eurl.getFile());
            if (file.exists() && file.isDirectory()) {
                loadImplementationsInDirectory(packageName, file, tests);
            } else {
                loadImplementationsInJar(packageName, eurl, tests);
            }
        } catch (IOException e) {
            log.debug("could not read entries", e); //$NON-NLS-1$
        } catch (URISyntaxException se) {
            log.debug("could not read entries", se); //$NON-NLS-1$
        }
    }
}

From source file:com.quinsoft.zeidon.standardoe.ApplicationList.java

/**
 * Loads the list of applications from %ZEIDON%/zeidon.app
 *///w  w w  .j a  va2s  .  co  m
ApplicationList(HomeDirectory home, ZeidonLogger logger) {
    logger.info("Loading application list");

    this.home = home;
    Map<String, ApplicationImpl> apps = new HashMap<String, ApplicationImpl>();

    // First try loading the resources.
    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader == null)
        classLoader = ClassLoader.getSystemClassLoader();

    try {
        for (Enumeration<URL> element = classLoader.getResources("zeidon.app"); element.hasMoreElements();) {
            URL url = element.nextElement();
            logger.info("Loading applications from resource %s", url.getFile());
            InputStream stream = url.openStream();
            ApplicationHandler appHandler = new ApplicationHandler(apps);
            PortableFileReader.ReadPortableFile(stream, logger, appHandler);
        }
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Error while attempting to load zeidon.app");
    }

    if (!StringUtils.isBlank(home.getHomeDirectory())) {
        String filename = FilenameUtils.concat(home.getHomeDirectory(), "zeidon.app");
        try {
            InputStream inputStream = JoeUtils.getInputStream(null, filename,
                    logger.getClass().getClassLoader());
            if (inputStream == null)
                logger.info("No zeidon.app found via ZEIDON_HOME.");
            else {
                logger.info("Loading apps using ZEIDON_HOME (%s)/zeidon.app", home.getHomeDirectory());
                ApplicationHandler appHandler = new ApplicationHandler(apps);
                PortableFileReader.ReadPortableFile(inputStream, logger, appHandler);
            }
        } catch (Exception e) {
            throw ZeidonException.wrapException(e).prependFilename(filename);
        }
    }

    if (apps.size() == 0)
        throw new ZeidonException("No resources named zeidon.app found.");

    applications = ImmutableMap.copyOf(apps);
}

From source file:org.echocat.jomon.runtime.i18n.RecursiveResourceBundleFactory.java

@Nullable
protected ResourceBundle loadBundles(@Nonnull String withName, @Nonnull ClassLoader from) {
    final List<ResourceBundle> bundles = new ArrayList<>();
    final Enumeration<URL> i;
    try {/*  w ww  .  j a v a2 s  . co m*/
        i = from.getResources(withName);
    } catch (final IOException e) {
        throw new RuntimeException(
                "Could not find all resourceBundles with name '" + withName + "' in " + from + ".", e);
    }
    while (i.hasMoreElements()) {
        final URL propertiesUrl = i.nextElement();
        try (final InputStream is = propertiesUrl.openStream()) {
            try (final Reader reader = new InputStreamReader(is, _charset)) {
                bundles.add(new PropertyResourceBundle(reader));
            }
        } catch (final IOException e) {
            throw new RuntimeException("Could not load resourceBundle from '" + propertiesUrl + "'.", e);
        }
    }
    return bundles.isEmpty() ? null : new CombinedResourceBundle(bundles);
}

From source file:dip.world.variant.VariantManager.java

/** 
 *   Get a resource for a variant. This uses the variantName to 
 *   deconflict, if multiple resources exist with the same name.
 *   <p>/*from ww  w.  j a  va 2 s.  c  om*/
 *   Conflict occur when plugins are loaded under the same ClassLoader,
 *   because variant plugin namespace is not unique.
 *   <p>
 *   This primarily applies to Webstart resources
 */
private static URL getWSResource(URL packURL, URI uri) {
    /*
    NOTE: this method is used by getResource(URL, URI), which is
    chiefly used by VariantManager and associated parsers; a VariantRecord
    has not yet been created. So we cannot use that; the internal
    logic here is slightly different.
     */
    assert (vm.isInWebstart);

    ClassLoader cl = vm.getClass().getClassLoader();
    String deconflictName = getWSPluginName(packURL);

    Enumeration<URL> enum2 = null;

    try {
        enum2 = cl.getResources(uri.toString());
    } catch (IOException e) {
        return null;
    }

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

        // deconflict. Note that this is not, and cannot be, foolproof;
        // due to name-mangling by webstart. For example, if two plugins
        // called "test" and "Supertest" exist, test may find the data
        // file within Supertest because indexOf(test, SuperTest) >= 0
        // 
        // however, if we can get the mangled name and set it as the
        // 'pluginName', we can be foolproof.
        //
        String lcPath = url.getPath();
        if (lcPath.indexOf(deconflictName) >= 0) {
            return url;
        }
    }

    return null;
}

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

protected void scanArtifactsManifests(Predicate<Pair<URL, Manifest>> manifestHandler) {
    ClassLoader loader = ExtendedClassUtils.getDefaultClassLoader(getClass());
    try {//from ww  w  .jav  a 2s  . c om
        for (Enumeration<URL> manifests = loader.getResources(JarFile.MANIFEST_NAME); (manifests != null)
                && manifests.hasMoreElements();) {
            URL url = manifests.nextElement();
            try {
                Manifest manifest = ManifestUtils.loadManifest(url);
                if (manifestHandler.evaluate(Pair.of(url, manifest))) {
                    logger.info("Scanning stopped by handler at URL=" + url.toExternalForm());
                    break;
                }
            } catch (Exception e) {
                logger.warn(e.getClass().getSimpleName() + " while handle URL=" + url.toExternalForm() + ": "
                        + e.getMessage());
            }
        }
    } catch (IOException e) {
        logger.warn("Failed (" + e.getClass().getSimpleName() + ") to get manifests URLs: " + e.getMessage());
    }
}

From source file:org.runway.utils.ServerBean.java

private String getDatabasePath(String dbname) {

    String dbpath = null;/*from www . j a  v  a 2  s  .c  om*/

    String dbscr = dbname + ".script";
    dbname = dbname + ".properties";

    // find the location of this file from classpath
    //ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
    ClassLoader sysClassLoader = ServerBean.class.getClassLoader();
    URL abspath = sysClassLoader.getResource(dbname);
    try {
        Enumeration<URL> scr = sysClassLoader.getResources(dbscr);

        for (; scr.hasMoreElements();) {
            URL u = scr.nextElement();
            System.out.println("uu " + u);
        }
    } catch (IOException e) {
        System.out.println("unable to find " + dbscr);
        e.printStackTrace();
    }

    //URL dd = getClass().getResource("target/classes/emarket.db.properties");

    if (abspath != null) {
        dbpath = abspath.toString();

        // then remove the .properties at the end
        if (dbpath.endsWith(".properties")) {
            dbpath = dbpath.replaceFirst(".properties", "");
        }
    } else {
        System.out.println("unable to find " + dbname);
        //throw new NullPointerException();
    }

    System.out.println("database : " + dbpath);

    return dbpath;
}

From source file:com.sachviet.bookman.server.util.ResolverUtil.java

public void findInPackage(String packageName, Test... tests) {
    packageName = packageName.replace('.', '/');
    final ClassLoader loader = getClassLoader();
    Enumeration<URL> urls;
    try {/*from w  w  w  .ja v a2s  .  c o m*/
        urls = loader.getResources(packageName);
    } catch (IOException ioe) {
        LOG.trace("Could not read package: " + packageName, ioe); //$NON-NLS-1$
        return;
    }
    while (urls.hasMoreElements()) {
        try {
            URL eurl = urls.nextElement();
            String urlPath = eurl.toURI().toString();

            if (urlPath.indexOf('!') > 0) {
                urlPath = urlPath.substring(0, urlPath.indexOf('!'));
                if (urlPath.startsWith("jar:")) { //$NON-NLS-1$
                    urlPath = urlPath.substring(4);
                }
                eurl = new URL(urlPath);
            }
            LOG.trace("Scanning for classes in [" + urlPath //$NON-NLS-1$
                    + "] matching criteria: " + tests); //$NON-NLS-1$

            // is it a file?
            final File file = new File(URLDecoder.decode(eurl.getFile(), "UTF-8")); //$NON-NLS-1$
            // File file = new File(eurl.getFile());
            if (file.exists() && file.isDirectory()) {
                loadImplementationsInDirectory(packageName, file, tests);
            } else {
                loadImplementationsInJar(packageName, eurl, tests);
            }
        } catch (IOException e) {
            LOG.trace("could not read entries", e); //$NON-NLS-1$
        } catch (URISyntaxException se) {
            LOG.trace("could not read entries", se); //$NON-NLS-1$
        }
    }
}

From source file:it.at.script.ConnectionScannerTest.java

public static String getRealPathOfResource(String resourceName) throws IOException {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final Enumeration<URL> resources = loader.getResources(resourceName);
    final String path = resources.nextElement().toString();
    final String replace = StringUtils.replace(path, "target/test-classes", "src/test/resources");
    return StringUtils.substringAfter(replace, "file:");
}