Example usage for java.net URLClassLoader getURLs

List of usage examples for java.net URLClassLoader getURLs

Introduction

In this page you can find the example usage for java.net URLClassLoader getURLs.

Prototype

public URL[] getURLs() 

Source Link

Document

Returns the search path of URLs for loading classes and resources.

Usage

From source file:org.apache.lens.server.session.TestDatabaseResourceService.java

private boolean isJarLoaded(ClassLoader loader, String db) throws Exception {
    URLClassLoader db1Loader = (URLClassLoader) loader;

    for (URL url : db1Loader.getURLs()) {
        String jarFile = url.getPath();
        if (jarFile.endsWith(db + ".jar")) {
            LOG.info("Found jar url " + url.toString());
            return true;
        }//  w w  w .j  ava 2 s  .  c o m
    }
    return false;
}

From source file:org.apache.nifi.spring.SpringContextProcessor.java

/**
 *
 *//*from www . j  a  v  a 2s  .  co  m*/
private static boolean isConfigResolvable(String configPath, File libDirPathFile) {
    List<URL> urls = new ArrayList<>();
    URLClassLoader parentLoader = (URLClassLoader) SpringContextProcessor.class.getClassLoader();
    urls.addAll(Arrays.asList(parentLoader.getURLs()));

    urls.addAll(SpringContextFactory.gatherAdditionalClassPathUrls(libDirPathFile.getAbsolutePath()));
    boolean resolvable = false;
    try (URLClassLoader throwawayCl = new URLClassLoader(urls.toArray(new URL[] {}), null)) {
        resolvable = throwawayCl.findResource(configPath) != null;
    } catch (IOException e) {
        // ignore since it can only happen on CL.close()
    }
    return resolvable;
}

From source file:org.apache.solr.core.SolrResourceLoader.java

private static URLClassLoader replaceClassLoader(final URLClassLoader oldLoader, final File base,
        final FileFilter filter) {
    if (null != base && base.canRead() && base.isDirectory()) {
        File[] files = base.listFiles(filter);

        if (null == files || 0 == files.length)
            return oldLoader;

        URL[] oldElements = oldLoader.getURLs();
        URL[] elements = new URL[oldElements.length + files.length];
        System.arraycopy(oldElements, 0, elements, 0, oldElements.length);

        for (int j = 0; j < files.length; j++) {
            try {
                URL element = files[j].toURI().normalize().toURL();
                log.info("Adding '" + element.toString() + "' to classloader");
                elements[oldElements.length + j] = element;
            } catch (MalformedURLException e) {
                SolrException.log(log, "Can't add element to classloader: " + files[j], e);
            }/*from   w  w  w.j av a  2s  .  c  o  m*/
        }
        ClassLoader oldParent = oldLoader.getParent();
        IOUtils.closeWhileHandlingException(oldLoader); // best effort
        return URLClassLoader.newInstance(elements, oldParent);
    }
    // are we still here?
    return oldLoader;
}

From source file:org.apache.zeppelin.interpreter.InterpreterFactory.java

private Interpreter createRepl(String dirName, String className, Properties property)
        throws InterpreterException {
    logger.info("Create repl {} from {}", className, dirName);

    ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
    try {/*ww w .ja  v  a 2s  .  c  o m*/

        URLClassLoader ccl = cleanCl.get(dirName);
        if (ccl == null) {
            // classloader fallback
            ccl = URLClassLoader.newInstance(new URL[] {}, oldcl);
        }

        boolean separateCL = true;
        try { // check if server's classloader has driver already.
            Class cls = this.getClass().forName(className);
            if (cls != null) {
                separateCL = false;
            }
        } catch (Exception e) {
            logger.error("exception checking server classloader driver", e);
        }

        URLClassLoader cl;

        if (separateCL == true) {
            cl = URLClassLoader.newInstance(new URL[] {}, ccl);
        } else {
            cl = ccl;
        }
        Thread.currentThread().setContextClassLoader(cl);

        Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className);
        Constructor<Interpreter> constructor = replClass.getConstructor(new Class[] { Properties.class });
        Interpreter repl = constructor.newInstance(property);
        repl.setClassloaderUrls(ccl.getURLs());
        LazyOpenInterpreter intp = new LazyOpenInterpreter(new ClassloaderInterpreter(repl, cl));
        return intp;
    } catch (SecurityException e) {
        throw new InterpreterException(e);
    } catch (NoSuchMethodException e) {
        throw new InterpreterException(e);
    } catch (IllegalArgumentException e) {
        throw new InterpreterException(e);
    } catch (InstantiationException e) {
        throw new InterpreterException(e);
    } catch (IllegalAccessException e) {
        throw new InterpreterException(e);
    } catch (InvocationTargetException e) {
        throw new InterpreterException(e);
    } catch (ClassNotFoundException e) {
        throw new InterpreterException(e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldcl);
    }
}

From source file:org.apache.zeppelin.spark.DepInterpreter.java

private List<File> classPath(ClassLoader cl) {
    List<File> paths = new LinkedList<>();
    if (cl == null) {
        return paths;
    }//  ww  w .j  a  v a 2 s.  c om

    if (cl instanceof URLClassLoader) {
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] urls = ucl.getURLs();
        if (urls != null) {
            for (URL url : urls) {
                paths.add(new File(url.getFile()));
            }
        }
    }
    return paths;
}

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*from w w  w  .  java  2s. c  o  m*/
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:org.ebayopensource.turmeric.plugins.maven.resources.ResourceLocator.java

