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.nuxeo.runtime.jboss.deployer.Bootstrap.java

public void stopNuxeo() throws Exception {
    Thread thread = Thread.currentThread();
    ClassLoader oldcl = thread.getContextClassLoader();
    thread.setContextClassLoader(cl);/*from w w  w. j av  a  2 s. c  o  m*/
    try {
        invokeStop();
    } finally {
        thread.setContextClassLoader(oldcl);
    }
}

From source file:net.sourceforge.vulcan.jabber.SmackKeepAliveThreadInterrupter.java

public void interrupt() {
    final ThreadGroup group = Thread.currentThread().getThreadGroup();

    final Thread[] threads = new Thread[group.activeCount()];

    group.enumerate(threads);/*w  w w .jav  a  2  s  . co  m*/

    for (Thread thread : threads) {
        if (!thread.getName().startsWith("Smack Keep Alive")) {
            continue;
        }

        if (!thread.getContextClassLoader().equals(getClass().getClassLoader())) {
            // only wake up threads from our own class loader
            LOG.info("Not waking up " + thread.getName() + " because it uses a different class loader.");
            continue;
        }

        LOG.info("Interrupting " + thread.getName());

        thread.interrupt();

        try {
            thread.join(1000);
        } catch (InterruptedException ignore) {
        }

        if (thread.isAlive()) {
            LOG.error("Smack Keep Alive thread still alive after interruption.");
        }
    }
}

From source file:org.opennaas.extensions.bod.autobahn.protocol.AutobahnProtocolSession.java

private <T> T createSoapService(String uri, QName serviceName, QName portName, Class<T> clazz)
        throws ProtocolException {
    /*/*from   w w w . j  a va2s  .c om*/
     * The JAXWS SPI uses the context class loader to locate an implementation. We therefore make sure the context class loader is set to our
     * class loader.
     */
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(getClass().getClassLoader());
        Service service = Service.create(serviceName);
        service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, uri);
        return service.getPort(portName, clazz);
    } catch (WebServiceException e) {
        throw new ProtocolException("Failed to create Autobahn session: " + e.getMessage(), e);
    } finally {
        thread.setContextClassLoader(oldLoader);
    }
}

From source file:org.nuxeo.ecm.core.persistence.PersistenceProvider.java

public <T> T run(Boolean needActiveSession, RunCallback<T> callback) throws ClientException {
    // needActiveSession now unused
    Thread myThread = Thread.currentThread();
    ClassLoader lastLoader = myThread.getContextClassLoader();
    myThread.setContextClassLoader(getClass().getClassLoader());
    try { // insure context class loader restoring
        EntityManager em = doAcquireEntityManager();
        doBegin(em);/*from   w  w  w . j a  v  a2s  . c  om*/
        try { // insure entity manager releasing
            return callback.runWith(em);
        } finally {
            releaseEntityManager(em);
        }
    } finally {
        myThread.setContextClassLoader(lastLoader);
    }
}

From source file:org.nuxeo.ecm.core.persistence.PersistenceProvider.java

public void run(Boolean needActiveSession, RunVoid callback) throws ClientException {
    // needActiveSession now unused
    Thread myThread = Thread.currentThread();
    ClassLoader lastLoader = myThread.getContextClassLoader();
    myThread.setContextClassLoader(getClass().getClassLoader());
    try { // insure context class loader restoring
        EntityManager em = doAcquireEntityManager();
        doBegin(em);/*from   w w w. ja  v a  2 s .  c o m*/
        try { // insure entity manager releasing
            callback.runWith(em);
        } finally {
            releaseEntityManager(em);
        }
    } finally {
        myThread.setContextClassLoader(lastLoader);
    }
}

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  . j a  v  a2 s . c o m*/
        curThread.setContextClassLoader(_loader);
        return runnable.run();
    } finally {
        curThread.setContextClassLoader(oldLoader);
    }
}

From source file:org.sakaiproject.kernel.persistence.eclipselink.EntityManagerFactoryProvider.java

/**
 * Construct an EclipseLink entity manager provider.
 *
 * @param minRead// www. j  a v  a 2 s  . com
 * @param minWrite
 * @param dataSourceService
 * @param unitName
 */
@Inject
@SuppressWarnings(value = {
        "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED" }, justification = "Expected to only ever be executed from a privalaged environment")
