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.apache.unomi.plugins.baseplugin.conditions.PropertyConditionEvaluator.java

private ExpressionAccessor getPropertyAccessor(Item item, String expression) throws Exception {
    ExpressionAccessor accessor = null;/*w  ww  . java 2  s. co  m*/
    String clazz = item.getClass().getName();
    Map<String, ExpressionAccessor> expressions = expressionCache.get(clazz);
    if (expressions == null) {
        expressions = new HashMap<>();
        expressionCache.put(clazz, expressions);
    } else {
        accessor = expressions.get(expression);
    }
    if (accessor == null) {
        long time = System.nanoTime();
        Thread current = Thread.currentThread();
        ClassLoader contextCL = current.getContextClassLoader();
        try {
            current.setContextClassLoader(PropertyConditionEvaluator.class.getClassLoader());
            Node node = Ognl.compileExpression((OgnlContext) Ognl.createDefaultContext(null), item, expression);
            accessor = node.getAccessor();
        } finally {
            current.setContextClassLoader(contextCL);
        }
        if (accessor != null) {
            expressions.put(expression, accessor);
        } else {
            logger.warn("Unable to compile expression for {} and {}", clazz, expression);
        }
        time = System.nanoTime() - time;
        logger.info("Expression compilation for {} took {}", expression, time / 1000000L);
    }

    return accessor;
}

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

@Override
public void afterPropertiesSet() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader cl = thread.getContextClassLoader();
    try {/* w  w  w .ja  v a 2 s  .  c  om*/
        thread.setContextClassLoader(classLoader);
        super.afterPropertiesSet();
    } finally {
        thread.setContextClassLoader(cl);
    }
}

From source file:com.gatf.executor.dataprovider.SQLDatabaseTestDataSource.java

public void init() {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {/*www. j ava2 s .com*/
        currentThread.setContextClassLoader(getProjectClassLoader());
        if (args == null || args.length == 0) {
            throw new AssertionError("No arguments passed to the DatabaseProvider");
        }

        if (args.length < 4) {
            throw new AssertionError("All 4 arguments, namely jdbcUrl, jdbcDriver, dbUserName and"
                    + "dbPassword are mandatory for DatabaseProvider");
        }

        Assert.assertNotNull("jdbcUrl cannot be empty", args[0]);
        Assert.assertNotNull("jdbcDriver cannot be empty", args[1]);
        Assert.assertNotNull("dbUserName cannot be empty", args[2]);
        Assert.assertNotNull("dbPassword cannot be empty", args[3]);

        jdbcUrl = args[0].trim();
        String jdbcDriver = args[1].trim();
        dbUserName = args[2].trim();
        dbPassword = args[3].trim();

        Assert.assertFalse("jdbcUrl cannot be empty", jdbcUrl.isEmpty());
        Assert.assertFalse("jdbcDriver cannot be empty", jdbcDriver.isEmpty());
        Assert.assertFalse("dbUserName cannot be empty", dbUserName.isEmpty());

        StringBuilder build = new StringBuilder();
        build.append("DatabaseTestDataSource configuration [\n");
        build.append(String.format("jdbcUrl is %s\n", jdbcUrl));
        build.append(String.format("jdbcDriver is %s\n", jdbcDriver));
        build.append(String.format("dbUserName is %s\n", dbUserName));
        build.append(String.format("dbPassword is %s]", dbPassword));
        logger.info(build.toString());

        //Load the driver first
        try {
            Driver driver = (Driver) getProjectClassLoader().loadClass(jdbcDriver).newInstance();
            CustomDriverManager.registerDriver(driver);
        } catch (Exception e) {
            throw new AssertionError(String.format("Driver class %s not found", jdbcDriver));
        }

        for (int i = 0; i < poolSize; i++) {
            //Now try connecting to the Database
            Connection conn = null;
            try {
                conn = CustomDriverManager.getConnection(jdbcUrl, dbUserName, dbPassword);
            } catch (Exception e) {
                throw new AssertionError(String.format(
                        "Connection to the Database using the JDBC URL %s failed with the error %s", jdbcUrl,
                        ExceptionUtils.getStackTrace(e)));
            }

            addToPool(conn, false);
        }

    } catch (Exception t) {
        t.printStackTrace();
    } finally {
        currentThread.setContextClassLoader(oldClassLoader);
    }
}

From source file:org.springframework.data.gemfire.CacheFactoryBean.java

