Example usage for java.lang Thread getContextClassLoader

List of usage examples for java.lang Thread getContextClassLoader

Introduction

In this page you can find the example usage for java.lang Thread getContextClassLoader.

Prototype

@CallerSensitive
public ClassLoader getContextClassLoader() 

Source Link

Document

Returns the context ClassLoader for this thread.

Usage

From source file:com.liferay.maven.arquillian.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.
    SecurityManager securityManager = new SecurityManager() {

        @Override/*from w w w  .j  av a2s .  co m*/
        public void checkPermission(Permission permission) {
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:com.freetmp.common.util.ClassUtils.java

public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
        currentThread.setContextClassLoader(classLoaderToUse);
        return threadContextClassLoader;
    } else {/*from  w  w w . j a  va 2s. c om*/
        return null;
    }
}

From source file:com.liferay.arquillian.maven.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        @Override/* w  ww  . j  a  v  a  2  s  . co  m*/
        public void checkPermission(Permission permission) {
            //It is not needed to check permissions
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

private void releaseFromThreads(WeakReference<ClassLoader> classLoader) {
    final List<Thread> threads = new ArrayList<Thread>(Thread.getAllStackTraces().keySet());

    for (Thread thread : threads) {
        if (Objects.equals(classLoader.get(), thread.getContextClassLoader())) {
            thread.setContextClassLoader(null);
        }/*from  w  w w  . j  av a  2s  .  c  o m*/
    }
}

From source file:org.whitesource.bamboo.plugins.AgentTask.java

private void reportCheckPoliciesResult(CheckPoliciesResult result, final BuildContext buildContext,
        final File buildDirectory, BuildLogger buildLogger) throws IOException {
    PolicyCheckReport report = new PolicyCheckReport(result, buildContext.getProjectName(),
            buildContext.getBuildResultKey());
    /*// w  ww  .  j ava2s  .  c  o  m
     * NOTE: if used as is, report.generate() yields an exception 'Velocity is not initialized correctly' due to a
     * difficult to debug classpath issue, where 'ResourceManagerImpl instanceof ResourceManager' surprisingly
     * yields false, see https://github.com/whitesource/whitesource-bamboo-agent/issues/9 for details.
     * 
     * It turns out that Velocity isn't very OSGi friendly in the first place (despite being 'OSGi ready' since
     * version 1.7, see https://issues.apache.org/jira/browse/VELOCITY-694), for examples see e.g.
     * https://developer.atlassian.com/display/PLUGINFRAMEWORK/Troubleshooting+Velocity+in+OSGi and
     * http://stackoverflow.com/a/11437049/45773.
     * 
     * Even worse seems to be the reflection based dynamic class loading in place, which matches the issues outline
     * in http://wiki.eclipse.org/index.php/Context_Class_Loader_Enhancements#Problem_Description (another remotely
     * related issue is http://wiki.osgi.org/wiki/Avoid_Classloader_Hacks#Assumption_of_Global_Class_Visibility).
     * Fortunately the former provides an easy workaround for the single call at hand though, which is used here
     * accordingly (see http://wiki.eclipse.org/index.php/Context_Class_Loader_Enhancements#Context_Class_Loader_2).
     */
    File reportArchive = null;
    Thread thread = Thread.currentThread();
    ClassLoader loader = thread.getContextClassLoader();
    thread.setContextClassLoader(this.getClass().getClassLoader());
    try {
        reportArchive = report.generate(buildDirectory, true);
    } finally {
        thread.setContextClassLoader(loader);
    }

    if (reportArchive != null) {
        ArtifactDefinitionContext artifact = new ArtifactDefinitionContextImpl(SecureToken.create());
        artifact.setName(reportArchive.getName());
        artifact.setCopyPattern(reportArchive.getName());
        buildContext.getArtifactContext().getDefinitionContexts().add(artifact);
        log.info(WssUtils.logMsg(LOG_COMPONENT, "Defined artifact " + artifact));
    }
}

From source file:org.nuxeo.ecm.core.management.probes.ProbeManagerImpl.java

protected void doRunProbe(ProbeInfo probe) {
    if (!probe.isEnabled()) {
        return;//from www . j av a 2  s . c o  m
    }
    try {
        ProbeInfoImpl probeInfoImpl = (ProbeInfoImpl) probe;
        Thread currentThread = Thread.currentThread();
        ClassLoader lastLoader = currentThread.getContextClassLoader();
        currentThread.setContextClassLoader(ProbeInfoImpl.class.getClassLoader());
        probeInfoImpl.lastRunnedDate = new Date();
        probeInfoImpl.runnedCount += 1;
        try {
            Probe runnableProbe = probesByShortcuts.get(probe.getShortcutName());
            probeInfoImpl.lastStatus = runnableProbe.run();
            if (probeInfoImpl.lastStatus.isSuccess()) {
                probeInfoImpl.lastSucceedDate = probeInfoImpl.lastRunnedDate;
                probeInfoImpl.lastSuccessStatus = probeInfoImpl.lastStatus;
                probeInfoImpl.successCount += 1;
            } else {
                probeInfoImpl.lastFailureStatus = probeInfoImpl.lastStatus;
                probeInfoImpl.failureCount += 1;
                probeInfoImpl.lastFailureDate = probeInfoImpl.lastRunnedDate;
            }
        } catch (Throwable e) {
            probeInfoImpl.failureCount += 1;
            probeInfoImpl.lastFailureDate = new Date();
            probeInfoImpl.lastFailureStatus = ProbeStatus.newError(e);
        } finally {
            probeInfoImpl.lastDuration = doGetDuration(probeInfoImpl.lastRunnedDate, new Date());
            currentThread.setContextClassLoader(lastLoader);
        }

        if (probe.isInError()) {
            succeed.remove(probe);
            failed.add(probe);
        } else {
            failed.remove(probe);
            succeed.add(probe);
        }
    } catch (Throwable e) {
        succeed.remove(probe);
        failed.add(probe);
    }
}

From source file:org.springframework.osgi.web.tomcat.internal.Activator.java

public void stop(BundleContext context) throws Exception {
    // unpublish service first
    registration.unregister();// w w  w.  j a  v a  2s.co  m
    urlRegistration.unregister();

    log.info("Unpublished  " + ServerInfo.getServerInfo() + " OSGi service");

    // default startup procedure
    ClassLoader cl = Activator.class.getClassLoader();
    Thread current = Thread.currentThread();
    ClassLoader old = current.getContextClassLoader();

    try {
        current.setContextClassLoader(cl);
        //reset CCL 
        // current.setContextClassLoader(null);
        log.info("Stopping " + ServerInfo.getServerInfo() + " ...");
        server.stop();
        log.info("Succesfully stopped " + ServerInfo.getServerInfo());
    } catch (Exception ex) {
        log.error("Cannot stop " + ServerInfo.getServerInfo(), ex);
        throw ex;
    } finally {
        current.setContextClassLoader(old);
    }
}

From source file:org.apache.openejb.server.axis.assembler.CommonsSchemaLoader.java

private Definition readWsdl(URI wsdlURI) throws OpenEJBException {
    Definition definition;/*from w w  w.ja v  a2 s.  c o m*/
    WSDLFactory wsdlFactory;
    try {
        wsdlFactory = WSDLFactory.newInstance();
    } catch (WSDLException e) {
        throw new OpenEJBException("Could not create WSDLFactory", e);
    }
    WSDLReader wsdlReaderNoImport = wsdlFactory.newWSDLReader();
    wsdlReaderNoImport.setFeature("javax.wsdl.importDocuments", false);
    ExtensionRegistry extensionRegistry = new PopulatedExtensionRegistry();
    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_1999,
            extensionRegistry.getDefaultSerializer());

    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_2000,
            extensionRegistry.getDefaultSerializer());

    extensionRegistry.mapExtensionTypes(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            UnknownExtensibilityElement.class);
    extensionRegistry.registerDeserializer(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            extensionRegistry.getDefaultDeserializer());
    extensionRegistry.registerSerializer(Types.class, SchemaConstants.Q_ELEM_XSD_2001,
            extensionRegistry.getDefaultSerializer());
    wsdlReaderNoImport.setExtensionRegistry(extensionRegistry);

    JarWSDLLocator wsdlLocator = new JarWSDLLocator(wsdlURI);
    WSDLReader wsdlReader = wsdlFactory.newWSDLReader();

    Thread thread = Thread.currentThread();
    ClassLoader oldCl = thread.getContextClassLoader();
    thread.setContextClassLoader(this.getClass().getClassLoader());
    try {
        try {
            definition = wsdlReader.readWSDL(wsdlLocator);
        } catch (WSDLException e) {
            throw new OpenEJBException("Failed to read wsdl document", e);
        } catch (RuntimeException e) {
            throw new OpenEJBException(e.getMessage(), e);
        }
    } finally {
        thread.setContextClassLoader(oldCl);
    }

    return definition;
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void releaseFromShutdownHooks(WeakReference<ClassLoader> classLoader) {
    final Map<Thread, Thread> hooks = (Map<Thread, Thread>) Reflections
            .getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");

    if (hooks != null) {
        final List<Thread> shutdownHooks = new ArrayList<>(hooks.keySet());

        for (Thread shutdownHook : shutdownHooks) {
            if (Objects.equals(classLoader.get(), shutdownHook.getContextClassLoader())) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
                shutdownHook.start();/*from   w  ww. java 2 s.  c  o m*/
                try {
                    shutdownHook.join(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    shutdownHook.stop();
                }
                shutdownHook.setContextClassLoader(null);
            }
        }
    }
}

