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:org.yestech.maven.HibernateSearchBuildIndexesMojo.java

public void execute() throws MojoExecutionException {

    if (skip) {//w w w  .  j av  a2  s  . c  o  m
        getLog().info("Skipping search index population");
        return;
    }

    Thread thread = Thread.currentThread();
    ClassLoader oldClassLoader = thread.getContextClassLoader();
    thread.setContextClassLoader(getClassLoader());

    FullTextSession fullTextSession = null;
    Connection con = null;
    try {

        Class.forName(driver);
        con = java.sql.DriverManager.getConnection(url, username, password);

        Configuration configuration = new AnnotationConfiguration();
        configuration = configuration.configure(config);
        if (StringUtils.isNotBlank(dialect)) {
            configuration.setProperty("hibernate.dialect", dialect);
        }

        prepareIndexDir(configuration);

        if (StringUtils.isNotBlank(directoryProvider)) {
            configuration.setProperty("hibernate.search.default.directory_provider", directoryProvider);
        }

        fullTextSession = processObjects(fullTextSession, con, configuration);
    } catch (Exception e) {
        throw new MojoExecutionException("Build " + e.getMessage(), e);
    } finally {
        if (fullTextSession != null) {
            fullTextSession.flushToIndexes();
            fullTextSession.flush();
            fullTextSession.close();
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                getLog().error(e);
            }
        }
        thread.setContextClassLoader(oldClassLoader);
    }

}

From source file:org.opencastproject.userdirectory.ldap.LdapUserProviderInstance.java

/**
 * Loads a user from LDAP./*from www  .  j  a v  a  2s.  c  o  m*/
 * 
 * @param userName
 *          the username
 * @return the user
 */
protected User loadUserFromLdap(String userName) {
    if (delegate == null || cache == null) {
        throw new IllegalStateException("The LDAP user detail service has not yet been configured");
    }
    ldapLoads.incrementAndGet();
    UserDetails userDetails = null;

    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassloader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(LdapUserProviderFactory.class.getClassLoader());
        try {
            userDetails = delegate.loadUserByUsername(userName);
        } catch (UsernameNotFoundException e) {
            cache.put(userName, nullToken);
            return null;
        }

        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        String[] roles = null;
        if (authorities != null) {
            int i = 0;
            roles = new String[authorities.size()];
            for (GrantedAuthority authority : authorities) {
                String role = authority.getAuthority();
                roles[i++] = role;
            }
        }
        User user = new User(userDetails.getUsername(), getOrganization(), roles);
        cache.put(userName, user);
        return user;
    } finally {
        currentThread.setContextClassLoader(originalClassloader);
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java

/**
 * Overrides the default behaviour to including binding of Grails domain classes.
 *//*from w ww .j a va 2 s . c  om*/
@Override
protected void secondPassCompile() throws MappingException {
    final Thread currentThread = Thread.currentThread();
    final ClassLoader originalContextLoader = currentThread.getContextClassLoader();
    if (!configLocked) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("[GrailsAnnotationConfiguration] [" + domainClasses.size()
                    + "] Grails domain classes to bind to persistence runtime");
        }

        // do Grails class configuration
        DefaultGrailsDomainConfiguration.configureDomainBinder(grailsApplication, domainClasses);

        for (GrailsDomainClass domainClass : domainClasses) {

            final String fullClassName = domainClass.getFullName();

            String hibernateConfig = fullClassName.replace('.', '/') + ".hbm.xml";
            final ClassLoader loader = originalContextLoader;
            // don't configure Hibernate mapped classes
            if (loader.getResource(hibernateConfig) != null)
                continue;

            final Mappings mappings = super.createMappings();
            if (!GrailsHibernateUtil.usesDatasource(domainClass, dataSourceName)) {
                continue;
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("[GrailsAnnotationConfiguration] Binding persistent class [" + fullClassName + "]");
            }

            Mapping m = GrailsDomainBinder.getMapping(domainClass);
            mappings.setAutoImport(m == null || m.getAutoImport());
            GrailsDomainBinder.bindClass(domainClass, mappings, sessionFactoryBeanName);
        }
    }

    try {
        currentThread.setContextClassLoader(grailsApplication.getClassLoader());
        super.secondPassCompile();
    } finally {
        currentThread.setContextClassLoader(originalContextLoader);
    }

    configLocked = true;
}

