List of usage examples for java.lang Thread setContextClassLoader
public void setContextClassLoader(ClassLoader cl)
From source file:com.icesoft.util.ThreadFactory.java
public Thread newThread(final Runnable runnable) { Thread _thread; synchronized (lock) { _thread = new Thread(runnable, prefix + " [" + ++counter + "]"); }// www. ja v a 2 s. c o m _thread.setDaemon(daemon); try { /* * We attempt to set the context class loader because some J2EE * containers don't seem to set this properly, which leads to * important classes not being found. However, other J2EE containers * see this as a security violation. */ _thread.setContextClassLoader(runnable.getClass().getClassLoader()); } catch (SecurityException exception) { /* * If the current security policy does not allow this, we have to * hope that the appropriate class loader settings were transferred * to this new thread. */ if (LOG.isTraceEnabled()) { LOG.trace("Setting the context class loader is not permitted.", exception); } } if (LOG.isDebugEnabled()) { LOG.debug("New thread: " + _thread.getName()); } return _thread; }
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 w ww .j a v a 2 s.c o m 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.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML1BearerGrantHandler.java
public void init() throws IdentityOAuth2Exception { super.init(); Thread thread = Thread.currentThread(); ClassLoader loader = thread.getContextClassLoader(); thread.setContextClassLoader(this.getClass().getClassLoader()); try {/* w w w . j a va 2s . com*/ DefaultBootstrap.bootstrap(); } catch (ConfigurationException e) { String errorMessage = "Error in bootstrapping the OpenSAML library"; log.error(errorMessage, e); throw new IdentityOAuth2Exception(errorMessage, e); } finally { thread.setContextClassLoader(loader); } profileValidator = new SAMLSignatureProfileValidator(); Properties grantTypeProperties = new Properties(); InputStream stream = loader.getResourceAsStream("repository/conf/" + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE); if (stream != null) { try { grantTypeProperties.load(stream); audienceRestrictionValidationEnabled = Boolean .parseBoolean(grantTypeProperties.getProperty("audienceRestrictionValidationEnabled")); if (log.isDebugEnabled()) { log.debug("Audience restriction validation enabled is set to " + audienceRestrictionValidationEnabled); } } catch (IOException e) { log.warn( "Failed to load the SAML-1.0-BearerGrantType.properties stream. The default configurations are " + "used instead of configurations defined in " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE + " file."); } finally { try { stream.close(); } catch (IOException e) { log.warn("Failed to close the input stream of " + SAML10_BEARER_GRANT_TYPE_CONFIG_FILE, e); } } } }
From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java
@Nonnull @Override// w w w. j a v a 2 s . c om public ClassLoader getClassLoader() { // Get current context class loader final Thread currentThread = Thread.currentThread(); final ClassLoader contextClassLoader = currentThread.getContextClassLoader(); // Get interpreter class loader from context getInterpreter().setContextClassLoader(); final ClassLoader interpreterClassLoader = currentThread.getContextClassLoader(); // Reset context currentThread.setContextClassLoader(contextClassLoader); return interpreterClassLoader; }
From source file:com.liferay.portal.search.elasticsearch.internal.connection.EmbeddedElasticsearchConnection.java
protected Node createNode(Settings settings) { Thread thread = Thread.currentThread(); ClassLoader contextClassLoader = thread.getContextClassLoader(); Class<?> clazz = getClass(); thread.setContextClassLoader(clazz.getClassLoader()); String jnaTmpDir = System.getProperty("jna.tmpdir"); System.setProperty("jna.tmpdir", _jnaTmpDirName); try {/*from w w w .j a v a 2 s . c om*/ NodeBuilder nodeBuilder = new NodeBuilder(); nodeBuilder.settings(settings); nodeBuilder.local(true); Node node = nodeBuilder.build(); if (elasticsearchConfiguration.syncSearch()) { Injector injector = node.injector(); _replaceTransportRequestHandler(injector.getInstance(TransportService.class), injector.getInstance(SearchService.class)); } return node; } finally { thread.setContextClassLoader(contextClassLoader); if (jnaTmpDir == null) { System.clearProperty("jna.tmpdir"); } else { System.setProperty("jna.tmpdir", jnaTmpDir); } } }
From source file:org.opencastproject.authorization.xacml.XACMLAuthorizationService.java
/** * {@inheritDoc}//from w ww . j a va 2s . c o m * * @see org.opencastproject.security.api.AuthorizationService#getAccessControlList(org.opencastproject.mediapackage.MediaPackage) */ @SuppressWarnings("unchecked") @Override public AccessControlList getAccessControlList(MediaPackage mediapackage) { Thread currentThread = Thread.currentThread(); ClassLoader originalClassLoader = currentThread.getContextClassLoader(); try { currentThread.setContextClassLoader(XACMLAuthorizationService.class.getClassLoader()); Attachment[] xacmlAttachments = mediapackage.getAttachments(MediaPackageElements.XACML_POLICY); URI xacmlUri = null; if (xacmlAttachments.length == 0) { logger.debug("No XACML attachment found in {}", mediapackage); return getFallbackAcl(mediapackage); } else if (xacmlAttachments.length > 1) { // try to find the source policy. Some may be copies sent to distribution channels. for (Attachment a : xacmlAttachments) { if (a.getReference() == null) { if (xacmlUri == null) { xacmlUri = a.getURI(); } else { logger.warn("More than one non-referenced XACML policy is attached to {}.", mediapackage); return getFallbackAcl(mediapackage); } } } if (xacmlUri == null) { logger.warn("Multiple XACML policies are attached to {}, and none seem to be authoritative.", mediapackage); return getFallbackAcl(mediapackage); } } else { xacmlUri = xacmlAttachments[0].getURI(); } File xacmlPolicyFile = null; try { xacmlPolicyFile = workspace.get(xacmlUri); } catch (NotFoundException e) { logger.warn("XACML policy file not found '{}'.", xacmlUri); return getFallbackAcl(mediapackage); } catch (IOException e) { logger.error("Unable to access XACML policy file. {}", xacmlPolicyFile, e); return getFallbackAcl(mediapackage); } FileInputStream in; try { in = new FileInputStream(xacmlPolicyFile); } catch (FileNotFoundException e) { throw new IllegalStateException("Unable to find file in the workspace: " + xacmlPolicyFile); } PolicyType policy = null; try { policy = ((JAXBElement<PolicyType>) XACMLUtils.jBossXacmlJaxbContext.createUnmarshaller() .unmarshal(in)).getValue(); } catch (JAXBException e) { throw new IllegalStateException("Unable to unmarshall xacml document" + xacmlPolicyFile); } finally { IoSupport.closeQuietly(in); } AccessControlList accessControlList = new AccessControlList(); List<AccessControlEntry> acl = accessControlList.getEntries(); for (Object object : policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) { if (object instanceof RuleType) { RuleType rule = (RuleType) object; if (rule.getTarget() == null) { continue; } ActionType action = rule.getTarget().getActions().getAction().get(0); String actionForAce = (String) action.getActionMatch().get(0).getAttributeValue().getContent() .get(0); String role = null; JAXBElement<ApplyType> apply = (JAXBElement<ApplyType>) rule.getCondition().getExpression(); for (JAXBElement<?> element : apply.getValue().getExpression()) { if (element.getValue() instanceof AttributeValueType) { role = (String) ((AttributeValueType) element.getValue()).getContent().get(0); break; } } if (role == null) { logger.warn("Unable to find a role in rule {}", rule); continue; } AccessControlEntry ace = new AccessControlEntry(role, actionForAce, rule.getEffect().equals(EffectType.PERMIT)); acl.add(ace); } else { logger.debug("Skipping {}", object); } } return accessControlList; } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } }
From source file:org.eclipse.hudson.init.InitialSetup.java
public void invokeHudson(boolean restart) { final WebAppController controller = WebAppController.get(); if (initialClassLoader == null) { initialClassLoader = getClass().getClassLoader(); }/* w w w . ja va 2s . co m*/ Class hudsonIsLoadingClass; try { outerClassLoader = new OuterClassLoader(initialClassLoader); hudsonIsLoadingClass = outerClassLoader.loadClass("hudson.util.HudsonIsLoading"); HudsonIsLoading hudsonIsLoading = (HudsonIsLoading) hudsonIsLoadingClass.newInstance(); Class runnableClass = outerClassLoader.loadClass("org.eclipse.hudson.init.InitialRunnable"); Constructor ctor = runnableClass.getDeclaredConstructors()[0]; ctor.setAccessible(true); InitialRunnable initialRunnable = (InitialRunnable) ctor.newInstance(controller, logger, hudsonHomeDir, servletContext, restart); controller.install(hudsonIsLoading); Thread initThread = new Thread(initialRunnable, "hudson initialization thread " + (++highInitThreadNumber)); initThread.setContextClassLoader(outerClassLoader); initThread.start(); } catch (Exception ex) { logger.error("Hudson failed to load!!!", ex); } /** Above replaces these lines controller.install(new HudsonIsLoading()); new Thread("hudson initialization thread") { }.start(); */ }
From source file:org.atm.mvn.run.JavaBootstrap.java
/** * Run the main method in the class using the specified class path. * /*from w ww .j a v a 2s .c om*/ * @throws Exception * Any exceptions that might occur. */ public void run() throws Exception { Thread currentThread = Thread.currentThread(); ClassLoader existingClassLoader = currentThread.getContextClassLoader(); try { /* * Replace the current class loader with one with all of the needed * dependencies. */ ClassLoader bootstrapClassLoader = createClassLoader(ClassLoader.getSystemClassLoader(), false); currentThread.setContextClassLoader(bootstrapClassLoader); // find the java class Class<?> mainClass = resolveClass(bootstrapClassLoader); // find the main method Method mainMethod = resolveMainMethod(mainClass); // invoke the main method invokeMain(mainMethod); } finally { currentThread.setContextClassLoader(existingClassLoader); } }
From source file:com.buaa.cfs.security.UserGroupInformation.java
private static LoginContext newLoginContext(String appName, Subject subject, javax.security.auth.login.Configuration loginConf) throws LoginException { // Temporarily switch the thread's ContextClassLoader to match this // class's classloader, so that we can properly load HadoopLoginModule // from the JAAS libraries. Thread t = Thread.currentThread(); ClassLoader oldCCL = t.getContextClassLoader(); t.setContextClassLoader(HadoopLoginModule.class.getClassLoader()); try {//ww w . j a v a 2 s . c o m return new LoginContext(appName, subject, null, loginConf); } finally { t.setContextClassLoader(oldCCL); } }
From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngine.java
@Override public Object cluster(Query query, SolrDocumentList solrDocList, Map<SolrDocument, Integer> docIds, SolrQueryRequest sreq) {// w w w. j a v a 2 s . com try { // Prepare attributes for Carrot2 clustering call Map<String, Object> attributes = new HashMap<>(); List<Document> documents = getDocuments(solrDocList, docIds, query, sreq); attributes.put(AttributeNames.DOCUMENTS, documents); attributes.put(AttributeNames.QUERY, query.toString()); // Pass the fields on which clustering runs. attributes.put("solrFieldNames", getFieldsForClustering(sreq)); // Pass extra overriding attributes from the request, if any extractCarrotAttributes(sreq.getParams(), attributes); // Perform clustering and convert to an output structure of clusters. // // Carrot2 uses current thread's context class loader to get // certain classes (e.g. custom tokenizer/stemmer) at runtime. // 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()); return clustersToNamedList(controller.process(attributes, clusteringAlgorithmClass).getClusters(), sreq.getParams()); } finally { ct.setContextClassLoader(prev); } } catch (Exception e) { log.error("Carrot2 clustering failed", e); throw new SolrException(ErrorCode.SERVER_ERROR, "Carrot2 clustering failed", e); } }