Example usage for java.net URLClassLoader getParent

List of usage examples for java.net URLClassLoader getParent

Introduction

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

Prototype

@CallerSensitive
public final ClassLoader getParent() 

Source Link

Document

Returns the parent class loader for delegation.

Usage

From source file:com.tacitknowledge.util.discovery.ClasspathUtils.java

/**
 * Returns the classpath as a list directory and archive names.
 *
 * @return the classpath as a list of directory and archive file names; if
 *         no components can be found then an empty list will be returned
 *///from   w  w w .  j  a v a  2 s.co  m
public static List getClasspathComponents() {
    List components = new LinkedList();

    // walk the classloader hierarchy, trying to get all the components we can
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    while ((null != cl) && (cl instanceof URLClassLoader)) {
        URLClassLoader ucl = (URLClassLoader) cl;
        components.addAll(getUrlClassLoaderClasspathComponents(ucl));

        try {
            cl = ucl.getParent();
        } catch (SecurityException se) {
            cl = null;
        }
    }

    // walking the hierarchy doesn't guarantee we get everything, so
    // lets grab the system classpath for good measure.
    String classpath = System.getProperty("java.class.path");
    String separator = System.getProperty("path.separator");
    StringTokenizer st = new StringTokenizer(classpath, separator);
    while (st.hasMoreTokens()) {
        String component = st.nextToken();
        // Calling File.getPath() cleans up the path so that it's using
        // the proper path separators for the host OS
        component = getCanonicalPath(component);
        components.add(component);
    }

    // Set removes any duplicates, return a list for the api.
    return new LinkedList(new HashSet(components));
}

From source file:com.googlecode.fightinglayoutbugs.FindBugsRunner.java

private static List<String> getClassPath(Class<?> suiteClass) {
    List<String> classPath = new ArrayList<String>();
    URLClassLoader classLoader = (URLClassLoader) suiteClass.getClassLoader();
    do {//from w w w  .j  av a2  s  .  c  o m
        for (URL url : classLoader.getURLs()) {
            final String temp = url.toString();
            if (temp.startsWith("file:")) {
                @SuppressWarnings("deprecation")
                String path = URLDecoder.decode(temp.substring("file:".length()));
                classPath.add(path);
            } else {
                throw new RuntimeException(
                        "Don't know how to convert class path URL '" + temp + "' into a path.");
            }
        }
        ClassLoader parentClassLoader = classLoader.getParent();
        classLoader = (parentClassLoader instanceof URLClassLoader && parentClassLoader != classLoader
                ? (URLClassLoader) parentClassLoader
                : null);
    } while (classLoader != null);
    return classPath;
}

From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java

private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException {
    /** Compilation Requirements *********************************************************************************************/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within
    // in it...//from   www  . jav  a2 s .c  o m
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(getAllJarsClassPathInMavenLocalRepo());
    optionList.add("-verbose");

    File helloWorldJava = new File(classFilePathName);

    Iterable<? extends JavaFileObject> compilationUnit = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));
    JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null,
            compilationUnit);

    /********************************************************************************************* Compilation Requirements **/
    if (task.call()) {
        /** Load and execute *************************************************************************************************/
        // Create a new custom class loader, pointing to the directory that
        // contains the compiled
        // classes, this should point to the top of the package structure!
        //TODO the / separator needs to be revised to platform awared 
        URLClassLoader classLoader = new URLClassLoader(new URL[] {
                new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() },
                Thread.currentThread().getContextClassLoader());
        String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/";
        ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent());
        classLoader.loadClass(className);
        classLoader.close();
        /************************************************************************************************* Load and execute **/
    } else {
        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
            System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(),
                    diagnostic.getSource(), diagnostic.getMessage(new Locale("en")));
        }
    }
}

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  a va  2 s  . 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.springframework.cloud.dataflow.app.utils.ClassloaderUtils.java