From source file:com.liferay.wsrp.proxy.ServiceHandler.java

public Object doInvoke(Object proxy, Method method, Object[] args) throws Exception {

    String methodName = method.getName();

    if (_v2 && methodName.equals("getWSRP_v2_Markup_Service")) {
        WSRP_v2_Markup_Binding_SOAPStub markupService = new WSRP_v2_Markup_Binding_SOAPStub((URL) args[0],
                _serviceLocator);//w w w.ja v  a  2s  . c o  m

        WSRP_v2_ServiceLocator wsrpV2ServiceLocator = (WSRP_v2_ServiceLocator) _serviceLocator;

        String markupServiceName = wsrpV2ServiceLocator.getWSRP_v2_Markup_ServiceWSDDServiceName();

        markupService.setPortName(markupServiceName);

        return markupService;
    }

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    URL bindingURL = (URL) args[0];

    int x = methodName.indexOf("_v2_") + 4;
    int y = methodName.lastIndexOf("_Service");

    String serviceName = methodName.substring(x, y);

    StringBundler sb = new StringBundler(7);

    sb.append(_OASIS_PACKAGE);
    sb.append(_version);
    sb.append(".bind.WSRP_");
    sb.append(_version);
    sb.append(StringPool.UNDERLINE);
    sb.append(serviceName);
    sb.append("_Binding_SOAPStub");

    Class<?> clazz = contextClassLoader.loadClass(sb.toString());

    args = new Object[] { bindingURL, getService() };

    Object stub = ConstructorUtils.invokeConstructor(clazz, args);

    sb = new StringBundler(5);

    sb.append("getWSRP_");
    sb.append(_version);
    sb.append(StringPool.UNDERLINE);
    sb.append(serviceName);
    sb.append("_ServiceWSDDServiceName");

    Object serviceWSDDServiceName = MethodUtils.invokeMethod(_serviceLocator, sb.toString(), null);

    MethodUtils.invokeMethod(stub, "setPortName", serviceWSDDServiceName);

    if (_v2) {
        return stub;
    }

    sb.setIndex(0);

    sb.append(_OASIS_PACKAGE);
    sb.append("v2.intf.WSRP_v2_");
    sb.append(serviceName);
    sb.append("_PortType");

    Class<?> proxyInterface = contextClassLoader.loadClass(sb.toString());

    sb.setIndex(0);

    sb.append(_WSRP_PROXY_PACKAGE);
    sb.append(serviceName);
    sb.append("ServiceHandler");

    clazz = contextClassLoader.loadClass(sb.toString());

    InvocationHandler invocationHandler = (InvocationHandler) ConstructorUtils.invokeConstructor(clazz, stub);

    return ProxyUtil.newProxyInstance(ServiceHandler.class.getClassLoader(),
            new Class[] { proxyInterface, Stub.class }, invocationHandler);
}

From source file:org.atm.mvn.run.JavaBootstrap.java

/**
 * Run the main method in the class using the specified class path.
 * /*  www  . ja  va 2 s .c  om*/
 * @throws Exception
 *             Any exceptions that might occur.
 */
public void run() throws Exception {
    Thread currentThread = Thread.currentThread();

    ClassLoader existingClassLoader = currentThread.getContextClassLoader();
    try {
        /*
         * Replace the current class loader with one with all of the needed
         * dependencies.
         */
        ClassLoader bootstrapClassLoader = createClassLoader(ClassLoader.getSystemClassLoader(), false);

        currentThread.setContextClassLoader(bootstrapClassLoader);

        // find the java class
        Class<?> mainClass = resolveClass(bootstrapClassLoader);

        // find the main method
        Method mainMethod = resolveMainMethod(mainClass);

        // invoke the main method
        invokeMain(mainMethod);
    } finally {
        currentThread.setContextClassLoader(existingClassLoader);
    }
}

From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java

