List of usage examples for org.apache.http.auth AuthScope ANY_PORT
int ANY_PORT
To view the source code for org.apache.http.auth AuthScope ANY_PORT.
Click Source Link
From source file:com.domuslink.communication.ApiHandler.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.//from w w w . j ava 2s . c om * * @param type The type of either a GET or POST for the request * @param commandURI The constructed URI for the path * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler) throws ApiException { HttpResponse response; HttpRequestBase request; if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string DefaultHttpClient client = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds); client.setCredentialsProvider(credsProvider); CookieStore cookieStore = cookieHandler.getCookieStore(); if (cookieStore != null) { boolean expiredCookies = false; Date nowTime = new Date(); for (Cookie theCookie : cookieStore.getCookies()) { if (theCookie.isExpired(nowTime)) expiredCookies = true; } if (!expiredCookies) client.setCookieStore(cookieStore); else { cookieHandler.setCookieStore(null); cookieStore = null; } } try { if (type == POST_TYPE) request = new HttpPost(commandURI); else request = new HttpGet(commandURI); request.setHeader("User-Agent", sUserAgent); response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { Log.e(TAG, "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString()); throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } if (cookieStore == null) { List<Cookie> realCookies = client.getCookieStore().getCookies(); if (!realCookies.isEmpty()) { BasicCookieStore newCookies = new BasicCookieStore(); for (int i = 0; i < realCookies.size(); i++) { newCookies.addCookie(realCookies.get(i)); // Log.d(TAG, "aCookie - " + realCookies.get(i).toString()); } cookieHandler.setCookieStore(newCookies); } } // Return result from buffered stream return content.toString(); } catch (IOException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } catch (IllegalArgumentException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java
@VisibleForTesting static RestTemplate buildRestTemplate(String adminUri, String user, String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... // auth cache BasicScheme basicAuth = new BasicScheme(); URI uri;/*from w w w . ja v a2 s .c o m*/ try { uri = new URI(adminUri); } catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return localContext; } }); restTemplate.setMessageConverters( Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter())); return restTemplate; }
From source file:org.opensaml.soap.client.http.AbstractPipelineHttpSOAPClient.java
/** * A convenience method to set a (single) username and password used for BASIC authentication. * To disable BASIC authentication pass null for the credentials instance. * /*from w ww .j a va 2 s .co m*/ * <p> * If the <code>authScope</code> is null, an {@link AuthScope} will be generated which specifies * any host, port, scheme and realm. * </p> * * <p>To specify multiple usernames and passwords for multiple host, port, scheme, and realm combinations, instead * provide an instance of {@link CredentialsProvider} via {@link #setCredentialsProvider(CredentialsProvider)}.</p> * * @param credentials the username and password credentials * @param scope the HTTP client auth scope with which to scope the credentials, may be null */ public void setBasicCredentialsWithScope(@Nullable final UsernamePasswordCredentials credentials, @Nullable final AuthScope scope) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); ComponentSupport.ifDestroyedThrowDestroyedComponentException(this); if (credentials != null) { AuthScope authScope = scope; if (authScope == null) { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(authScope, credentials); setCredentialsProvider(provider); } else { log.debug("Either username or password were null, disabling basic auth"); setCredentialsProvider(null); } }
From source file:com.googlecode.sardine.impl.SardineImpl.java
/** * @param username//from w ww. ja v a 2 s .c o m * Use in authentication header credentials * @param password * Use in authentication header credentials * @param domain * NTLM authentication * @param workstation * NTLM authentication */ public void setCredentials(String username, String password, String domain, String workstation) { if (username != null) { this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM), new NTCredentials(username, password, workstation, domain)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC), new UsernamePasswordCredentials(username, password)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); } }
From source file:net.sf.jasperreports.data.http.HttpDataService.java
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder) { String username = getUsername(parameters); if (username != null) { String password = getPassword(parameters); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); //FIXME proxy authentication? credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); }//w w w.j a va2 s.co m }
From source file:com.hp.saas.agm.rest.client.AliRestClient.java
@Override public void setHttpProxyCredentials(String username, String password) { Credentials cred = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); httpClient.getCredentialsProvider().setCredentials(scope, cred); }
From source file:org.artifactory.util.HttpClientConfigurator.java
/** * Configures preemptive authentication on this client. Ignores blank username input. *///from w ww .j a v a 2s . com public HttpClientConfigurator authentication(String username, String password, boolean allowAnyHost) { if (StringUtils.isNotBlank(username)) { if (StringUtils.isBlank(host)) { throw new IllegalStateException("Cannot configure authentication when host is not set."); } AuthScope authscope = allowAnyHost ? new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) : new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM); credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password)); builder.addInterceptorFirst(new PreemptiveAuthInterceptor()); } return this; }
From source file:org.opcfoundation.ua.transport.https.HttpsClient.java
/** * Initialize HttpsClient. /*from w w w . j a va 2 s .com*/ * * @param connectUrl * @param tcs */ public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx) throws ServiceResultException { this.connectUrl = connectUrl; this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri(); this.transportChannelSettings = tcs; HttpsSettings httpsSettings = tcs.getHttpsSettings(); HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies(); if (policies != null && policies.length > 0) securityPolicy = policies[policies.length - 1]; else securityPolicy = HttpsSecurityPolicy.TLS_1_1; // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri ); if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1 && securityPolicy != HttpsSecurityPolicy.TLS_1_2) throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed, "Https Client doesn't support securityPolicy " + securityPolicy); if (logger.isDebugEnabled()) { logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(), ObjectUtils.printFields(tcs)); } // Setup Encoder EndpointConfiguration endpointConfiguration = tcs.getConfiguration(); encoderCtx = ctx; encoderCtx.setMaxArrayLength( endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0); encoderCtx.setMaxStringLength( endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength() : 0); encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null ? endpointConfiguration.getMaxByteStringLength() : 0); encoderCtx.setMaxMessageSize( endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0); timer = TimerUtil.getTimer(); try { SchemeRegistry sr = new SchemeRegistry(); if (protocol.equals(UriUtil.SCHEME_HTTPS)) { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null); X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null ? httpsSettings.getHostnameVerifier() : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) { protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException { socket.setEnabledCipherSuites(cipherSuites); }; }; SSLEngine sslEngine = sslcontext.createSSLEngine(); String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites(); cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites, securityPolicy.getCipherSuites()); logger.info("Enabled protocols in SSL Engine are {}", Arrays.toString(sslEngine.getEnabledProtocols())); logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites)); logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(), Arrays.toString(cipherSuites)); Scheme https = new Scheme("https", 443, sf); sr.register(https); } if (protocol.equals(UriUtil.SCHEME_HTTP)) { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); sr.register(http); } if (ccm == null) { PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr); ccm = pccm; pccm.setMaxTotal(maxConnections); pccm.setDefaultMaxPerRoute(maxConnections); } BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, transportChannelSettings.getConfiguration().getOperationTimeout()); HttpConnectionParams.setSoTimeout(httpParams, 0); httpclient = new DefaultHttpClient(ccm, httpParams); // Set username and password authentication if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword())); httpclient.setCredentialsProvider(credsProvider); } } catch (NoSuchAlgorithmException e) { new ServiceResultException(e); } catch (KeyManagementException e) { new ServiceResultException(e); } }
From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java
public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username, String password, boolean preAuth) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = client.getCredentialsProvider(); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); BasicHttpContext httpContext = new BasicHttpContext(); if (preAuth) { AuthCache authCache = new BasicAuthCache(); authCache.put(httpHost, new BasicScheme()); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }/*from www . j av a 2 s.c om*/ return httpContext; } return null; }
From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username, String password, boolean preAuth) { // set Username and Password if (!StringUtil.isEmpty(username, true)) { if (password == null) password = ""; CredentialsProvider cp = new BasicCredentialsProvider(); builder.setDefaultCredentialsProvider(cp); cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); BasicHttpContext httpContext = new BasicHttpContext(); if (preAuth) { AuthCache authCache = new BasicAuthCache(); authCache.put(httpHost, new BasicScheme()); httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache); }// ww w . j av a2 s.co m return httpContext; } return null; }