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.axis2.classloader.MultiParentClassLoader.java

public Enumeration findResources(String name) throws IOException {
    if (isDestroyed()) {
        return Collections.enumeration(Collections.EMPTY_SET);
    }/*from  w w  w  .j  a v a2 s  . c o  m*/

    List resources = new ArrayList();

    //
    // if we are using inverse class loading, add the resources from local urls first
    //
    if (inverseClassLoading && !isDestroyed()) {
        List myResources = Collections.list(super.findResources(name));
        resources.addAll(myResources);
    }

    //
    // Add parent resources
    //
    for (int i = 0; i < parents.length; i++) {
        ClassLoader parent = parents[i];
        List parentResources = Collections.list(parent.getResources(name));
        resources.addAll(parentResources);
    }

    //
    // if we are not using inverse class loading, add the resources from local urls now
    //
    if (!inverseClassLoading && !isDestroyed()) {
        List myResources = Collections.list(super.findResources(name));
        resources.addAll(myResources);
    }

    return Collections.enumeration(resources);
}

From source file:com.krawler.portal.util.StringUtil.java

public static String read(ClassLoader classLoader, String name, boolean all) throws IOException {

    if (all) {//from   ww  w .j  av  a2s .c  o  m
        StringBuilder sb = new StringBuilder();

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

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

            InputStream is = url.openStream();

            String s = read(is);

            if (s != null) {
                sb.append(s);
                sb.append(StringPool.NEW_LINE);
            }

            is.close();
        }

        return sb.toString().trim();
    } else {
        InputStream is = classLoader.getResourceAsStream(name);

        String s = read(is);

        is.close();

        return s;
    }
}

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

/** 
 *   Initiaize the VariantManager. /*from   w  ww.j  av  a2s.c o m*/
 *   <p>
 *   An exception is thrown if no File paths are specified. A "." may be used
 *   to specify th ecurrent directory.
 *   <p>
 *   Loaded XML may be validated if the isValidating flag is set to true.
 *
 */
