List of usage examples for java.lang Thread getContextClassLoader
@CallerSensitive
public ClassLoader getContextClassLoader()
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./* w w w.j a va 2 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:org.openmrs.util.MemoryLeakUtil.java
public static void shutdownKeepAliveTimer() { try {//from w w w .j a v a2 s .c o 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:br.com.riselabs.cotonet.model.db.Database.java
public static Connection getConnection() { Thread currentThread = Thread.currentThread(); ClassLoader classloader = currentThread.getContextClassLoader(); InputStream input = classloader.getResourceAsStream("db.properties"); Properties prop = new Properties(); try {/* w w w . ja v a2 s .c om*/ if (input != null) { prop.load(input); input.close(); } else { Logger.logStackTrace(new FileNotFoundException("The file 'db.properties was not found.")); } } catch (IOException e) { Logger.logStackTrace(e); } String db = prop.getProperty("database.name"); String user = prop.getProperty("database.user"); String pass = prop.getProperty("database.password"); return getConnection(db, user, pass); }
From source file:Main.java
/** * <P>Attempts to find the most suitable {@link ClassLoader} as follows:</P> * <UL>// w w w.j av a 2s .c o m * <LI><P> * Check the {@link Thread#getContextClassLoader()} value * </P></LI> * * <LI><P> * If no thread context class loader then check the anchor * class (if given) for its class loader * </P></LI> * * <LI><P> * If still no loader available, then use {@link ClassLoader#getSystemClassLoader()} * </P></LI> * </UL> * * @param anchor The anchor {@link Class} to use if no current thread * - ignored if {@code null} * context class loader * @return The resolver {@link ClassLoader} */ public static ClassLoader resolveDefaultClassLoader(Class<?> anchor) { Thread thread = Thread.currentThread(); ClassLoader cl = thread.getContextClassLoader(); if (cl != null) { return cl; } if (anchor != null) { cl = anchor.getClassLoader(); } if (cl == null) { // can happen for core Java classes cl = ClassLoader.getSystemClassLoader(); } return cl; }
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 w w w .ja va 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:edu.wisc.nexus.auth.rut.realm.NexusSecurityTestCaseSupport.java
public static void copyFile(File destDir, String dir, String filename) throws IOException { final File confDir; if (dir != null && dir.length() > 0) { if (!dir.endsWith("/")) { dir = dir + "/"; }/*from www . j a va 2 s . c o m*/ confDir = new File(destDir, dir); confDir.mkdirs(); } else { dir = ""; confDir = destDir; } final Thread currentThread = Thread.currentThread(); final ClassLoader contextClassLoader = currentThread.getContextClassLoader(); final String src = dir + filename; final InputStream fileStream = contextClassLoader.getResourceAsStream(src); final File dest = new File(confDir, filename); try { FileUtils.copyStreamToFile(new RawInputStreamFacade(fileStream), dest); } catch (Exception e) { throw new IOException("Failed to copy " + src + " to " + dest, e); } finally { IOUtils.closeQuietly(fileStream); } }
From source file:com.liferay.portal.test.TestUtil.java
private static void setPortletClassLoader() { //Had to add this for GA2 Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); PortletClassLoaderUtil.setClassLoader(contextClassLoader); }
From source file:org.carewebframework.ui.util.MemoryLeakPreventionUtil.java
/** * CWI-1409/*from w w w .jav a 2 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:com.liferay.portal.util.InitUtil.java
public static synchronized void init() { if (_initialized) { return;//from ww w .j a va 2 s . c om } StopWatch stopWatch = null; if (_PRINT_TIME) { stopWatch = new StopWatch(); stopWatch.start(); } // Set the default locale used by Liferay. This locale is no longer set // at the VM level. See LEP-2584. String userLanguage = SystemProperties.get("user.language"); String userCountry = SystemProperties.get("user.country"); String userVariant = SystemProperties.get("user.variant"); LocaleUtil.setDefault(userLanguage, userCountry, userVariant); // Set the default time zone used by Liferay. This time zone is no // longer set at the VM level. See LEP-2584. String userTimeZone = SystemProperties.get("user.timezone"); TimeZoneUtil.setDefault(userTimeZone); // Shared class loader try { Thread currentThread = Thread.currentThread(); PortalClassLoaderUtil.setClassLoader(currentThread.getContextClassLoader()); } catch (Exception e) { e.printStackTrace(); } // Log4J if (GetterUtil.getBoolean(SystemProperties.get("log4j.configure.on.startup"), true)) { ClassLoader classLoader = InitUtil.class.getClassLoader(); Log4JUtil.configureLog4J(classLoader.getResource("META-INF/portal-log4j.xml")); try { Log _log = LogFactoryUtil.getLog(InitUtil.class); String configName = "META-INF/portal-log4j-ext.xml"; Enumeration<URL> configs = classLoader.getResources(configName); if (_log.isDebugEnabled() && !configs.hasMoreElements()) { _log.debug("No " + configName + " has been found"); } while (configs.hasMoreElements()) { URL config = configs.nextElement(); Log4JUtil.configureLog4J(config); } } catch (Exception e) { e.printStackTrace(); } } // Shared log try { LogFactoryUtil.setLogFactory(new Log4jLogFactoryImpl()); } catch (Exception e) { e.printStackTrace(); } // Cache registry CacheRegistryUtil.setCacheRegistry(new CacheRegistryImpl()); // Configuration factory ConfigurationFactoryUtil.setConfigurationFactory(new ConfigurationFactoryImpl()); // Data source factory DataSourceFactoryUtil.setDataSourceFactory(new DataSourceFactoryImpl()); // DB factory DBFactoryUtil.setDBFactory(new DBFactoryImpl()); // Java properties JavaProps.isJDK5(); // ROME XmlReader.setDefaultEncoding(StringPool.UTF8); if (_PRINT_TIME) { System.out.println("InitAction takes " + stopWatch.getTime() + " ms"); } _initialized = true; }
From source file:at.molindo.utils.reflect.ClassUtils.java
/** * @param thread/* w w w.j ava 2 s. co m*/ * {@link Thread} to use for * {@link Thread#getContextClassLoader() context ClassLoader} or * <code>null</code> for {@link Thread#currentThread() current * thread} * @param fallback * {@link ClassLoader} providing class if no context classloader * or <code>null</code> for this class * @return never <code>null</code> */ public static ClassLoader getClassLoader(Thread thread, Class<?> fallback) { if (thread == null) { thread = Thread.currentThread(); } ClassLoader loader = thread.getContextClassLoader(); if (loader == null) { loader = (fallback != null ? fallback : ClassUtils.class).getClassLoader(); } if (loader == null) { ClassLoader.getSystemClassLoader(); } return loader; }