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:com.mirth.connect.server.launcher.MirthLauncher.java

public static void main(String[] args) {
    try {//from  www.  j  a v a 2 s.  c  om
        try {
            uninstallPendingExtensions();
            installPendingExtensions();
        } catch (Exception e) {
            logger.error("Error uninstalling or installing pending extensions.", e);
        }

        Properties mirthProperties = new Properties();
        String includeCustomLib = null;

        try {
            mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE)));
            includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB);
            createAppdataDir(mirthProperties);
        } catch (Exception e) {
            logger.error("Error creating the appdata directory.", e);
        }

        ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar");
        ManifestDirectory serverLibDir = new ManifestDirectory("server-lib");
        serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>();
        manifestList.add(mirthServerJar);
        manifestList.add(mirthClientCoreJar);
        manifestList.add(serverLibDir);

        // We want to include custom-lib if the property isn't found, or if it equals "true"
        if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) {
            manifestList.add(new ManifestDirectory("custom-lib"));
        }

        ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]);

        // Get the current server version
        JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName());
        Properties versionProperties = new Properties();
        versionProperties.load(mirthClientCoreJarFile
                .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties")));
        String currentVersion = versionProperties.getProperty("mirth.version");

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addExtensionsToClasspath(classpathUrls, currentVersion);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth");
        Thread mirthThread = (Thread) mirthClass.newInstance();
        mirthThread.setContextClassLoader(classLoader);
        mirthThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.nuxeo.ecm.platform.uidgen.service.UIDSequencerImpl.java

private static void activatePersistenceProvider() {
    Thread thread = Thread.currentThread();
    ClassLoader last = thread.getContextClassLoader();
    try {//from www.  ja  v  a 2  s  .c  o  m
        thread.setContextClassLoader(PersistenceProvider.class.getClassLoader());
        PersistenceProviderFactory persistenceProviderFactory = Framework
                .getLocalService(PersistenceProviderFactory.class);
        persistenceProvider = persistenceProviderFactory.newProvider("NXUIDSequencer");
        persistenceProvider.openPersistenceUnit();
    } finally {
        thread.setContextClassLoader(last);
    }
}

From source file:Main.java

/**
 * Override the thread context ClassLoader with the environment's bean ClassLoader
 * if necessary, i.e. if the bean ClassLoader is not equivalent to the thread
 * context ClassLoader already.//from   w ww .  j a v a2 s. c o m
 *
 * @param classLoaderToUse the actual ClassLoader to use for the thread context
 * @return the original thread context ClassLoader, or {@code null} if not overridden
 */
public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
        currentThread.setContextClassLoader(classLoaderToUse);
        return threadContextClassLoader;
    } else {
        return null;
    }
}

From source file:com.alibaba.wasp.jdbc.Driver.java

/**
 * INTERNAL//from  w  ww . j a  v  a 2s . c o m
 */
public static void setThreadContextClassLoader(Thread thread) {
    // This is very likely to create a memory leak.
    try {
        thread.setContextClassLoader(Driver.class.getClassLoader());
    } catch (Throwable t) {
        // ignore
    }
}

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

