Example usage for java.lang ClassLoader getParent

List of usage examples for java.lang ClassLoader getParent

Introduction

In this page you can find the example usage for java.lang ClassLoader getParent.

Prototype

@CallerSensitive
public final ClassLoader getParent() 

Source Link

Document

Returns the parent class loader for delegation.

Usage

From source file:org.jbpm.jpdl.par.ResourceAction.java

public void execute(ExecutionContext executionContext) throws Exception {
    Assert.assertEquals("org.jbpm.jpdl.par", getClass().getPackage().getName());

    URL resource = getClass().getResource("classresource.txt");
    InputStream stream = resource.openStream();
    String classResourceUrl = read(stream);
    Assert.assertEquals("the class resource content", classResourceUrl);

    stream = getClass().getResourceAsStream("classresource.txt");
    String classResourceStream = read(stream);
    Assert.assertEquals("the class resource content", classResourceStream);

    ClassLoader resourceActionClassLoader = ResourceAction.class.getClassLoader();
    log.info("resource action classloader: " + getClass().getClassLoader());
    log.info("parent of resource action classloader: " + getClass().getClassLoader().getParent());
    resource = resourceActionClassLoader.getResource("org/jbpm/jpdl/par/classresource.txt");
    stream = resource.openStream();/*from ww  w.  ja  va2  s.c om*/
    String classLoaderResourceUrl = read(stream);
    Assert.assertEquals("the class resource content", classLoaderResourceUrl);

    stream = resourceActionClassLoader.getResourceAsStream("org/jbpm/jpdl/par/classresource.txt");
    String classLoaderResourceStream = read(stream);
    Assert.assertEquals("the class resource content", classLoaderResourceStream);

    resource = getClass().getResource("//archiveresource.txt");
    stream = resource.openStream();
    String archiveResourceUrl = read(stream);
    Assert.assertEquals("the archive resource content", archiveResourceUrl);

    stream = getClass().getResourceAsStream("//archiveresource.txt");
    String archiveResourceStream = read(stream);
    Assert.assertEquals("the archive resource content", archiveResourceStream);

    resource = resourceActionClassLoader.getResource("//archiveresource.txt");
    stream = resource.openStream();
    String archiveClassLoaderResourceUrl = read(stream);
    Assert.assertEquals("the archive resource content", archiveClassLoaderResourceUrl);

    stream = resourceActionClassLoader.getResourceAsStream("//archiveresource.txt");
    String archiveClassLoaderResourceStream = read(stream);
    Assert.assertEquals("the archive resource content", archiveClassLoaderResourceStream);

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    log.info("resource action context classloader: " + contextClassLoader);
    log.info("parent of resource action context classloader: " + contextClassLoader.getParent());
    resource = contextClassLoader.getResource("//archiveresource.txt");
    stream = resource.openStream();
    String contextClassLoaderResourceUrl = read(stream);
    Assert.assertEquals("the archive resource content", contextClassLoaderResourceUrl);

    stream = contextClassLoader.getResourceAsStream("//archiveresource.txt");
    String contextClassLoaderResourceStream = read(stream);
    Assert.assertEquals("the archive resource content", contextClassLoaderResourceStream);

    try {
        getClass().getResourceAsStream("unexistingresource.txt");
    } catch (RuntimeException e) {
        // ok
    }

    try {
        resourceActionClassLoader.getResourceAsStream("org/jbpm/jpdl/par/unexistingresource.txt");
    } catch (RuntimeException e) {
        // ok
    }

    try {
        getClass().getResourceAsStream("//unexistingarchiveresource.txt");
    } catch (RuntimeException e) {
        // ok
    }
    try {
        resourceActionClassLoader.getResourceAsStream("//unexistingarchiveresource.txt");
    } catch (RuntimeException e) {
        // ok
    }
}

From source file:org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.java

private static void cleanUpLoader(ClassLoader loader, Set<ClassLoader> encounteredLoaders,
        Set<Class<?>> encounteredClasses) throws Exception {
    if (!(loader instanceof GroovyClassLoader)) {
        return;//from w  w w. j  a  v a  2s.c  o  m
    }
    if (!encounteredLoaders.add(loader)) {
        return;
    }
    cleanUpLoader(loader.getParent(), encounteredLoaders, encounteredClasses);
    LOGGER.log(Level.FINER, "found {0}", String.valueOf(loader));
    SerializableClassRegistry.getInstance().release(loader);
    cleanUpGlobalClassValue(loader);
    GroovyClassLoader gcl = (GroovyClassLoader) loader;
    for (Class<?> clazz : gcl.getLoadedClasses()) {
        if (encounteredClasses.add(clazz)) {
            LOGGER.log(Level.FINER, "found {0}", clazz.getName());
            Introspector.flushFromCaches(clazz);
            cleanUpGlobalClassSet(clazz);
            cleanUpObjectStreamClassCaches(clazz);
            cleanUpLoader(clazz.getClassLoader(), encounteredLoaders, encounteredClasses);
        }
    }
    gcl.clearCache();
}

