List of usage examples for java.lang Thread setContextClassLoader
public void setContextClassLoader(ClassLoader cl)
From source file:org.batoo.jpa.community.test.BaseCoreTest.java
/** * Sets up the entity manager factory./* www. ja v a 2s.c om*/ * * @param puName * the persistence unit name * @return the entity manager factory * * @since 2.0.0 */ protected EntityManagerFactoryImpl setupEmf(String puName) { final Thread currentThread = Thread.currentThread(); if (this.oldContextClassLoader != null) { currentThread.setContextClassLoader(this.oldContextClassLoader); } this.oldContextClassLoader = currentThread.getContextClassLoader(); final TestClassLoader cl = new TestClassLoader(this.oldContextClassLoader); currentThread.setContextClassLoader(cl); cl.setRoot(this.getRootPackage()); return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(puName); }
From source file:org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java
public void afterPropertiesSet() throws Exception { Thread thread = Thread.currentThread(); ClassLoader cl = thread.getContextClassLoader(); try {//from ww w.j a v a 2s . c om thread.setContextClassLoader(classLoader); buildSessionFactory(); } finally { thread.setContextClassLoader(cl); } }
From source file:org.apache.hadoop.hbase.coprocessor.CoprocessorHost.java
/** * Load a coprocessor implementation into the host * @param path path to implementation jar * @param className the main class name/* w w w .j av a 2 s. com*/ * @param priority chaining priority * @param conf configuration for coprocessor * @throws java.io.IOException Exception */ public E load(Path path, String className, int priority, Configuration conf) throws IOException { Class<?> implClass = null; LOG.debug("Loading coprocessor class " + className + " with path " + path + " and priority " + priority); ClassLoader cl = null; if (path == null) { try { implClass = getClass().getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { throw new IOException("No jar path specified for " + className); } } else { cl = CoprocessorClassLoader.getClassLoader(path, getClass().getClassLoader(), pathPrefix, conf); try { implClass = cl.loadClass(className); } catch (ClassNotFoundException e) { throw new IOException("Cannot load external coprocessor class " + className, e); } } //load custom code for coprocessor Thread currentThread = Thread.currentThread(); ClassLoader hostClassLoader = currentThread.getContextClassLoader(); try { // switch temporarily to the thread classloader for custom CP currentThread.setContextClassLoader(cl); E cpInstance = loadInstance(implClass, priority, conf); return cpInstance; } finally { // restore the fresh (host) classloader currentThread.setContextClassLoader(hostClassLoader); } }
From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java
protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception { Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(classLoader); SecurityManager currentSecurityManager = System.getSecurityManager(); // Required to prevent premature exit by DBBuilder. See LPS-7524. SecurityManager securityManager = new SecurityManager() { public void checkPermission(Permission permission) { }//from ww w . jav a 2s.co m public void checkExit(int status) { throw new SecurityException(); } }; System.setSecurityManager(securityManager); try { System.setProperty("external-properties", "com/liferay/portal/tools/dependencies" + "/portal-tools.properties"); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger"); Class<?> clazz = classLoader.loadClass(toolClassName); Method method = clazz.getMethod("main", String[].class); method.invoke(null, (Object) args); } catch (InvocationTargetException ite) { if (ite.getCause() instanceof SecurityException) { } else { throw ite; } } finally { currentThread.setContextClassLoader(contextClassLoader); System.clearProperty("org.apache.commons.logging.Log"); System.setSecurityManager(currentSecurityManager); } }
From source file:org.rhq.enterprise.server.agent.EmbeddedAgentBootstrapService.java
public void executeAgentPromptCommand(final String command) { // all this funky threading/reflection is so we execute the command // in the isoloated context of the embedded agent final Exception[] error = new Exception[] { null }; final Runnable agentRunnable = new Runnable() { public void run() { try { Class<?> agentClass = agent.getClass(); Method agentMethod = agentClass.getMethod("executePromptCommand", new Class[] { String.class }); agentMethod.invoke(agent, new Object[] { command }); } catch (Throwable t) { error[0] = new Exception( "Cannot execute embedded agent prompt command [" + command + "]. Cause: " + t); }// w w w . j a v a 2s . c om } }; // create our thread that executes the agent command with the isolated class loader as its context Thread agentThread = new Thread(agentRunnable, "Embedded RHQ Agent Prompt Command"); agentThread.setDaemon(true); agentThread.setContextClassLoader(agent.getClass().getClassLoader()); agentThread.start(); try { agentThread.join(); if (error[0] == null) { log.info("Embedded agent executed the command [" + command + "] - see the embedded agent output file for the results"); } else { log.warn(error[0].toString()); } } catch (InterruptedException ignore) { } return; }
From source file:no.eris.applet.AppletViewer.java
/** * Runs the applet. Creates a Frame and adds it to it. * @param async whether to start a separate thread running the viewer. * @return the started thread or <code>null</code> when async is false *///from www .j av a2s.c om public Thread run(final boolean async) { overrideCookieHandler(manager); frame = new JFrame("AppletViewer"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { LOGGER.debug("windowClosing"); disposeResources(); } }); Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); // Instantiate the AppletAdapter which gives us // AppletStub and AppletContext. if (appletAdapter == null) appletAdapter = new AppletAdapter(this, attributes, params); // The AppletAdapter also gives us showStatus. // Therefore, must add() it very early on, since the Applet's // Constructor or its init() may use showStatus() cp.add(BorderLayout.SOUTH, appletAdapter); showStatus("Loading Applet "); if (loadFromLocalClasspath) { loadAppletLocaly(); } else { loadAppletRemotely(); } setAppletSize(); if (applet == null) { LOGGER.debug("applet null"); return null; } // Now right away, tell the Applet how to find showStatus et al. applet.setStub(appletAdapter); // Connect the Applet to the Frame. cp.add(BorderLayout.CENTER, applet); threadGroup = new ThreadGroup("AppletViewer-" + applet.getParameter("name") + "-FIXME_ID"); threadGroup.setDaemon(true); // Here we pretend to be a browser! final Runnable task = new Runnable() { public void run() { applet.init(); final Dimension d = applet.getSize(); d.height += appletAdapter.getSize().height; frame.setSize(d); frame.setVisible(true); // make the Frame and all in it appear applet.start(); showStatus("Applet " + applet.getParameter("name") + " loaded"); if (async) { waitForAppletToClose(); } } }; if (async) { Thread t = new Thread(threadGroup, task); final ClassLoader loader = applet.getClass().getClassLoader(); t.setContextClassLoader(loader); t.start(); return t; } else { task.run(); return null; } }
From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngine.java
@Override @SuppressWarnings("rawtypes") public String init(NamedList config, final SolrCore core) { this.core = core; String result = super.init(config, core); final SolrParams initParams = SolrParams.toSolrParams(config); // Initialization attributes for Carrot2 controller. HashMap<String, Object> initAttributes = new HashMap<>(); // Customize Carrot2's resource lookup to first look for resources // using Solr's resource loader. If that fails, try loading from the classpath. ResourceLookup resourceLookup = new ResourceLookup( // Solr-specific resource loading. new SolrResourceLocator(core, initParams), // Using the class loader directly because this time we want to omit the prefix new ClassLoaderLocator(core.getResourceLoader().getClassLoader())); DefaultLexicalDataFactoryDescriptor.attributeBuilder(initAttributes).resourceLookup(resourceLookup); // Make sure the requested Carrot2 clustering algorithm class is available String carrotAlgorithmClassName = initParams.get(CarrotParams.ALGORITHM); try {/*www . jav a2 s .c o m*/ this.clusteringAlgorithmClass = core.getResourceLoader().findClass(carrotAlgorithmClassName, IClusteringAlgorithm.class); } catch (SolrException s) { if (!(s.getCause() instanceof ClassNotFoundException)) { throw s; } } // Load Carrot2-Workbench exported attribute XMLs based on the 'name' attribute // of this component. This by-name convention lookup is used to simplify configuring algorithms. String componentName = initParams.get(ClusteringEngine.ENGINE_NAME); log.info("Initializing Clustering Engine '" + MoreObjects.firstNonNull(componentName, "<no 'name' attribute>") + "'"); if (!Strings.isNullOrEmpty(componentName)) { IResource[] attributeXmls = resourceLookup.getAll(componentName + "-attributes.xml"); if (attributeXmls.length > 0) { if (attributeXmls.length > 1) { log.warn("More than one attribute file found, first one will be used: " + Arrays.toString(attributeXmls)); } Thread ct = Thread.currentThread(); ClassLoader prev = ct.getContextClassLoader(); try { ct.setContextClassLoader(core.getResourceLoader().getClassLoader()); AttributeValueSets avs = AttributeValueSets.deserialize(attributeXmls[0].open()); AttributeValueSet defaultSet = avs.getDefaultAttributeValueSet(); initAttributes.putAll(defaultSet.getAttributeValues()); } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Could not read attributes XML for clustering component: " + componentName, e); } finally { ct.setContextClassLoader(prev); } } } // Extract solrconfig attributes, they take precedence. extractCarrotAttributes(initParams, initAttributes); // Customize the stemmer and tokenizer factories. The implementations we provide here // are included in the code base of Solr, so that it's possible to refactor // the Lucene APIs the factories rely on if needed. // Additionally, we set a custom lexical resource factory for Carrot2 that // will use both Carrot2 default stop words as well as stop words from // the StopFilter defined on the field. final AttributeBuilder attributeBuilder = BasicPreprocessingPipelineDescriptor .attributeBuilder(initAttributes); attributeBuilder.lexicalDataFactory(SolrStopwordsCarrot2LexicalDataFactory.class); if (!initAttributes.containsKey(BasicPreprocessingPipelineDescriptor.Keys.TOKENIZER_FACTORY)) { attributeBuilder.tokenizerFactory(LuceneCarrot2TokenizerFactory.class); } if (!initAttributes.containsKey(BasicPreprocessingPipelineDescriptor.Keys.STEMMER_FACTORY)) { attributeBuilder.stemmerFactory(LuceneCarrot2StemmerFactory.class); } // Pass the schema (via the core) to SolrStopwordsCarrot2LexicalDataFactory. initAttributes.put("solrCore", core); // Carrot2 uses current thread's context class loader to get // certain classes (e.g. custom tokenizer/stemmer) at initialization time. // To make sure classes from contrib JARs are available, // we swap the context class loader for the time of clustering. Thread ct = Thread.currentThread(); ClassLoader prev = ct.getContextClassLoader(); try { ct.setContextClassLoader(core.getResourceLoader().getClassLoader()); this.controller.init(initAttributes); } finally { ct.setContextClassLoader(prev); } SchemaField uniqueField = core.getLatestSchema().getUniqueKeyField(); if (uniqueField == null) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, CarrotClusteringEngine.class.getSimpleName() + " requires the schema to have a uniqueKeyField"); } this.idFieldName = uniqueField.getName(); return result; }
From source file:org.rhq.enterprise.server.agent.EmbeddedAgentBootstrapService.java
public void stopAgent() throws Exception { if (agent != null) { log.info("Stopping the embedded RHQ Agent..."); // all this funky threading/reflection is so we execute the command // in the isoloated context of the embedded agent final Exception[] error = new Exception[] { null }; final Runnable agentRunnable = new Runnable() { public void run() { try { agent.getClass().getMethod("shutdown", new Class[0]).invoke(agent, new Object[0]); } catch (Throwable t) { error[0] = new Exception("Failed to stop the embedded RHQ Agent. Cause: " + t); }/*from w ww . ja v a 2 s . c om*/ } }; // create our thread that executes the agent command with the isolated class loader as its context Thread agentThread = new Thread(agentRunnable, "Embedded RHQ Agent Shutdown Request"); agentThread.setDaemon(true); agentThread.setContextClassLoader(agent.getClass().getClassLoader()); agentThread.start(); try { agentThread.join(); } catch (InterruptedException ignore) { } if (error[0] == null) { agent = null; log.info("Embedded RHQ Agent has been stopped!"); } else { log.warn(error[0].toString()); throw error[0]; } return; } }
From source file:org.nuxeo.ecm.activity.ActivityStreamServiceImpl.java
protected void activatePersistenceProvider() { Thread thread = Thread.currentThread(); ClassLoader last = thread.getContextClassLoader(); try {/*from w w w .j a v a 2 s . c o m*/ thread.setContextClassLoader(PersistenceProvider.class.getClassLoader()); PersistenceProviderFactory persistenceProviderFactory = Framework .getLocalService(PersistenceProviderFactory.class); persistenceProvider = persistenceProviderFactory.newProvider(ACTIVITIES_PROVIDER); persistenceProvider.openPersistenceUnit(); } finally { thread.setContextClassLoader(last); } }
From source file:org.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java
@Override public SessionFactory buildSessionFactory() throws HibernateException { // set the class loader to load Groovy classes if (grailsApplication != null) { LOG.debug("[GrailsAnnotationConfiguration] Setting context class loader to Grails GroovyClassLoader"); Thread.currentThread().setContextClassLoader(grailsApplication.getClassLoader()); }// www .jav a 2 s. c o m // work around for HHH-2624 Map<String, Type> empty = new HashMap<String, Type>(); addFilterDefinition(new FilterDefinition("dynamicFilterEnabler", "1=1", empty)); SessionFactory sessionFactory = null; ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER); Thread currentThread = Thread.currentThread(); ClassLoader threadContextClassLoader = currentThread.getContextClassLoader(); boolean overrideClassLoader = (appClassLoader != null && !appClassLoader.equals(threadContextClassLoader)); if (overrideClassLoader) { currentThread.setContextClassLoader(appClassLoader); } try { ConfigurationHelper.resolvePlaceHolders(getProperties()); EventListenerIntegrator eventListenerIntegrator = new EventListenerIntegrator(hibernateEventListeners, eventListeners); BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder() .with(eventListenerIntegrator).build(); setSessionFactoryObserver(new SessionFactoryObserver() { private static final long serialVersionUID = 1; public void sessionFactoryCreated(SessionFactory factory) { } public void sessionFactoryClosed(SessionFactory factory) { ((ServiceRegistryImplementor) serviceRegistry).destroy(); } }); StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry).applySettings(getProperties()); sessionFactory = super.buildSessionFactory(standardServiceRegistryBuilder.build()); serviceRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry(); } finally { if (overrideClassLoader) { currentThread.setContextClassLoader(threadContextClassLoader); } } if (grailsApplication != null) { GrailsHibernateUtil.configureHibernateDomainClasses(sessionFactory, sessionFactoryBeanName, grailsApplication); } return sessionFactory; }