public static synchronized void init(final List<File> searchPaths, boolean isValidating)
        throws javax.xml.parsers.ParserConfigurationException, NoVariantsException {
    long ttime = System.currentTimeMillis();
    long vptime = ttime;
    Log.println("VariantManager.init()");

    if (searchPaths == null || searchPaths.isEmpty()) {
        throw new IllegalArgumentException();
    }

    if (vm != null) {
        // perform cleanup
        vm.variantMap.clear();
        vm.variants = new ArrayList<Variant>();
        vm.currentUCL = null;
        vm.currentPackageURL = null;

        vm.symbolPacks = new ArrayList<SymbolPack>();
        vm.symbolMap.clear();
    }

    vm = new VariantManager();

    // find plugins, create plugin loader
    final List<URL> pluginURLs = vm.searchForFiles(searchPaths, VARIANT_EXTENSIONS);

    // setup document builder
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        // this may improve performance, and really only apply to Xerces
        dbf.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
        dbf.setAttribute("http://apache.org/xml/properties/input-buffer-size", new Integer(4096));
        dbf.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
    } catch (Exception e) {
        Log.println("VM: Could not set XML feature.", e);
    }

    dbf.setValidating(isValidating);
    dbf.setCoalescing(false);
    dbf.setIgnoringComments(true);

    // setup variant parser
    XMLVariantParser variantParser = new XMLVariantParser(dbf);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL variantXMLURL = urlCL.findResource(VARIANT_FILE_NAME);
        if (variantXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(variantXMLURL.openStream());
                variantParser.parse(is, pluginURL);
                final List<Variant> variants = variantParser.getVariants();

                // add variants; variants with same name (but older versions) are
                // replaced with same-name newer versioned variants
                for (final Variant variant : variants) {
                    addVariant(variant, pluginName, pluginURL);
                }
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars
    Enumeration<URL> enum2 = null;
    ClassLoader cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(VARIANT_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL variantURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(variantURL);

                try {
                    is = new BufferedInputStream(variantURL.openStream());

                    variantParser.parse(is, variantURL);
                    final List<Variant> variants = variantParser.getVariants();

                    // add variants; variants with same name (but older versions) are
                    // replaced with same-name newer versioned variants
                    for (final Variant variant : variants) {
                        addVariant(variant, pluginName, variantURL);
                    }
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, variantURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    }

    // check: did we find *any* variants? Throw an exception.
    if (vm.variantMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No variants found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }

    Log.printTimed(vptime, "VariantManager: variant parsing time: ");

    ///////////////// SYMBOLS /////////////////////////

    // now, parse symbol packs
    XMLSymbolParser symbolParser = new XMLSymbolParser(dbf);

    // find plugins, create plugin loader
    final List<URL> pluginURLs2 = vm.searchForFiles(searchPaths, SYMBOL_EXTENSIONS);

    // for each plugin, attempt to find the "variants.xml" file inside. 
    // if it does not exist, we will not load the file. If it does, we will parse it,
    // and associate the variant with the URL in a hashtable.
    for (final URL pluginURL : pluginURLs2) {
        URLClassLoader urlCL = new URLClassLoader(new URL[] { pluginURL });
        URL symbolXMLURL = urlCL.findResource(SYMBOL_FILE_NAME);
        if (symbolXMLURL != null) {
            String pluginName = getFile(pluginURL);

            // parse variant description file, and create hash entry of variant object -> URL
            InputStream is = null;
            try {
                is = new BufferedInputStream(symbolXMLURL.openStream());
                symbolParser.parse(is, pluginURL);
                addSymbolPack(symbolParser.getSymbolPack(), pluginName, pluginURL);
            } catch (IOException e) {
                // display error dialog
                ErrorDialog.displayFileIO(null, e, pluginURL.toString());
            } catch (org.xml.sax.SAXException e) {
                // display error dialog
                ErrorDialog.displayGeneral(null, e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    // if we are in webstart, search for variants within webstart jars      
    enum2 = null;
    cl = null;

    if (vm.isInWebstart) {
        cl = vm.getClass().getClassLoader();

        try {
            enum2 = cl.getResources(SYMBOL_FILE_NAME);
        } catch (IOException e) {
            enum2 = null;
        }

        if (enum2 != null) {
            while (enum2.hasMoreElements()) {
                URL symbolURL = enum2.nextElement();

                // parse variant description file, and create hash entry of variant object -> URL
                InputStream is = null;
                String pluginName = getWSPluginName(symbolURL);

                try {
                    is = new BufferedInputStream(symbolURL.openStream());
                    symbolParser.parse(is, symbolURL);
                    addSymbolPack(symbolParser.getSymbolPack(), pluginName, symbolURL);
                } catch (IOException e) {
                    // display error dialog
                    ErrorDialog.displayFileIO(null, e, symbolURL.toString());
                } catch (org.xml.sax.SAXException e) {
                    // display error dialog
                    ErrorDialog.displayGeneral(null, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } // if(enum2 != null)
    } // if(isInWebStart)      

    // check: did we find *any* symbol packs? Throw an exception.
    if (vm.symbolMap.isEmpty()) {
        StringBuffer msg = new StringBuffer(256);
        msg.append("No SymbolPacks found on path: ");
        for (final File searchPath : searchPaths) {
            msg.append(searchPath);
            msg.append("; ");
        }

        throw new NoVariantsException(msg.toString());
    }
    Log.printTimed(ttime, "VariantManager: total parsing time: ");
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Scan a classloader for classes under the given package.
 * @param pkg package name/*from w ww. j  a v a 2s  .  c o m*/
 * @param loader classloader
 * @param lookInsideJars whether to consider classes inside jars or only "unpacked" class files
 * @return matching class names (will not attemp to actually load these classes)
 */
private Collection<String> scanClasspath(String pkg, ClassLoader loader, boolean lookInsideJars) {
    Collection<String> classes = Lists.newArrayList();

    Enumeration<URL> resources;
    String packageDir = pkg.replace(PACKAGE_SEPARATOR, JAR_PATH_SEPARATOR) + JAR_PATH_SEPARATOR;

    try {
        resources = loader.getResources(packageDir);
    } catch (IOException e) {
        s_log.warn("couldn't scan package", e);
        return classes;
    }

    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        String path = resource.getPath();
        s_log.debug("processing path {}", path);

        if (path.startsWith(FILE_URL_PREFIX)) {
            if (lookInsideJars) {
                String jarFilePath = StringUtils.substringBetween(path, FILE_URL_PREFIX,
                        NESTED_FILE_URL_SEPARATOR);
                try {
                    JarFile jarFile = new JarFile(jarFilePath);
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while (entries.hasMoreElements()) {
                        String entryName = entries.nextElement().getName();
                        if (entryName.startsWith(packageDir) && entryName.endsWith(CLASS_NAME_SUFFIX)) {
                            String potentialClassName = entryName.substring(packageDir.length(),
                                    entryName.length() - CLASS_NAME_SUFFIX.length());
                            if (!potentialClassName.contains(JAR_PATH_SEPARATOR)) {
                                classes.add(pkg + PACKAGE_SEPARATOR + potentialClassName);
                            }
                        }
                    }
                } catch (IOException e) {
                    s_log.warn("couldn't open jar file", e);
                }
            }
        } else {
            File dir = new File(path);
            if (dir.exists() && dir.isDirectory()) {
                String[] files = dir.list();
                for (String file : files) {
                    s_log.debug("file {}", file);
                    if (file.endsWith(CLASS_NAME_SUFFIX)) {
                        classes.add(pkg + PACKAGE_SEPARATOR + StringUtils.removeEnd(file, CLASS_NAME_SUFFIX));
                    }
                }
            }
        }
    }
    return classes;
}

From source file:org.pentaho.reporting.libraries.base.versioning.VersionHelper.java

/**
 * Loads the versioning information for the given project-information structure using the project information's
 * internal name as lookup key.//www  .  j a va  2 s .  c  o m
 *
 * @param projectInformation the project we load information for.
 */
public VersionHelper(final ProjectInformation projectInformation) {
    if (projectInformation == null) {
        throw new NullPointerException();
    }

    this.projectInformation = projectInformation;

    Manifest manifest = manifestCache.get(projectInformation.getInternalName());
    if (manifest == null) {
        final ClassLoader loader = projectInformation.getClass().getClassLoader();
        try {
            final Enumeration resources = loader.getResources("META-INF/MANIFEST.MF");
            while (resources.hasMoreElements()) {
                final URL url = (URL) resources.nextElement();
                final String urlAsText = url.toURI().toString();
                Manifest maybeManifest = manifestCache.getByURL(urlAsText);
                if (maybeManifest == null) {
                    final InputStream inputStream = url.openStream();
                    try {
                        maybeManifest = new Manifest(new BufferedInputStream(inputStream));
                    } finally {
                        inputStream.close();
                    }
                }

                final Attributes attr = getAttributes(maybeManifest, projectInformation.getInternalName());
                final String maybeTitle = getValue(attr, "Implementation-ProductID", null);
                if (maybeTitle != null) {
                    manifestCache.set(maybeTitle, urlAsText, maybeManifest);
                    if (maybeTitle.equals(projectInformation.getInternalName())) {
                        manifest = maybeManifest;
                        break;
                    }
                } else {
                    manifestCache.set(null, urlAsText, maybeManifest);
                }
            }

        } catch (Exception e) {
            // Ignore; Maybe log.
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to read manifest for retrieving library version information for "
                        + projectInformation.getProductId(), e);
            }
        }
    }
    if (manifest != null) {
        init(manifest);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to create version information for " + projectInformation.getInternalName());
        }
        version = "TRUNK.development";
        title = projectInformation.getInternalName();
        productId = projectInformation.getInternalName();
        releaseMajor = "999";
        releaseMinor = "999";
        releaseMilestone = "999";
        releasePatch = "0";
        releaseBuildNumber = SNAPSHOT_TOKEN;
        releaseNumber = createReleaseVersion();
    }
}

From source file:com.liferay.portal.spring.hibernate.PortalHibernateConfiguration.java

protected void readResource(Configuration configuration, String resource) throws Exception {

    ClassLoader classLoader = getConfigurationClassLoader();

    if (!resource.startsWith("classpath*:")) {
        InputStream is = classLoader.getResourceAsStream(resource);
        readResource(configuration, resource, is);
    } else {/* ww w. ja  v a2 s . c  o  m*/
        String resourceName = resource.substring("classpath*:".length());
        try {
            Enumeration<URL> resources = classLoader.getResources(resourceName);
            if (_log.isDebugEnabled() && !resources.hasMoreElements()) {
                _log.debug("No " + resourceName + " has been found");
            }
            while (resources.hasMoreElements()) {
                URL resourceFullName = resources.nextElement();
                try {
                    InputStream is = new UrlResource(resourceFullName).getInputStream();
                    readResource(configuration, resource, is);
                } catch (Exception e2) {
                    if (_log.isWarnEnabled()) {
                        _log.warn("Problem while loading " + resource, e2);
                    }
                }
            }
        } catch (Exception e2) {
            if (_log.isWarnEnabled()) {
                _log.warn("Problem while loading classLoader resources: " + resourceName, e2);
            }
        }
    }

}

From source file:org.apache.axis2.deployment.RepositoryListener.java

protected void loadClassPathModules() {
    ModuleDeployer deployer = deploymentEngine.getModuleDeployer();

    // Find Modules on the class path (i.e. if classpath includes "addressing.mar" then
    // addressing will be available for engaging)

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {/*  ww  w.j ava2 s.  c  o m*/
        Enumeration moduleURLs = loader.getResources("META-INF/module.xml");
        while (moduleURLs.hasMoreElements()) {
            try {
                URL url = (URL) moduleURLs.nextElement();
                URI moduleURI;
                if (url.getProtocol().equals("file")) {
                    String urlString = url.toString();
                    moduleURI = new URI(urlString.substring(0, urlString.lastIndexOf("/META-INF/module.xml")));
                } else {
                    // Check if the URL refers to an archive (such as
                    // jar:file:/dir/some.jar!/META-INF/module.xml) and extract the
                    // URL of the archive. In general the protocol will be "jar", but
                    // some containers may use other protocols, e.g. WebSphere uses
                    // "wsjar" (AXIS2-4258).
                    String path = url.getPath();
                    int idx = path.lastIndexOf("!/");
                    if (idx != -1 && path.substring(idx + 2).equals("META-INF/module.xml")) {
                        moduleURI = new URI(path.substring(0, idx).replaceAll(" ", "%20"));
                        if (!moduleURI.getScheme().equals("file")) {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }

                log.debug("Deploying module from classpath at '" + moduleURI + "'");
                File f = new File(moduleURI);
                addFileToDeploy(f, deployer, WSInfo.TYPE_MODULE);

            } catch (URISyntaxException e) {
                log.info(e);
            }
        }
    } catch (Exception e) {
        // Oh well, log the problem
        log.error("Error occurred while loading modules from classpath", e);
    }

    String classPath = getLocation();

    if (classPath == null)
        return;

    int lstindex = classPath.lastIndexOf(File.separatorChar);
    if (lstindex > 0) {
        classPath = classPath.substring(0, lstindex);
    } else {
        classPath = ".";
    }
    File root = new File(classPath);
    File[] files = root.listFiles();
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (!file.isDirectory()) {
                if (DeploymentFileData.isModuleArchiveFile(file.getName())) {
                    //adding modules in the class path
                    addFileToDeploy(file, deployer, WSInfo.TYPE_MODULE);
                }
            }
        }
    }

    ClassLoader cl = deploymentEngine.getAxisConfig().getModuleClassLoader();
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            URL[] urls = ((URLClassLoader) cl).getURLs();
            for (int i = 0; (urls != null) && i < urls.length; i++) {
                String path = urls[i].getPath();
                //If it is a drive letter, adjust accordingly.
                if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':') {
                    path = path.substring(1);
                }
                try {
                    path = URLDecoder.decode(path, Utils.defaultEncoding);
                } catch (UnsupportedEncodingException e) {
                    // Log this?
                }
                File file = new File(path.replace('/', File.separatorChar).replace('|', ':'));
                // If there is a security manager, then it is highly probable that it will deny
                // read access to some files in the class loader hierarchy. Therefore we first
                // check if the name matches that of a module archive and only then check if we
                // can access it. If the security manager denies access, we log a warning.
                if (DeploymentFileData.isModuleArchiveFile(file.getName())) {
                    boolean isFile;
                    try {
                        isFile = file.isFile();
                    } catch (SecurityException ex) {
                        log.warn("Not deploying " + file.getName() + " because security manager denies access",
                                ex);
                        isFile = false;
                    }
                    if (isFile) {
                        //adding modules in the class path
                        addFileToDeploy(file, deployer, WSInfo.TYPE_MODULE);
                    }
                }
            }
        }
        cl = cl.getParent();
    }

    deploymentEngine.doDeploy();
}

From source file:org.apache.myfaces.trinidadbuild.plugin.faces.AbstractFacesMojo.java

protected List getCompileDependencyResources(MavenProject project, String resourcePath)
        throws MojoExecutionException {
    try {/* w  w w  .  j  a v a  2 s.  c om*/
        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 MojoExecutionException("Unable to get resources for path " + "\"" + resourcePath + "\"", e);
    }

}

From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java

/**
 * First finds path to marker file url, otherwise throws {@link JarValidationException}.
 * Then scans jar classes according to list indicated in marker files.
 * Additional logic is added to close {@link URL} after {@link ConfigFactory#parseURL(URL)}.
 * This is extremely important for Windows users where system doesn't allow to delete file if it's being used.
 *
 * @param classLoader unique class loader for jar
 * @param path local path to jar/*w w w. ja va  2  s  . c om*/
 * @param urls urls associated with the jar (ex: binary and source)
 * @return scan result of packages, classes, annotations found in jar
 */
private ScanResult scan(ClassLoader classLoader, Path path, URL[] urls) throws IOException {
    Enumeration<URL> markerFileEnumeration = classLoader
            .getResources(CommonConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME);
    while (markerFileEnumeration.hasMoreElements()) {
        URL markerFile = markerFileEnumeration.nextElement();
        if (markerFile.getPath().contains(path.toUri().getPath())) {
            URLConnection markerFileConnection = null;
            try {
                markerFileConnection = markerFile.openConnection();
                DrillConfig drillConfig = DrillConfig.create(ConfigFactory.parseURL(markerFile));
                return RunTimeScan.dynamicPackageScan(drillConfig, Sets.newHashSet(urls));
            } finally {
                if (markerFileConnection instanceof JarURLConnection) {
                    ((JarURLConnection) markerFile.openConnection()).getJarFile().close();
                }
            }
        }
    }
    throw new JarValidationException(String.format("Marker file %s is missing in %s",
            CommonConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME, path.getName()));
}

From source file:org.apparatus_templi.Coordinator.java

/**
 * Scans all classes accessible from the context class loader which belong to the given package
 * and subpackages./* www.  j  a  v  a  2s  .com*/
 * 
 * @param packageName
 *            The base package
 * @return The classes
 * @throws ClassNotFoundException
 * @throws IOException
 */
@SuppressWarnings({ "unchecked", "unused" })
private static Class<org.apparatus_templi.driver.Driver>[] getClasses(String packageName)
        throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class<org.apparatus_templi.driver.Driver>> classes = new ArrayList<Class<org.apparatus_templi.driver.Driver>>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes.toArray(new Class[classes.size()]);
}