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.mule.tools.schemadocs.SchemaDocsMain.java

protected List listSchema2() throws IOException {
    ClassLoader loader = getClass().getClassLoader();
    List files = new LinkedList();
    Enumeration resources = loader.getResources("META-INF");
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            if (name.startsWith(MULE) && name.endsWith(XSD)) {
                for (int i = 0; i < BLOCKED.length; ++i) {
                    if (name.indexOf(BLOCKED[i]) > -1) {
                        return false;
                    }//from ww  w.  j ava2  s .  c  o m
                }
                return true;
            } else {
                return false;
            }
        }
    };
    while (resources.hasMoreElements()) {
        URL url = (URL) resources.nextElement();
        logger.debug("url: " + url);
        if (url.toString().startsWith("jar:")) {
            readFromJar(url, files);
        } else if ("file".equals(url.getProtocol())) {
            readFromDirectory(new File(url.getFile()), files, filter);
        }
    }
    return files;
}

From source file:com.cyclopsgroup.tornado.impl.hibernate.DefaultHibernateService.java

/**
 * Override method DefaultHibernateFactory in supper class
 *
 * @see org.apache.avalon.framework.activity.Initializable#initialize()
 *///from  w  w w .j  av a  2s  .  c om
public void initialize() throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enu = cl.getResources("META-INF/cyclopsgroup/hibernate." + getName() + ".cfg.xml");

    hibernateConfiguration = new org.hibernate.cfg.Configuration();
    hibernateConfiguration.setProperties(hibernateProperties);

    while (enu.hasMoreElements()) {
        URL resource = enu.nextElement();
        getLogger().info("Configure hibernate service [" + name + "] with " + resource);
        hibernateConfiguration.configure(resource);
    }

    sessionFactory = hibernateConfiguration.buildSessionFactory();

    if (StringUtils.isNotEmpty(dataSourceServiceRole)) {
        dataSourceService = (DataSourceService) serviceManager.lookup(dataSourceServiceRole);
    }
}

From source file:org.massyframework.modules.launching.DefaultAssemblyResourceLoader.java

@Override
public List<AssemblyResource> getAssemblyResources() throws Exception {
    List<AssemblyResource> result = new ArrayList<AssemblyResource>();
    for (Entry<ModuleIdentifier, List<String>> entry : this.assemblyResources.entrySet()) {
        ModuleIdentifier identifier = entry.getKey();
        List<String> resources = entry.getValue();

        Module module = this.moduleLoader.loadModule(identifier);
        ClassLoader loader = module.getClassLoader();

        if (resources == null) {
            Enumeration<URL> em = loader.getResources(DEFAULT_RESOURCE);
            while (em.hasMoreElements()) {
                URL url = em.nextElement();
                AssemblyResource resource = new DefaultAssemblyResource(loader, url);
                result.add(resource);//  w  w w . j a va2s  .c o  m
            }
        } else {
            for (String resource : resources) {
                AssemblyResource assemblyResource = this.createAssemblyResource(loader, resource);
                if (assemblyResource == null) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("cannot found assembly resource: module=" + identifier.toString()
                                + ", path=" + resource + ".");
                        ;
                    }
                } else {
                    result.add(assemblyResource);
                }
            }
        }
    }
    return result;
}

From source file:com.chinamobile.bcbsp.util.BSPJob.java

/**
 * Find the BC-BSP application jar of the job.
 * @param myClass/*w  ww .java2 s  .co m*/
 *        The BC-BSP application jarFileClass of the job.
 * @return The name of the jar.
 */