public EntityManagerFactoryProvider(DataSourceService dataSourceService,
        @Named(KernelConstants.DB_MIN_NUM_READ) String minRead,
        @Named(KernelConstants.DB_MIN_WRITE) String minWrite,
        @Named(KernelConstants.DB_UNITNAME) String unitName,
        @Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName,
        @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username,
        @Named(KernelConstants.JDBC_PASSWORD) String password) {

    Map<String, Object> properties = new HashMap<String, Object>();

    // Ensure RESOURCE_LOCAL transactions is used.
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

    LOG.info("Using provided data source");
    properties.put(dataSourceService.getType(), dataSourceService.getDataSource());

    // Configure the internal EclipseLink connection pool
    // LOG.info("Creating internal data source");
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, driverClassName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, url);
    // properties.put(PersistenceUnitProperties.JDBC_USER, username);
    // properties.put(PersistenceUnitProperties.JDBC_PASSWORD, password);
    // properties
    // .put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, minRead);
    // properties.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN,
    // minWrite);

    // Configure logging. FINE ensures all SQL is shown
    properties.put(LOGGING_LEVEL, (debug ? "FINE" : "INFO"));
    properties.put(LOGGING_TIMESTAMP, "true");
    properties.put(LOGGING_THREAD, "true");
    properties.put(LOGGING_SESSION, "true");

    // Ensure that no server-platform is configured
    properties.put(TARGET_SERVER, TargetServer.None);

    properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    properties.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql");
    properties.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql");
    properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE,
            PersistenceUnitProperties.DDL_BOTH_GENERATION);

    // properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
    // EnableIntegrityChecker.class.getName());

    LOG.info("Starting connection manager with properties " + properties);
    final Thread currentThread = Thread.currentThread();
    final ClassLoader saveClassLoader = currentThread.getContextClassLoader();

    PersistenceUnitClassLoader persistenceCL = new PersistenceUnitClassLoader(this.getClass().getClassLoader());
    currentThread.setContextClassLoader(persistenceCL);
    entityManagerFactory = Persistence.createEntityManagerFactory(unitName, properties);
    currentThread.setContextClassLoader(saveClassLoader);

}

From source file:org.apache.hadoop.hbase.coprocessor.BaseEnvironment.java

/** Initialize the environment */
@Override/* ww w.j  av  a 2 s. com*/
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.apereo.portal.portlet.container.EventProviderImpl.java

@Override
public Event createEvent(QName qname, Serializable value) throws IllegalArgumentException {
    if (this.isDeclaredAsPublishingEvent(qname)) {
        if (value != null && !this.isValueInstanceOfDefinedClass(qname, value)) {
            throw new IllegalArgumentException("Payload class (" + value.getClass().getCanonicalName()
                    + ") does not have the right class, check your defined event types in portlet.xml.");
        }//from w w w  .  j  av  a2s .  co  m

        if (value == null) {
            return new EventImpl(qname);
        }

        try {
            final Thread currentThread = Thread.currentThread();
            final ClassLoader cl = currentThread.getContextClassLoader();
            final Writer out = new StringWriter();
            final Class clazz = value.getClass();
            try {
                currentThread.setContextClassLoader(this.portletClassLoader);
                final JAXBContext jc = JAXBContext.newInstance(clazz);
                final Marshaller marshaller = jc.createMarshaller();
                final JAXBElement<Serializable> element = new JAXBElement<Serializable>(qname, clazz, value);
                marshaller.marshal(element, out);
            } finally {
                currentThread.setContextClassLoader(cl);
            }
            return new EventImpl(qname, out.toString());
        } catch (JAXBException e) {
            // maybe there is no valid jaxb binding
            // TODO throw exception?
            logger.error("Event handling failed", e);
        } catch (FactoryConfigurationError e) {
            // TODO throw exception?
            logger.warn(e.getMessage(), e);
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.coprocessor.BaseEnvironment.java

/** Clean up the environment */
@Override//from   ww w  .  j a  v  a 2 s  .  co  m
public void shutdown() {
    if (state == Coprocessor.State.ACTIVE) {
        state = Coprocessor.State.STOPPING;
        Thread currentThread = Thread.currentThread();
        ClassLoader hostClassLoader = currentThread.getContextClassLoader();
        try {
            currentThread.setContextClassLoader(this.getClassLoader());
            impl.stop(this);
            state = Coprocessor.State.STOPPED;
        } catch (IOException ioe) {
            LOG.error("Error stopping coprocessor " + impl.getClass().getName(), ioe);
        } finally {
            currentThread.setContextClassLoader(hostClassLoader);
        }
    } else {
        LOG.warn("Not stopping coprocessor " + impl.getClass().getName() + " because not active (state="
                + state.toString() + ")");
    }
    synchronized (openTables) {
        // clean up any table references
        for (Table table : openTables) {
            try {
                ((HTableWrapper) table).internalClose();
            } catch (IOException e) {
                // nothing can be done here
                LOG.warn("Failed to close " + table.getName(), e);
            }
        }
    }
}