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

private ExpressionAccessor getPropertyAccessor(Item item, String expression) throws Exception {
    ExpressionAccessor accessor = null;/*w ww . j a v  a 2 s  .c  o 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:com.gatf.executor.dataprovider.SQLDatabaseTestDataSource.java

public void init() {
    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {/*  ww  w. j a va2 s  .c om*/
        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.impalaframework.spring.service.proxy.ServiceEndpointInterceptor.java

public Object invoke(MethodInvocation invocation) throws Throwable {

    final Method method = invocation.getMethod();
    final Object[] arguments = invocation.getArguments();

    final boolean setCCCL = optionsHelper.isSetContextClassLoader();

    ServiceRegistryEntry serviceReference = targetSource.getServiceRegistryReference();

    int retriesUsed = 0;
    while (serviceReference == null && retriesUsed < optionsHelper.getRetryCount()) {
        try {//from  ww  w  .j  a v  a 2 s  . com
            Thread.sleep(optionsHelper.getRetryInterval());
        } catch (InterruptedException e) {
        }
        serviceReference = targetSource.getServiceRegistryReference();
        retriesUsed++;
    }

    if (serviceReference != null) {

        final Thread currentThread;
        final ClassLoader existingClassLoader;
        if (setCCCL) {
            currentThread = Thread.currentThread();
            existingClassLoader = currentThread.getContextClassLoader();
        } else {
            currentThread = null;
            existingClassLoader = null;
        }

        try {
            if (setCCCL) {
                currentThread.setContextClassLoader(serviceReference.getBeanClassLoader());
            }

            return AopUtils.invokeJoinpointUsingReflection(
                    serviceReference.getServiceBeanReference().getService(), method, arguments);

        } finally {
            //reset the previous class loader
            if (setCCCL) {
                Thread.currentThread().setContextClassLoader(existingClassLoader);
            }
        }
    } else {

        if (optionsHelper.isLogWarningNoService()) {
            log.warn("************************************************************************* ");
            log.warn("No service available for bean " + beanName + ". Proceeding with stub implementation");
            log.warn("************************************************************************* ");
        }

        if (optionsHelper.isProceedWithNoService()) {
            return invokeDummy(invocation);
        } else {
            throw new NoServiceException("No service available for bean " + beanName);
        }
    }
}

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 {/*from  w  ww .jav  a2 s .c o m*/
        thread.setContextClassLoader(classLoader);
        super.afterPropertiesSet();
    } finally {
        thread.setContextClassLoader(cl);
    }
}

From source file:org.nuxeo.runtime.jetty.JettyComponent.java

@Override
public void applicationStarted(ComponentContext context) {
    if (server == null) {
        return;/*from   w  w  w .  j  a va 2 s  .  c  o  m*/
    }
    ctxMgr.applyLifecycleListeners();
    Thread t = Thread.currentThread();
    ClassLoader oldcl = t.getContextClassLoader();
    t.setContextClassLoader(getClass().getClassLoader());
    try {
        server.start();
    } catch (Exception e) { // stupid Jetty API throws Exception
        throw ExceptionUtils.runtimeException(e);
    } finally {
        t.setContextClassLoader(getClassLoader(oldcl));
    }
}

From source file:test.unit.be.fedict.eid.tsl.TrustServiceListFactoryTest.java

@Test
public void testThumbprint() throws Exception {
    // setup/*from   w w w . j  av  a 2s .c  om*/
    Document tslDocument = TrustTestUtils.loadDocumentFromResource("tsl-unsigned-1.xml");
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    File tslFile = new File(classLoader.getResource("tsl-unsigned-1.xml").toURI());
    TrustServiceList trustServiceList = TrustServiceListFactory.newInstance(tslDocument, tslFile);

    // operate
    String thumbprint = trustServiceList.getSha1Fingerprint();

    // verify
    LOG.debug("thumbprint: " + thumbprint);
    assertEquals("035a826a61d786c1c73c922cb5044952672cd3e0", thumbprint);
}

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();
    }//from  w w w .  j a va 2s  . c  o m
    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:org.wso2.carbon.server.admin.service.ServerAdmin.java

public void startMaintenance() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader originalClassloader = thread.getContextClassLoader();
    try {/*  w  w  w. j  a v  a  2 s  . com*/
        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  .jav a  2 s .  co  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  . j  a v  a2s  . 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;
}