private static String findContainingJar(Class<?> myClass) {
    ClassLoader loader = myClass.getClassLoader();
    String classFile = myClass.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            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) {
        LOG.error("[findContainingJar]", e);
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.ops4j.gaderian.impl.XmlModuleDescriptorProvider.java

private List<Resource> getDescriptorResources(String resourcePath, ClassResolver resolver) {
    if (LOG.isDebugEnabled())
        LOG.debug("Processing modules visible to " + resolver);

    // Use a set to ensure unique resources being loaded - GAD-32
    Set<Resource> descriptors = new HashSet<Resource>();

    ClassLoader loader = resolver.getClassLoader();
    Enumeration<URL> e = null;

    try {//  ww  w .j a va2s.c o m
        e = loader.getResources(resourcePath);
    } catch (IOException ex) {
        throw new ApplicationRuntimeException(ImplMessages.unableToFindModules(resolver, ex), ex);
    }

    while (e.hasMoreElements()) {
        URL descriptorURL = e.nextElement();

        if (!descriptors.add(new URLResource(descriptorURL))) {
            LOG.warn("Class loader duplicated resource detected at '" + descriptorURL.toString()
                    + "', will ignoring it (see GAD-32)");
        }

    }

    // Convert the set to the list that the API is expecting
    return new ArrayList<Resource>(descriptors);
}

From source file:com.adito.boot.AbstractXMLDefinedPropertyClass.java

void loadPropertyCategoryDefinitionsFromResources(ClassLoader classloader) throws IOException, JDOMException {
    SAXBuilder build = new SAXBuilder();
    if (classloader == null) {
        classloader = getClass().getClassLoader();
    }/* w w w. ja v a 2s.com*/
    for (Enumeration<URL> e = classloader.getResources("META-INF/" + getName() + "-categories.xml"); e
            .hasMoreElements();) {
        URL u = e.nextElement();
        log.info("Loading categories for class " + getName() + " from " + u);
        Element root = build.build(u).getRootElement();
        if (!root.getName().equals("categories")) {
            throw new JDOMException("Root element in " + u + " should be <categories>");
        }
        for (Iterator i = root.getChildren().iterator(); i.hasNext();) {
            Element c = (Element) i.next();
            if (c.getName().equals("category")) {
                addCategories(c, null);
            } else {
                throw new JDOMException(
                        "Expect root element of <categories> with child elements of <category>. Got <"
                                + c.getName() + ">.");
            }
        }
    }
}

From source file:com.atlassw.tools.eclipse.checkstyle.builder.PackageNamesLoader.java

/**
 * Returns the default list of package names.
 * /*w  w  w .j  av  a  2s .  co  m*/
 * @param aClassLoader the class loader that gets the default package names.
 * @return the default list of package names.
 * @throws CheckstylePluginException if an error occurs.
 */
public static List<String> getPackageNames(ClassLoader aClassLoader) throws CheckstylePluginException {

    if (sPackages == null) {
        sPackages = new ArrayList<String>();

        PackageNamesLoader nameLoader = null;

        try {
            nameLoader = new PackageNamesLoader();
            final InputStream stream = aClassLoader.getResourceAsStream(DEFAULT_PACKAGES);
            InputSource source = new InputSource(stream);
            nameLoader.parseInputSource(source);
        } catch (ParserConfigurationException e) {
            CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES); //$NON-NLS-1$
        } catch (SAXException e) {
            CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES + " - " //$NON-NLS-1$ //$NON-NLS-2$
                    + e.getMessage());
        } catch (IOException e) {
            CheckstylePluginException.rethrow(e, "unable to read " + DEFAULT_PACKAGES); //$NON-NLS-1$
        }

        // load custom package files
        try {
            Enumeration<URL> packageFiles = aClassLoader.getResources("checkstyle_packages.xml"); //$NON-NLS-1$

            while (packageFiles.hasMoreElements()) {

                URL aPackageFile = packageFiles.nextElement();
                InputStream iStream = null;

                try {

                    iStream = new BufferedInputStream(aPackageFile.openStream());
                    InputSource source = new InputSource(iStream);
                    nameLoader.parseInputSource(source);
                } catch (SAXException e) {
                    LimyEclipsePluginUtils.log(e);
                    //                        CheckstyleLog.log(e, "unable to parse " + aPackageFile.toExternalForm() //$NON-NLS-1$
                    //                                + " - " + e.getLocalizedMessage()); //$NON-NLS-1$
                } catch (IOException e) {
                    LimyEclipsePluginUtils.log(e);
                    //                        CheckstyleLog.log(e, "unable to read " + aPackageFile.toExternalForm()); //$NON-NLS-1$
                } finally {
                    IOUtils.closeQuietly(iStream);
                }
            }
        } catch (IOException e1) {
            CheckstylePluginException.rethrow(e1);
        }
    }

    return sPackages;
}

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   w  ww.java  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(MapRecObj mro, URI uri) {
    assert (vm.isInWebstart);

    if (uri == null) {
        return null;
    }

    ClassLoader cl = vm.getClass().getClassLoader();

    if (mro != null) {
        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();
            String search = mro.getPluginName() + "!";

            if (lcPath.indexOf(search) >= 0) {
                return url;
            }
        }
    }

    return null;
}

From source file:org.rhq.enterprise.server.plugin.pc.ServerPluginValidatorUtil.java

private List<URL> findPluginJars() throws Exception {
    List<URL> retUrls = new ArrayList<URL>();

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> descriptorUrls = classloader.getResources(PLUGIN_DESCRIPTOR_PATH);
    while (descriptorUrls.hasMoreElements()) {
        URL descriptorUrl = descriptorUrls.nextElement();
        URLConnection connection = descriptorUrl.openConnection();
        if (connection instanceof JarURLConnection) {
            URL jarUrl = ((JarURLConnection) connection).getJarFileURL();
            retUrls.add(jarUrl);//from  ww w.j ava 2s.  c o  m
            LOG.info("Found plugin jar: " + jarUrl);
        } else {
            LOG.warn("Found a plugin descriptor outside of a jar, skipping: " + descriptorUrl);
        }
    }

    return retUrls;
}

From source file:org.apache.bval.jsr.DefaultValidationProviderResolver.java

/**
 * {@inheritDoc}/*from www.j a  va  2  s . com*/
 */
public List<ValidationProvider<?>> getValidationProviders() {
    List<ValidationProvider<?>> providers = new ArrayList<ValidationProvider<?>>();
    try {
        // get our classloader
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = DefaultValidationProviderResolver.class.getClassLoader();
        // find all service provider cfgs
        Enumeration<URL> cfgs = cl.getResources(SPI_CFG);
        while (cfgs.hasMoreElements()) {
            final URL url = cfgs.nextElement();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(url.openStream()), 256);
                String line = br.readLine();
                // cfgs may contain multiple providers and/or comments
                while (line != null) {
                    line = line.trim();
                    if (!line.startsWith("#")) {
                        try {
                            // try loading the specified class
                            @SuppressWarnings("rawtypes")
                            final Class<? extends ValidationProvider> providerType = cl.loadClass(line)
                                    .asSubclass(ValidationProvider.class);
                            // create an instance to return
                            providers.add(
                                    Reflection.newInstance(providerType.asSubclass(ValidationProvider.class)));

                        } catch (ClassNotFoundException e) {
                            throw new ValidationException(
                                    "Failed to load provider " + line + " configured in file " + url, e);
                        }
                    }
                    line = br.readLine();
                }
            } catch (IOException e) {
                throw new ValidationException("Error trying to read " + url, e);
            } finally {
                if (br != null) {
                    br.close();
                }
            }
        }
    } catch (IOException e) {
        throw new ValidationException("Error trying to read a " + SPI_CFG, e);
    }
    // caller must handle the case of no providers found
    return providers;
}