private Location lookInClasspath(String pathref) throws MojoExecutionException {
    log.debug("Looking for resource in project classpath: " + pathref);

    if (log.isDebugEnabled()) {
        StringBuilder dbg = new StringBuilder();
        dbg.append("System.getProperty('java.class.path')=");

        String rawcp = System.getProperty("java.class.path");
        for (String cp : rawcp.split(File.pathSeparator)) {
            dbg.append("\n  ").append(cp);
        }//w  ww . j  a v  a2  s  . c o m

        log.debug(dbg.toString());

        ClassLoader cl = this.getClass().getClassLoader();
        if (cl instanceof URLClassLoader) {
            dbg = new StringBuilder();
            dbg.append("URLClassLoader(");
            dbg.append(cl.getClass().getName());
            dbg.append("):");

            URLClassLoader ucl = (URLClassLoader) cl;

            for (URL url : ucl.getURLs()) {
                dbg.append("\n  ").append(url.toExternalForm());
            }

            log.debug(dbg.toString());
        }
    }

    List<URL> resources = new ArrayList<URL>();
    try {
        Enumeration<URL> enurls = ClassLoader.getSystemResources(pathref);
        if (enurls != null) {
            while (enurls.hasMoreElements()) {
                URL url = enurls.nextElement();
                if (!resources.contains(url)) {
                    resources.add(url);
                }
            }
        }

        addFoundResource(resources, pathref, Thread.currentThread().getContextClassLoader());
        addFoundResource(resources, pathref, this.getClass().getClassLoader());
        if (resources.isEmpty()) {
            log.debug("NOT FOUND in project classpath");
            return null;
        }

        if (resources.size() > 1) {
            log.warn("Found more than 1 classpath entry for: " + pathref);
            for (URL url : resources) {
                log.warn(" + " + url.toExternalForm());
            }
        }

        URI uri = resources.get(0).toURI();
        log.debug("FOUND resource in project classpath: " + uri);
        return new Location(uri, project);
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Unable to process resource lookup in project classpath: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new MojoExecutionException(
                "Unable to process resource lookup in project classpath: " + e.getMessage(), e);
    }
}

From source file:org.ebayopensource.turmeric.tools.codegen.AbstractServiceGeneratorTestCase.java

private void dumpClassLoader(String indent, ClassLoader cl) {
    if (cl == null) {
        return;//w  w  w .  j  av  a  2s .  c om
    }
    System.out.printf("%sClassLoader: %s: %s%n", indent, cl.getClass().getName(), cl.toString());
    if (cl instanceof URLClassLoader) {
        URLClassLoader ucl = (URLClassLoader) cl;
        System.out.printf("%s(URLClassLoader)%n", indent);
        URL urls[] = ucl.getURLs();
        for (URL url : urls) {
            System.out.printf("%s* %s%n", indent, url);
        }
    }
    ClassLoader parent = cl.getParent();
    dumpClassLoader(indent + "  ", parent);
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.ClassPathUtil.java

private static void getClassPathFromClassLoader(LinkedList<File> classpath, ClassLoader classLoader) {
    if (classLoader == null) {
        return; // no classloader
    }/*  w  ww .  ja  va2  s .  com*/

    if (!(classLoader instanceof URLClassLoader)) {
        // unable to get anything from this classloader.
        // Try parent instead.
        getClassPathFromClassLoader(classpath, classLoader.getParent());
        return;
    }

    URLClassLoader ucl = (URLClassLoader) classLoader;

    URL[] urls = null;
    if (ucl instanceof CodeGenClassLoader) {
        CodeGenClassLoader cgcl = (CodeGenClassLoader) ucl;
        urls = cgcl.getAllURLs();
    } else {
        urls = ucl.getURLs();
    }

    // Add the urls
    File file;
    String path;
    for (URL url : urls) {
        // Normalize the path
        try {
            file = new File(url.toURI());
        } catch (URISyntaxException e) {
            LOG.warning("Unable to identify file from invalid URI: " + url.toExternalForm());
            path = url.toExternalForm();
            if (path.startsWith("file:")) {
                path = path.substring("file:".length());
                path = FilenameUtils.normalize(path);
            }
            file = new File(path);
        }
        addFilePath(classpath, file);
    }

    getClassPathFromClassLoader(classpath, classLoader.getParent());
    dumpStats();
}

From source file:org.eclipse.emf.mwe.utils.StandaloneSetup.java

public void setScanClassPath(boolean doScan) {
    if (!doScan)//from w ww . j av a2s  .c  om
        return;
    String property = System.getProperty("java.class.path");
    String separator = System.getProperty("path.separator");
    Set<File> scanned = new HashSet<File>();
    if (property != null) {
        String[] entries = property.split(separator);
        for (String entry : entries) {
            File file = new File(entry);
            scanned.add(file);
            doRegisterResourceMapping(file);
        }
    }
    ClassLoader classLoader = getClass().getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        @SuppressWarnings("resource")
        URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
        URL[] urLs = urlClassLoader.getURLs();
        for (URL url : urLs) {
            File file;
            try {
                file = new File(url.toURI());
                if (scanned.add(file))
                    doRegisterResourceMapping(file);
            } catch (URISyntaxException e) {
                log.debug("Couldn't convert url '" + url + "' to a file : " + e.getMessage());
            }
        }
    }
}