List of usage examples for org.apache.http.impl.client DefaultHttpClient setCredentialsProvider
public synchronized void setCredentialsProvider(final CredentialsProvider credsProvider)
From source file:org.modeshape.test.kit.JBossASKitIT.java
@Test public void webApplicationsShouldBeAccessible() throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setCredentialsProvider(new BasicCredentialsProvider() { @Override/*from www .j a v a2 s.co m*/ public Credentials getCredentials(AuthScope authscope) { //defined via modeshape-user and modeshape-roles return new UsernamePasswordCredentials("admin", "admin"); } }); assertURIisAccessible("http://localhost:8080/modeshape-webdav", httpClient); assertURIisAccessible("http://localhost:8080/modeshape-rest", httpClient); assertURIisAccessible("http://localhost:8080/modeshape-cmis", httpClient); assertURIisAccessible("http://localhost:8080/modeshape-explorer", httpClient); }
From source file:com.sun.jersey.client.apache4.ApacheHttpClient4.java
/** * Create a default Apache HTTP client handler. * * @param cc ClientConfig instance. Might be null. * * @return a default Apache HTTP client handler. *///from w ww . jav a 2 s . com private static ApacheHttpClient4Handler createDefaultClientHandler(final ClientConfig cc) { Object connectionManager = null; Object httpParams = null; if (cc != null) { connectionManager = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER); if (connectionManager != null) { if (!(connectionManager instanceof ClientConnectionManager)) { Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING, "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER + " (" + connectionManager.getClass().getName() + ") - not instance of org.apache.http.conn.ClientConnectionManager."); connectionManager = null; } } httpParams = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS); if (httpParams != null) { if (!(httpParams instanceof HttpParams)) { Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING, "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS + " (" + httpParams.getClass().getName() + ") - not instance of org.apache.http.params.HttpParams."); httpParams = null; } } } final DefaultHttpClient client = new DefaultHttpClient((ClientConnectionManager) connectionManager, (HttpParams) httpParams); CookieStore cookieStore = null; boolean preemptiveBasicAuth = false; if (cc != null) { for (Map.Entry<String, Object> entry : cc.getProperties().entrySet()) client.getParams().setParameter(entry.getKey(), entry.getValue()); if (cc.getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES)) client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); Object credentialsProvider = cc.getProperty(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER); if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) { client.setCredentialsProvider((CredentialsProvider) credentialsProvider); } final Object proxyUri = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme()); if (cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME) && cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD)) { client.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), u.getPort()), new UsernamePasswordCredentials( cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME).toString(), cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD).toString())); } client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } preemptiveBasicAuth = cc .getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION); } if (client.getParams().getParameter(ClientPNames.COOKIE_POLICY) == null || !client.getParams() .getParameter(ClientPNames.COOKIE_POLICY).equals(CookiePolicy.IGNORE_COOKIES)) { cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); } return new ApacheHttpClient4Handler(client, cookieStore, preemptiveBasicAuth); }
From source file:org.valkyriercp.security.remoting.BasicAuthCommonsHttpInvokerProxyFactoryBean.java
/** * Handle a change in the current authentication token. * This method will fail fast if the executor isn't a CommonsHttpInvokerRequestExecutor. * @see org.valkyriercp.security.AuthenticationAware#setAuthenticationToken(org.springframework.security.core.Authentication) *//*w w w.ja v a2s .c o m*/ public void setAuthenticationToken(Authentication authentication) { if (logger.isDebugEnabled()) { logger.debug("New authentication token: " + authentication); } HttpComponentsHttpInvokerRequestExecutor executor = (HttpComponentsHttpInvokerRequestExecutor) getHttpInvokerRequestExecutor(); DefaultHttpClient httpClient = (DefaultHttpClient) executor.getHttpClient(); BasicCredentialsProvider provider = new BasicCredentialsProvider(); httpClient.setCredentialsProvider(provider); httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor()); UsernamePasswordCredentials usernamePasswordCredentials; if (authentication != null) { usernamePasswordCredentials = new UsernamePasswordCredentials(authentication.getName(), authentication.getCredentials().toString()); } else { usernamePasswordCredentials = null; } provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials); }
From source file:net.seedboxer.seedroid.utils.RestClient.java
private void executeRequest(HttpUriRequest request, String url) { DefaultHttpClient client = new DefaultHttpClient(); if (credProvider != null) { client.setCredentialsProvider(credProvider); }/*w w w . j a v a2 s . com*/ HttpResponse httpResponse; try { httpResponse = client.execute(request); responseCode = httpResponse.getStatusLine().getStatusCode(); message = httpResponse.getStatusLine().getReasonPhrase(); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); response = convertStreamToString(instream); // Closing the input stream will trigger connection release instream.close(); } } catch (ClientProtocolException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } catch (IOException e) { client.getConnectionManager().shutdown(); e.printStackTrace(); } }
From source file:com.googlecode.sardine.AuthenticationTest.java
@Test public void testBasicPreemptiveAuth() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); final CountDownLatch count = new CountDownLatch(1); client.setCredentialsProvider(new BasicCredentialsProvider() { @Override//from www . jav a 2 s. c o m public Credentials getCredentials(AuthScope authscope) { // Set flag that credentials have been used indicating preemptive authentication count.countDown(); return new Credentials() { public Principal getUserPrincipal() { return new BasicUserPrincipal("anonymous"); } public String getPassword() { return "invalid"; } }; } }); SardineImpl sardine = new SardineImpl(client); URI url = URI.create("http://sudo.ch/dav/basic/"); //Send basic authentication header in initial request sardine.enablePreemptiveAuthentication(url.getHost()); try { sardine.list(url.toString()); fail("Expected authorization failure"); } catch (SardineException e) { // Expect Authorization Failed assertEquals(401, e.getStatusCode()); // Make sure credentials have been queried assertEquals("No preemptive authentication attempt", 0, count.getCount()); } }
From source file:org.apache.olingo.client.core.http.NTLMAuthHttpClientFactory.java
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final DefaultHttpClient httpclient = super.create(method, uri); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(username, password, workstation, domain)); httpclient.setCredentialsProvider(credsProvider); return httpclient; }
From source file:ua.pp.msk.cliqr.GetProcessorImpl.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);/*from w ww . java2 s.co m*/ UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new CliQrRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:ua.pp.msk.gradle.http.Client.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);// ww w . j a v a 2 s . com UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new NexusHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new NexusRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:org.springframework.data.solr.server.support.SolrServerUtilTests.java
/** * @see DATASOLR-189/*from w ww . ja v a 2s .c o m*/ */ @Test public void cloningLBHttpSolrServerShouldCopyCredentialsProviderCorrectly() { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar")); DefaultHttpClient client = new DefaultHttpClient(); client.setCredentialsProvider(credentialsProvider); LBHttpSolrServer lbSolrServer = new LBHttpSolrServer(client, BASE_URL, ALTERNATE_BASE_URL); LBHttpSolrServer cloned = SolrServerUtils.clone(lbSolrServer, CORE_NAME); Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(), IsEqual.<CredentialsProvider>equalTo(credentialsProvider)); }
From source file:org.springframework.data.solr.server.support.SolrServerUtilTests.java
/** * @see DATASOLR-189//from ww w . ja v a 2 s .c om */ @Test public void cloningHttpSolrServerShouldCopyCredentialsProviderCorrectly() { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar")); DefaultHttpClient client = new DefaultHttpClient(); client.setCredentialsProvider(credentialsProvider); HttpSolrServer solrServer = new HttpSolrServer(BASE_URL, client); HttpSolrServer cloned = SolrServerUtils.clone(solrServer); Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(), IsEqual.<CredentialsProvider>equalTo(credentialsProvider)); }