@Nonnull
@Override/*from w  w w  .j  a v a  2s.  c o  m*/
public ClassLoader getClassLoader() {
    // Get current context class loader
    final Thread currentThread = Thread.currentThread();
    final ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    // Get interpreter class loader from context
    getInterpreter().setContextClassLoader();
    final ClassLoader interpreterClassLoader = currentThread.getContextClassLoader();

    // Reset context
    currentThread.setContextClassLoader(contextClassLoader);
    return interpreterClassLoader;
}

From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java

/**
 * Executes the specified callable after replacing the current context class loader.
 *
 * <p>This is a work-around to avoid {@link ClassCastException} issues caused by conflicts between Hadoop and Kylo Spark Shell. Spark uses the context class loader when loading Hadoop components
 * for running Spark on YARN. When both Hadoop and Kylo Spark Shell provide the same class then both classes are loaded when creating a {@link SparkContext}. The fix is to set the context class
 * loader to the same class loader that was used to load the {@link SparkContext} class.</p>
 *
 * @param callable the function to be executed
 * @param <T>      the return type
 * @return the return value//  w ww. j av a  2 s .co  m
 */
private <T> T executeWithSparkClassLoader(@Nonnull final Callable<T> callable) {
    // Set context class loader
    final Thread currentThread = Thread.currentThread();
    final ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    final ClassLoader sparkClassLoader = new ForwardingClassLoader(SparkContext.class.getClassLoader(),
            contextClassLoader);
    currentThread.setContextClassLoader(sparkClassLoader);

    // Execute callable
    try {
        return callable.call();
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    } finally {
        // Reset context class loader
        currentThread.setContextClassLoader(contextClassLoader);
    }
}

From source file:org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost.java

private boolean execOperation(final CoprocessorOperation ctx) throws IOException {
    if (ctx == null)
        return false;

    boolean bypass = false;
    for (RegionServerEnvironment env : coprocessors) {
        if (env.getInstance() instanceof RegionServerObserver) {
            ctx.prepare(env);//from www  .  j a v a2  s. c  om
            Thread currentThread = Thread.currentThread();
            ClassLoader cl = currentThread.getContextClassLoader();
            try {
                currentThread.setContextClassLoader(env.getClassLoader());
                ctx.call((RegionServerObserver) env.getInstance(), ctx);
            } catch (Throwable e) {
                handleCoprocessorThrowable(env, e);
            } finally {
                currentThread.setContextClassLoader(cl);
            }
            bypass |= ctx.shouldBypass();
            if (ctx.shouldComplete()) {
                break;
            }
        }
        ctx.postEnvCall(env);
    }
    return bypass;
}

From source file:com.liferay.portal.template.velocity.internal.VelocityManager.java

