Example usage for java.lang Thread setContextClassLoader

List of usage examples for java.lang Thread setContextClassLoader

Introduction

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

Prototype

public void setContextClassLoader(ClassLoader cl) 

Source Link

Document

Sets the context ClassLoader for this Thread.

Usage

From source file:org.springframework.boot.web.embedded.netty.NettyWebServer.java

private void startDaemonAwaitThread(DisposableServer disposableServer) {
    Thread awaitThread = new Thread("server") {

        @Override//from   www.  j a v a  2s  .c o  m
        public void run() {
            disposableServer.onDispose().block();
        }

    };
    awaitThread.setContextClassLoader(getClass().getClassLoader());
    awaitThread.setDaemon(false);
    awaitThread.start();
}

From source file:org.wso2.carbon.custom.connector.EJBStatelessBean.java

@Override
public void connect(MessageContext messageContext) {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {/*from ww  w .  jav a  2  s.  co  m*/
        //switching the classloader to prevent class loading glassfish classloading issues
        currentThread.setContextClassLoader(getClass().getClassLoader());
        callEJBStateless(messageContext);
    } catch (Exception e) {
        handleException("Error calling EJB Service from EJBConnector", e, messageContext);
    } finally {
        if (oldClassLoader != null) {
            //resetting the classloader
            currentThread.setContextClassLoader(oldClassLoader);
        }
    }
}

From source file:org.wso2.carbon.custom.connector.EJBStateful.java

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {// w  w  w.j  av  a2  s  .  co  m
        //switching the classloader to prevent class loading glassfish classloading issues
        currentThread.setContextClassLoader(getClass().getClassLoader());
        callEJBStateful(messageContext);
    } catch (Exception e) {
        handleException("Error calling EJB Service from EJBConnector", e, messageContext);
    } finally {
        if (oldClassLoader != null) {
            //resetting the classloader
            currentThread.setContextClassLoader(oldClassLoader);
        }
    }
}

From source file:org.wso2.carbon.custom.connector.EJBConnector.java

@Override
public void connect(MessageContext ctx) {
    log.info("Initializing EJBConnector");
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {/*from  ww w.ja va 2  s. c om*/
        //switching the classloader to prevent class loading glassfish classloading issues
        currentThread.setContextClassLoader(getClass().getClassLoader());
        callEJB();
    } catch (Exception e) {
        log.error("Error calling EJB Service from EJBConnector", e);
    } finally {
        if (oldClassLoader != null) {
            //resetting the classloader
            currentThread.setContextClassLoader(oldClassLoader);
        }
    }
}

From source file:org.hyperic.hq.hqu.PluginWrapper.java

private Object doInContext(Runnee runnable) throws Exception {
    Thread curThread = Thread.currentThread();
    ClassLoader oldLoader = curThread.getContextClassLoader();

    try {//  w  w  w  .  jav  a 2 s  . c  o m
        curThread.setContextClassLoader(_loader);
        return runnable.run();
    } finally {
        curThread.setContextClassLoader(oldLoader);
    }
}

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//  w  ww.  ja  v  a2 s  . c o  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:org.apache.hadoop.hbase.coprocessor.BaseEnvironment.java

/** Initialize the environment */
@Override//from   ww  w . ja  v  a  2  s  . co m
public void startup() throws IOException {
    if (state == Coprocessor.State.INSTALLED || state == Coprocessor.State.STOPPED) {
        state = Coprocessor.State.STARTING;
        Thread currentThread = Thread.currentThread();
        ClassLoader hostClassLoader = currentThread.getContextClassLoader();
        try {
            currentThread.setContextClassLoader(this.getClassLoader());
            impl.start(this);
            state = Coprocessor.State.ACTIVE;
        } finally {
            currentThread.setContextClassLoader(hostClassLoader);
        }
    } else {
        LOG.warn("Not starting coprocessor " + impl.getClass().getName() + " because not inactive (state="
                + state.toString() + ")");
    }
}

From source file:org.openmrs.util.OpenmrsClassLoader.java

public static void onShutdown() {

    //Since we are shutting down, stop all threads that reference the openmrs class loader.
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread thread : threadArray) {

        ClassLoader classLoader = thread.getContextClassLoader();

        //Threads like Finalizer, Reference Handler, etc have null class loader reference.
        if (classLoader == null) {
            continue;
        }/*from w  w w.j a v a 2 s. co  m*/

        if (classLoader instanceof OpenmrsClassLoader) {
            try {
                //Set to WebappClassLoader just in case stopping fails.
                thread.setContextClassLoader(classLoader.getParent());

                //Stopping the current thread will halt all current cleanup.
                //So do not ever ever even attempt stopping it. :)
                if (thread == Thread.currentThread()) {
                    continue;
                }

                log.info("onShutdown Stopping thread: " + thread.getName());
                thread.stop();
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }

    clearReferences();
}

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());
    /*//from   w  w  w .  j a  v  a  2s  .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: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//from  w  w w  .  j  av  a  2 s  .c  om
        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);
    }
}