public void afterPropertiesSet() throws Exception {
    // initialize locator
    if (useBeanFactoryLocator) {
        factoryLocator = new GemfireBeanFactoryLocator();
        factoryLocator.setBeanFactory(beanFactory);
        factoryLocator.setBeanName(beanName);
        factoryLocator.afterPropertiesSet();
    }//w ww.jav a  2s .  c om
    Properties cfgProps = mergeProperties();

    // use the bean class loader to load Declarable classes
    Thread th = Thread.currentThread();
    ClassLoader oldTCCL = th.getContextClassLoader();

    try {
        th.setContextClassLoader(beanClassLoader);
        // first look for open caches
        String msg = null;
        try {
            cache = fetchCache();
            msg = "Retrieved existing";
        } catch (CacheClosedException ex) {
            Object factory = createFactory(cfgProps);

            // GemFire 6.6 specific options
            if (pdxSerializer != null || pdxPersistent != null || pdxReadSerialized != null
                    || pdxIgnoreUnreadFields != null || pdxDiskStoreName != null) {
                Assert.isTrue(ClassUtils.isPresent("com.gemstone.gemfire.pdx.PdxSerializer", beanClassLoader),
                        "Cannot set PDX options since GemFire 6.6 not detected");
                applyPdxOptions(factory);
            }

            // fall back to cache creation
            cache = createCache(factory);
            msg = "Created";
        }

        DistributedSystem system = cache.getDistributedSystem();
        DistributedMember member = system.getDistributedMember();
        log.info("Connected to Distributed System [" + system.getName() + "=" + member.getId() + "@"
                + member.getHost() + "]");

        log.info(msg + " GemFire v." + CacheFactory.getVersion() + " Cache [" + cache.getName() + "]");

        // load/init cache.xml
        if (cacheXml != null) {
            cache.loadCacheXml(cacheXml.getInputStream());

            if (log.isDebugEnabled())
                log.debug("Initialized cache from " + cacheXml);
        }

    } finally {
        th.setContextClassLoader(oldTCCL);
    }
}

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

@Override
public void init() throws TemplateException {
    if (_velocityEngine != null) {
        return;/* w w w.j  av a2 s. c  o  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.openmrs.util.OpenmrsClassLoader.java

/**
 * Sets the class loader, for all threads referencing a destroyed openmrs class loader, 
 * to the current one.//from  ww w  .  jav a  2  s .  co m
 */
public static void setThreadsToNewClassLoader() {
    //Give ownership of all threads loaded by the old class loader to the new one.
    //Examples of such threads are: Keep-Alive-Timer, MySQL Statement Cancellation Timer, etc
    //That way they will no longer hold onto the destroyed OpenmrsClassLoader and hence
    //allow it to be garbage collected after a spring application context refresh, when a new one is created.
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread thread : threadArray) {

        ClassLoader classLoader = thread.getContextClassLoader();

        //Some threads have a null class loader reference. e.g Finalizer, Reference Handler, etc
        if (classLoader == null) {
            continue;
        }

        //Threads referencing the current class loader are good.
        if (classLoader == getInstance()) {
            continue;
        }

        //For threads referencing any destroyed class loader, point them to the new one.
        if (classLoader instanceof OpenmrsClassLoader) {
            thread.setContextClassLoader(getInstance());
        }
    }
}

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public void startMaintenance() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*from   w w  w .j  a  v a2 s. c  om*/
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        Map<String, TransportInDescription> inTransports = getAxisConfig().getTransportsIn();
        new ServerManagement(inTransports, getConfigContext()).startMaintenance();
        org.wso2.carbon.core.ServerStatus.setServerInMaintenance();
    } catch (AxisFault e) {
        String msg = "Cannot set server to maintenance mode";
        log.error(msg, e);
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
}

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public void endMaintenance() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*w  w  w. j  av a2 s . c o m*/
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        Map<String, TransportInDescription> inTransports = getAxisConfig().getTransportsIn();
        new ServerManagement(inTransports, getConfigContext()).endMaintenance();
        try {
            org.wso2.carbon.core.ServerStatus.setServerRunning();
        } catch (AxisFault e) {
            String msg = "Cannot set server to running mode";
            log.error(msg, e);
        }
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
}

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public boolean restart() throws Exception {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {//from  w ww.ja va2s .co m
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        ConfigurationContext configurationContext = getConfigContext();
        final Controllable controllable = (Controllable) configurationContext
                .getProperty(ServerConstants.CARBON_INSTANCE);
        Thread th = new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    controllable.restart();
                } catch (Exception e) {
                    String msg = "Cannot restart server";
                    log.error(msg, e);
                    throw new RuntimeException(msg, e);
                }
            }
        };
        th.start();
        invalidateSession();
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
    return true;
}

From source file:org.wso2.carbon.server.admin.service.ServerAdmin.java

public boolean restartGracefully() throws Exception {
    //        checkStandaloneMode();
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*  w  w w  . j a va2 s .  c  om*/
        thread.setContextClassLoader(dataHolder.getRestartThreadContextClassloader());
        ConfigurationContext configurationContext = getConfigContext();
        final Controllable controllable = (Controllable) configurationContext
                .getProperty(ServerConstants.CARBON_INSTANCE);
        Thread th = new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                    controllable.restartGracefully();
                } catch (Exception e) {
                    String msg = "Cannot restart server";
                    log.error(msg, e);
                    throw new RuntimeException(msg, e);
                }
            }
        };
        th.start();
        invalidateSession();
    } finally {
        thread.setContextClassLoader(originalClassloader);
    }
    return true;
}