/**
 * Creates a ClassLoader for the launched modules by merging the URLs supplied as argument with the URLs that
 * make up the additional classpath of the launched JVM (retrieved from the application classloader), and
 * setting the extension classloader of the JVM as parent, if accessible.
 *
 * @param urls a list of library URLs/*w  w  w.  j  a  v a 2  s  .  com*/
 * @return the resulting classloader
 */
public static ClassLoader createModuleClassloader(URL[] urls) {
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
    if (log.isDebugEnabled()) {
        log.debug("systemClassLoader is " + systemClassLoader);
    }
    if (systemClassLoader instanceof URLClassLoader) {
        // add the URLs of the application classloader to the created classloader
        // to compensate for LaunchedURLClassLoader not delegating to parent to retrieve resources
        @SuppressWarnings("resource")
        URLClassLoader systemUrlClassLoader = (URLClassLoader) systemClassLoader;
        URL[] mergedUrls = new URL[urls.length + systemUrlClassLoader.getURLs().length];
        if (log.isDebugEnabled()) {
            log.debug("Original URLs: " + StringUtils.arrayToCommaDelimitedString(urls));
            log.debug("Java Classpath URLs: "
                    + StringUtils.arrayToCommaDelimitedString(systemUrlClassLoader.getURLs()));
        }
        System.arraycopy(urls, 0, mergedUrls, 0, urls.length);
        System.arraycopy(systemUrlClassLoader.getURLs(), 0, mergedUrls, urls.length,
                systemUrlClassLoader.getURLs().length);
        // add the extension classloader as parent to the created context, if accessible
        if (log.isDebugEnabled()) {
            log.debug("Classloader URLs: " + StringUtils.arrayToCommaDelimitedString(mergedUrls));
        }
        return new LaunchedURLClassLoader(mergedUrls, systemUrlClassLoader.getParent());
    }
    return new LaunchedURLClassLoader(urls, systemClassLoader);
}

From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java

/**
 * Get the list of jars that this spark module requires.
 *
 * @return the list of spark application jars
 *//*w  w w . ja  v  a2 s. c  o  m*/
private List<String> getApplicationJars(Module module) {
    // Get jars from module classpath
    URLClassLoader classLoader = (URLClassLoader) ((SimpleModule) module).getClassLoader();
    List<String> jars = new ArrayList<String>();
    for (URL url : classLoader.getURLs()) {
        String file = url.getFile().split("\\!", 2)[0];
        if (file.endsWith(".jar")) {
            jars.add(file);
        }
    }
    // Get message bus libraries
    Environment env = this.getApplicationContext().getEnvironment();
    String jarsLocation = env.resolvePlaceholders(MessageBusClassLoaderFactory.MESSAGE_BUS_JARS_LOCATION);
    try {
        Resource[] resources = resolver.getResources(jarsLocation);
        for (Resource resource : resources) {
            URL url = resource.getURL();
            jars.add(url.getFile());
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    // Get necessary dependencies from XD DIRT.
    URLClassLoader parentClassLoader = (URLClassLoader) classLoader.getParent();
    URL[] urls = parentClassLoader.getURLs();
    for (URL url : urls) {
        String file = FilenameUtils.getName(url.getFile());
        String fileToAdd = url.getFile().split("\\!", 2)[0];
        if (file.endsWith(".jar") && (// Add spark jars
        file.contains("spark") ||
        // Add SpringXD dependencies
                file.contains("spring-xd-") ||
                // Add Spring dependencies
                file.contains("spring-core") || file.contains("spring-integration-core")
                || file.contains("spring-beans") || file.contains("spring-context")
                || file.contains("spring-boot") || file.contains("spring-aop")
                || file.contains("spring-expression") || file.contains("spring-messaging")
                || file.contains("spring-retry") || file.contains("spring-tx")
                || file.contains("spring-data-commons") || file.contains("spring-data-redis")
                || file.contains("commons-pool") || file.contains("jedis") ||
                // Add codec dependency
                file.contains("kryo") || file.contains("gs-collections"))) {
            jars.add(fileToAdd);
        }
    }
    return jars;
}