@Override
public void init() throws TemplateException {
    if (_velocityEngine != null) {
        return;//from  w  w  w.j a v  a2 s.  co  m
    }

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    Class<?> clazz = getClass();

    currentThread.setContextClassLoader(clazz.getClassLoader());

    try {
        _velocityEngine = new VelocityEngine();

        ExtendedProperties extendedProperties = new FastExtendedProperties();

        extendedProperties.setProperty(VelocityEngine.DIRECTIVE_IF_TOSTRING_NULLCHECK,
                String.valueOf(_velocityEngineConfiguration.directiveIfToStringNullCheck()));

        extendedProperties.setProperty(VelocityEngine.EVENTHANDLER_METHODEXCEPTION,
                LiferayMethodExceptionEventHandler.class.getName());

        extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,
                StringUtil.merge(_velocityEngineConfiguration.restrictedClasses()));

        extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_PACKAGES,
                StringUtil.merge(_velocityEngineConfiguration.restrictedPackages()));

        extendedProperties.setProperty(RuntimeConstants.PARSER_POOL_CLASS, VelocityParserPool.class.getName());

        extendedProperties.setProperty(VelocityEngine.RESOURCE_LOADER, "liferay");

        extendedProperties.setProperty(StringBundler.concat("liferay.", VelocityEngine.RESOURCE_LOADER, ".",
                VelocityTemplateResourceLoader.class.getName()), templateResourceLoader);

        boolean cacheEnabled = false;

        if (_velocityEngineConfiguration.resourceModificationCheckInterval() != 0) {

            cacheEnabled = true;
        }

        extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".cache",
                String.valueOf(cacheEnabled));

        extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".class",
                LiferayResourceLoader.class.getName());

        extendedProperties.setProperty(
                "liferay." + VelocityEngine.RESOURCE_LOADER + ".resourceModificationCheckInterval",
                _velocityEngineConfiguration.resourceModificationCheckInterval() + "");

        extendedProperties.setProperty(VelocityEngine.RESOURCE_MANAGER_CLASS,
                LiferayResourceManager.class.getName());

        extendedProperties.setProperty(
                "liferay." + VelocityEngine.RESOURCE_MANAGER_CLASS + ".resourceModificationCheckInterval",
                _velocityEngineConfiguration.resourceModificationCheckInterval() + "");

        extendedProperties.setProperty(VelocityTemplateResourceLoader.class.getName(), templateResourceLoader);

        extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
                _velocityEngineConfiguration.logger());

        extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
                _velocityEngineConfiguration.loggerCategory());

        extendedProperties.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName());

        extendedProperties.setProperty(VelocityEngine.VM_LIBRARY,
                StringUtil.merge(_velocityEngineConfiguration.velocimacroLibrary()));

        extendedProperties.setProperty(VelocityEngine.VM_LIBRARY_AUTORELOAD, String.valueOf(!cacheEnabled));

        extendedProperties.setProperty(VelocityEngine.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL,
                String.valueOf(!cacheEnabled));

        _velocityEngine.setExtendedProperties(extendedProperties);

        _velocityEngine.init();
    } catch (Exception e) {
        throw new TemplateException(e);
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);
    }
}

From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java

@SuppressWarnings("deprecation")
private void cleanupAllThreads() {
    final Thread[] threads = getThreads();
    final ClassLoader cl = this.getClass().getClassLoader();
    try {//  w ww .  j a va 2 s . com
        cl.getResource(null);
    } catch (final Exception e) {
    }

    final List<String> jvmThreadGroupList = new ArrayList<String>();
    jvmThreadGroupList.add("system");
    jvmThreadGroupList.add("RMI Runtime");

    // Iterate over the set of threads
    for (final Thread thread : threads) {
        if (thread != null) {
            final ClassLoader ccl = thread.getContextClassLoader();
            if (ccl != null && ccl.equals(cl)) {
                // Don't warn about this thread
                if (thread == Thread.currentThread()) {
                    continue;
                }

                // Don't warn about JVM controlled threads
                final ThreadGroup tg = thread.getThreadGroup();
                if (tg != null && jvmThreadGroupList.contains(tg.getName())) {
                    continue;
                }

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Interrupting a thread [" + thread.getName() + "]...");
                }
                thread.interrupt();

                waitThread(thread);
                // Skip threads that have already died
                if (!thread.isAlive()) {
                    continue;
                }

                if (logger.isInfoEnabled()) {
                    logger.info("Stopping a thread [" + thread.getName() + "]...");
                }
                thread.stop();
            }
        }
    }

    Field threadLocalsField = null;
    Field inheritableThreadLocalsField = null;
    Field tableField = null;
    try {
        threadLocalsField = Thread.class.getDeclaredField("threadLocals");
        threadLocalsField.setAccessible(true);
        inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
        inheritableThreadLocalsField.setAccessible(true);
        // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects
        // accessible
        final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
        tableField = tlmClass.getDeclaredField("table");
        tableField.setAccessible(true);
    } catch (final Exception e) {
        // ignore
    }
    for (final Thread thread : threads) {
        if (thread != null) {

            Object threadLocalMap;
            try {
                // Clear the first map
                threadLocalMap = threadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
            try { // Clear the second map
                threadLocalMap = inheritableThreadLocalsField.get(thread);
                clearThreadLocalMap(cl, threadLocalMap, tableField);
            } catch (final Exception e) {
                // ignore
            }
        }
    }
}