From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.java

/** This creates a java:comp/env/security context that contains a
 securityMgr binding pointing to an AuthenticationManager implementation
 and a realmMapping binding pointing to a RealmMapping implementation.
 *///from  ww w.j av  a  2 s. c o m
protected Context prepareENC() throws NamingException {

    if (logger.isDebugEnabled())
        logger.debug("JBossCatalinaRealm.prepareENC, Start");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    InitialContext iniCtx = new InitialContext();

    boolean securityContextExists = false;
    boolean isJaasSecurityManager = false;
    try {
        Context envCtx = (Context) iniCtx.lookup("java:comp/env");
        Context securityCtx = (Context) envCtx.lookup("security");
        securityContextExists = true;

        AuthenticationManager securityMgr = (AuthenticationManager) securityCtx.lookup("securityMgr");

        // If the Security Manager set in the web application ENC is not
        // a JaasSecurityManager, unbind the Security context and rebind it
        // with the JaasSecurityManager associated with the JOSSO Security Domain.
        // Note: the jboss-web.xml file of the partner application MUST not have an
        // entry referring to a security domain.
        if (!(securityMgr instanceof JaasSecurityManager)) {
            Util.unbind(envCtx, "security");
        } else
            isJaasSecurityManager = true;
    } catch (NamingException e) {
        // No Security Context found
    }

    // If we do not have a SecurityContext create it
    Context envCtx = null;
    if (!securityContextExists) {
        Thread currentThread = Thread.currentThread();
        if (logger.isDebugEnabled())
            logger.debug("Creating ENC using ClassLoader: " + loader);
        ClassLoader parent = loader.getParent();
        while (parent != null) {

            if (logger.isDebugEnabled())
                logger.debug(".." + parent);

            parent = parent.getParent();
        }

        envCtx = (Context) iniCtx.lookup("java:comp");
        envCtx = envCtx.createSubcontext("env");
    } else
        envCtx = (Context) iniCtx.lookup("java:comp/env");

    // If the Security Manager binded is not a JaasSecurityManager, rebind using
    // the Security Manager associated with the JOSSO Security Domain.
    if (!isJaasSecurityManager) {
        // Prepare the Security JNDI subcontext
        if (logger.isDebugEnabled())
            logger.debug("Linking security/securityMgr to JNDI name: " + JOSSO_SECURITY_DOMAIN);

        Util.bind(envCtx, "security/securityMgr", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/realmMapping", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/security-domain", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/subject", new LinkRef(JOSSO_SECURITY_DOMAIN + "/subject"));
    }

    if (logger.isDebugEnabled())
        logger.debug("JBossCatalinaRealm.prepareENC, End");

    return (Context) iniCtx.lookup("java:comp/env/security");
}

From source file:org.josso.jb32.agent.JBossCatalinaRealm.java

/** This creates a java:comp/env/security context that contains a
 securityMgr binding pointing to an AuthenticationManager implementation
 and a realmMapping binding pointing to a RealmMapping implementation.
 *///ww  w  .jav  a 2  s. com
protected Context prepareENC() throws NamingException {

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    InitialContext iniCtx = new InitialContext();

    boolean securityContextExists = false;
    boolean isJaasSecurityManager = false;
    try {
        Context envCtx = (Context) iniCtx.lookup("java:comp/env");
        Context securityCtx = (Context) envCtx.lookup("security");
        securityContextExists = true;

        AuthenticationManager securityMgr = (AuthenticationManager) securityCtx.lookup("securityMgr");

        // If the Security Manager set in the web application ENC is not
        // a JaasSecurityManager, unbind the Security context and rebind it
        // with the JaasSecurityManager associated with the JOSSO Security Domain.
        // Note: the jboss-web.xml file of the partner application MUST not have an
        // entry referring to a security domain.
        if (!(securityMgr instanceof JaasSecurityManager)) {
            Util.unbind(envCtx, "security");
        } else
            isJaasSecurityManager = true;
    } catch (NamingException e) {
        // No Security Context found
    }

    // If we do not have a SecurityContext create it
    Context envCtx = null;
    if (!securityContextExists) {
        Thread currentThread = Thread.currentThread();
        logger.debug("Creating ENC using ClassLoader: " + loader);
        ClassLoader parent = loader.getParent();
        while (parent != null) {
            logger.debug(".." + parent);
            parent = parent.getParent();
        }

        envCtx = (Context) iniCtx.lookup("java:comp");
        envCtx = envCtx.createSubcontext("env");
    } else
        envCtx = (Context) iniCtx.lookup("java:comp/env");

    // If the Security Manager binded is not a JaasSecurityManager, rebind using
    // the Security Manager associated with the JOSSO Security Domain.
    if (!isJaasSecurityManager) {
        // Prepare the Security JNDI subcontext
        logger.debug("Linking security/securityMgr to JNDI name: " + JOSSO_SECURITY_DOMAIN);
        Util.bind(envCtx, "security/securityMgr", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/realmMapping", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/security-domain", new LinkRef(JOSSO_SECURITY_DOMAIN));
        Util.bind(envCtx, "security/subject", new LinkRef(JOSSO_SECURITY_DOMAIN + "/subject"));
    }

    logger.debug("JBossCatalinaRealm.prepareENC, End");

    return (Context) iniCtx.lookup("java:comp/env/security");
}

From source file:org.kuali.coeus.sys.impl.KcConfigVerifier.java

/**
 * Checks if the Spring Instrumenting ClassLoader is in the ClassLoader chain. If so, this means
 * that it is properly configured.// www.ja va 2s  . c om
 */
protected boolean tomcatInstrumentingClassLoaderConfigured() {
    //generally this means that the tomcat context.xml file has tomcat ClassLoader configured.  If not then
    //something really strange is going on
    ClassLoader cl = this.getClass().getClassLoader();
    while (cl != null) {
        if (TOMCAT_INSTRUMENTATION_CLASS_LOADER_CLASS_NAME.equals(cl.getClass().getName())) {
            return true;
        }
        cl = cl.getParent();
    }
    return false;
}

From source file:org.kuali.kra.test.infrastructure.ApplicationServer.java

/**
 * The jetty server's jsp compiler does not have access to the classpath artifacts to compile the jsps.
 * This method takes the current webapp classloader and creates one containing all of the
 * classpath artifacts on the test's classpath.
 *
 * See http://stackoverflow.com/questions/17685330/how-do-you-get-embedded-jetty-9-to-successfully-resolve-the-jstl-uri
 *
 * @param current the current webapp classpath
 * @return a classloader to replace it with
 * @throws IOException if an error occurs creating the classloader
 *//*from w w  w  . ja  va  2s. co m*/
private static ClassLoader createClassLoaderForJasper(ClassLoader current) throws IOException {
    // Replace classloader with a new classloader with all URLs in manifests
    // from the parent loader bubbled up so Jasper looks at them.
    final ClassLoader parentLoader = current.getParent();
    if (current instanceof WebAppClassLoader && parentLoader instanceof URLClassLoader) {
        final LinkedList<URL> allURLs = new LinkedList<URL>(
                Arrays.asList(((URLClassLoader) parentLoader).getURLs()));

        for (URL url : ((LinkedList<URL>) allURLs.clone())) {
            try {
                final URLConnection conn = new URL("jar:" + url.toString() + "!/").openConnection();
                if (conn instanceof JarURLConnection) {
                    final JarURLConnection jconn = (JarURLConnection) conn;
                    final Manifest jarManifest = jconn.getManifest();
                    final String[] classPath = ((String) jarManifest.getMainAttributes().getValue("Class-Path"))
                            .split(" ");

                    for (String cpurl : classPath) {
                        allURLs.add(new URL(url, cpurl));
                    }
                }
            } catch (IOException | NullPointerException e) {
                //do nothing
            }
        }
        LOG.info("Creating new classloader for Application Server");
        return new WebAppClassLoader(new URLClassLoader(allURLs.toArray(new URL[] {}), parentLoader),
                ((WebAppClassLoader) current).getContext());
    }
    LOG.warn("Cannot create new classloader for app server " + current);
    return current;
}

From source file:org.kuali.rice.core.api.resourceloader.GlobalResourceLoader.java

private static synchronized ResourceLoader getResourceLoaderCheckParent(ClassLoader classLoader) {
    ResourceLoader resourceLoader = getResourceLoader(classLoader);

    if (resourceLoader != null && classLoader.getParent() != null) {
        ResourceLoader parentResourceLoader = getResourceLoaderCheckParent(classLoader.getParent());

        if (parentResourceLoader != null) {
            resourceLoader = new ParentChildResourceLoader(parentResourceLoader, resourceLoader);
        }//  ww w  . j  a v a  2 s  .c  om
    }

    if (resourceLoader == null && classLoader.getParent() != null) {
        resourceLoader = getResourceLoaderCheckParent(classLoader.getParent());
    }
    return resourceLoader;
}

From source file:org.lilyproject.runtime.classloading.ClassLoaderBuilder.java

public static synchronized ClassLoader build(List<ClasspathEntry> classpathEntries,
        ClassLoader parentClassLoader, ArtifactRepository repository)
        throws ArtifactNotFoundException, MalformedURLException {

    if (classLoaderCacheEnabled) {
        ///* w  w w  . ja  v a 2 s.  c o m*/
        // About the ClassLoader cache:
        //  The ClassLoader cache was introduced to handle leaks in the 'Perm Gen' and 'Code Cache'
        //  JVM memory spaces when repeatedly restarting Lily Runtime within the same JVM. In such cases,
        //  on each restart Lily Runtime would construct new class loaders, hence the classes loaded through
        //  them would be new and would stress those JVM memory spaces.
        //
        //  The solution here is good enough for what it is intended to do (restarting the same Lily Runtime
        //  app, unchanged, many times). There is no cache cleaning and the cache key calculation
        //  is not perfect, so if you would enable the cache when starting a wide variety of Lily Runtime
        //  apps within one VM or for reloading changed Lily Runtime apps, it could be problematic.
        //
        StringBuilder cacheKeyBuilder = new StringBuilder(2000);
        for (ClasspathEntry entry : classpathEntries) {
            cacheKeyBuilder.append(entry.getArtifactRef()).append("\u2603" /* unicode snowman as separator */);
        }

        // Add some identification of the parent class loader
        if (parentClassLoader instanceof URLClassLoader) {
            for (URL url : ((URLClassLoader) parentClassLoader).getURLs()) {
                cacheKeyBuilder.append(url.toString());
            }
        }

        String cacheKey = cacheKeyBuilder.toString();

        ClassLoader classLoader = classLoaderCache.get(cacheKey);
        if (classLoader == null) {
            Log log = LogFactory.getLog(ClassLoaderBuilder.class);
            log.debug("Creating and caching a new classloader");
            classLoader = create(classpathEntries, parentClassLoader, repository);
            classLoaderCache.put(cacheKey, classLoader);
        } else if (classLoader.getParent() != parentClassLoader) {
            Log log = LogFactory.getLog(ClassLoaderBuilder.class);
            log.error("Lily Runtime ClassLoader cache: parentClassLoader of cache ClassLoader is different"
                    + " from the specified one. Returning the cached one anyway.");
        }

        return classLoader;
    } else {
        return create(classpathEntries, parentClassLoader, repository);
    }
}

From source file:org.mortbay.jetty.webapp.WebAppContext.java

protected void doStart() throws Exception {
    try {/*from w w  w.j ava2 s.  com*/
        // Setup configurations 
        loadConfigurations();

        for (int i = 0; i < _configurations.length; i++)
            _configurations[i].setWebAppContext(this);

        // Configure classloader
        _ownClassLoader = false;
        if (getClassLoader() == null) {
            WebAppClassLoader classLoader = new WebAppClassLoader(this);
            setClassLoader(classLoader);
            _ownClassLoader = true;
        }

        if (Log.isDebugEnabled()) {
            ClassLoader loader = getClassLoader();
            Log.debug("Thread Context class loader is: " + loader);
            loader = loader.getParent();
            while (loader != null) {
                Log.debug("Parent class loader is: " + loader);
                loader = loader.getParent();
            }
        }

        for (int i = 0; i < _configurations.length; i++)
            _configurations[i].configureClassLoader();

        getTempDirectory();

        super.doStart();

        if (isLogUrlOnStart())
            dumpUrl();
    } catch (Exception e) {
        //start up of the webapp context failed, make sure it is not started
        Log.warn("Failed startup of context " + this, e);
        _unavailableException = e;
        _unavailable = true;
    }
}

From source file:org.mrgeo.utils.ClassLoaderUtil.java

public static void dumpClasspath(ClassLoader loader, int level) {
    System.out.println(indent(level) + "Classloader " + loader + ":");

    if (loader instanceof URLClassLoader) {
        URLClassLoader ucl = (URLClassLoader) loader;
        //System.out.println("\t" + Arrays.toString(ucl.getURLs()));

        URL[] urls = ucl.getURLs();
        String[] names = new String[urls.length];

        for (int i = 0; i < urls.length; i++) {
            //        String name = urls[i].toString();
            String name = FilenameUtils.getName(urls[i].toString());

            if (name.length() > 0) {
                names[i] = name;//from  ww w  . j  a va2s  .com
            } else {
                names[i] = urls[i].toString();
            }

        }
        Arrays.sort(names);

        for (String name : names) {
            System.out.println(indent(level + 1) + name);
        }
    } else
        System.out.println("\t(cannot display components as not a URLClassLoader)");

    System.out.println("");
    if (loader.getParent() != null) {
        dumpClasspath(loader.getParent(), level + 1);
    }

}