public static void shutdownKeepAliveTimer() {
    try {//from w ww  .j  a va  2 s.  co m
        final Field kac = HttpClient.class.getDeclaredField("kac");

        kac.setAccessible(true);
        final Field keepAliveTimer = KeepAliveCache.class.getDeclaredField("keepAliveTimer");

        keepAliveTimer.setAccessible(true);

        final Thread thread = (Thread) keepAliveTimer.get(kac.get(null));

        if (thread.getContextClassLoader() == OpenmrsClassLoader.getInstance()) {
            //Set to system class loader such that we can be garbage collected.
            thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
        }
    } catch (final Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.carewebframework.ui.util.MemoryLeakPreventionUtil.java

/**
 * CWI-1409/*w w w . j  a  v a2 s .  c  o  m*/
 * <p>
 * This does what Tomcat 7 context attribute clearReferencesHttpClientKeepAliveThread is
 * suggested to do but doesn't. Using reflection in this manner is a last resort.
 * <ul>
 * <li>JDK 7 is said to fix the keepAliveTimer thread bug.</li>
 * <li>Tomcat 7.0.x context attribute clearReferencesHttpClientKeepAliveThread is suggested to
 * fix this leak but does not</li>
 * </p>
 */
@SuppressWarnings("restriction")
protected static void clearReferencesHttpClientKeepAliveThread() {
    try {
        final Field kac = sun.net.www.http.HttpClient.class.getDeclaredField("kac");
        kac.setAccessible(true);
        final Field keepAliveTimer = sun.net.www.http.KeepAliveCache.class.getDeclaredField("keepAliveTimer");
        keepAliveTimer.setAccessible(true);

        final Thread t = (Thread) keepAliveTimer.get(kac.get(null));//kac is a static field, hence null argument
        if (t != null) {//May not actually be running
            log.debug("KeepAliveTimer contextClassLoader: " + t.getContextClassLoader());
            if (t.getContextClassLoader() == Thread.currentThread().getContextClassLoader()) {
                t.setContextClassLoader(ClassLoader.getSystemClassLoader());
                log.info("Changed KeepAliveTimer classloader to system to prevent leak.");
            }
        }
    } catch (final Exception e) {
        log.warn(
                "Exception occurred attempting to prevent sun.net.www.http.HttpClient keepAliveTimer memory leak. Note: this code should not be necessary w/ java7",
                e);
    }

}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBContextFromClasses.java

/**
 * Utility method that creates a JAXBContext from the 
 * class[] and ClassLoader./*from ww  w  .j  av a2 s.  co m*/
 * 
 * @param classArray
 * @param cl
 * @return JAXBContext
 * @throws Throwable
 */
private static JAXBContext _newInstance(final Class[] classArray, final ClassLoader cl,
        final Map<String, ?> properties) throws Throwable {
    JAXBContext jaxbContext;
    try {
        jaxbContext = (JAXBContext) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws JAXBException {
                // Unlike the JAXBContext.newInstance(Class[]) method
                // does now accept a classloader.  To workaround this
                // issue, the classloader is temporarily changed to cl
                Thread currentThread = Thread.currentThread();
                ClassLoader savedClassLoader = currentThread.getContextClassLoader();
                try {
                    currentThread.setContextClassLoader(cl);
                    return JAXBContext.newInstance(classArray, properties);
                } finally {
                    currentThread.setContextClassLoader(savedClassLoader);
                }
            }
        });
    } catch (PrivilegedActionException e) {
        throw ((PrivilegedActionException) e).getException();
    } catch (Throwable t) {
        throw t;
    }
    return jaxbContext;
}

From source file:org.talend.mdm.repository.core.service.ModelImpactAnalyseService.java

public static Result readResponseMessage(String message) {
    if (message != null) {
        if (message.trim().isEmpty()) {
            // first time deploy
            return null;
        }/*from w  w w  . j a v a 2  s . c  o  m*/
        Thread cur = Thread.currentThread();
        ClassLoader save = cur.getContextClassLoader();
        cur.setContextClassLoader(RepositoryPlugin.getDefault().getClass().getClassLoader());
        try {
            Result result = (Result) getParser().fromXML(message);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            cur.setContextClassLoader(save);

        }
    }
    return null;
}

From source file:org.nuxeo.common.xmap.XMap.java

private static DocumentBuilderFactory initFactory() {
    Thread t = Thread.currentThread();
    ClassLoader cl = t.getContextClassLoader();
    t.setContextClassLoader(XMap.class.getClassLoader());
    try {//from  w  ww.  j  a  v a2s  .  c o m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory;
    } finally {
        t.setContextClassLoader(cl);
    }
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LuceneIndexEditorContext.java

static IndexWriterConfig getIndexWriterConfig(IndexDefinition definition, boolean remoteDir) {
    // FIXME: Hack needed to make Lucene work in an OSGi environment
    Thread thread = Thread.currentThread();
    ClassLoader loader = thread.getContextClassLoader();
    thread.setContextClassLoader(IndexWriterConfig.class.getClassLoader());
    try {/*  w  ww  .  ja  va  2  s  .co  m*/
        Analyzer definitionAnalyzer = definition.getAnalyzer();
        Map<String, Analyzer> analyzers = new HashMap<String, Analyzer>();
        analyzers.put(FieldNames.SPELLCHECK, new ShingleAnalyzerWrapper(LuceneIndexConstants.ANALYZER, 3));
        if (!definition.isSuggestAnalyzed()) {
            analyzers.put(FieldNames.SUGGEST, SuggestHelper.getAnalyzer());
        }
        Analyzer analyzer = new PerFieldAnalyzerWrapper(definitionAnalyzer, analyzers);
        IndexWriterConfig config = new IndexWriterConfig(VERSION, analyzer);
        if (remoteDir) {
            config.setMergeScheduler(new SerialMergeScheduler());
        }
        if (definition.getCodec() != null) {
            config.setCodec(definition.getCodec());
        }
        return config;
    } finally {
        thread.setContextClassLoader(loader);
    }
}