From source file:org.springframework.osgi.web.tomcat.internal.Activator.java

public void start(BundleContext context) throws Exception {
    this.bundleContext = context;
    // do the initialization on a different thread
    // so the activator finishes fast
    startupThread = new Thread(new Runnable() {

        public void run() {
            log.info("Starting " + ServerInfo.getServerInfo() + " ...");

            // default startup procedure
            ClassLoader cl = Activator.class.getClassLoader();
            Thread current = Thread.currentThread();
            ClassLoader old = current.getContextClassLoader();

            try {
                current.setContextClassLoader(cl);

                server = createCatalinaServer(bundleContext.getBundle());

                server.start();//  ww  w .  j a v a 2 s  .c o  m

                Connector[] connectors = server.findConnectors();
                for (int i = 0; i < connectors.length; i++) {
                    Connector conn = connectors[i];
                    log.info("Succesfully started " + ServerInfo.getServerInfo() + " @ " + conn.getDomain()
                            + ":" + conn.getPort());
                }

                // register URL service
                urlRegistration = registerTomcatJNDIUrlService();
                // publish server as an OSGi service
                registration = publishServerAsAService(server);
                log.info("Published " + ServerInfo.getServerInfo() + " as an OSGi service");
            } catch (Exception ex) {
                String msg = "Cannot start " + ServerInfo.getServerInfo();
                log.error(msg, ex);
                throw new RuntimeException(msg, ex);
            } finally {
                current.setContextClassLoader(old);
            }
        }
    }, "Tomcat Catalina Start Thread");

    startupThread.start();
}