Example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider.

Prototype

public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider) 

Source Link

Document

Assigns default CredentialsProvider instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:edu.emory.bmi.medicurator.tcia.TciaQuery.java

private HttpClient getInsecureClient() throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }/*from  w  ww  .  ja  v  a2  s  . c om*/
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSSLSocketFactory(sslsf);
    if (Constants.PROXY_HOST != null && Constants.PROXY_PORT != null) {
        HttpHost proxy = new HttpHost(Constants.PROXY_HOST, Constants.PROXY_PORT, "http");
        builder.setProxy(proxy);
    }
    if (Constants.PROXY_USERNAME != null && Constants.PROXY_PASSWORD != null) {
        Credentials credentials = new UsernamePasswordCredentials(Constants.PROXY_USERNAME,
                Constants.PROXY_PASSWORD);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, credentials);
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:com.polydeucesys.eslogging.core.jest.JestHttpConnection.java

private JestClientFactory setupDefaultClientFactory() {
    JestClientFactory factory = new JestClientFactory();
    if (getClientCredentialConfig() != null) {
        factory = new JestClientFactory() {
            @Override/*from   ww  w.ja  v a2  s. c  o m*/
            protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder) {
                HttpClientCredentialConfig credConfig = getClientCredentialConfig();
                CredentialsProvider baseProvider = new BasicCredentialsProvider();
                AuthScope scope = new AuthScope(credConfig.getAuthScopeHost(), credConfig.getAuthScopePort(),
                        credConfig.getAuthScopeRealm());

                baseProvider.setCredentials(scope, credConfig.getCredentials());
                builder.setDefaultCredentialsProvider(baseProvider);
                return builder;
            }
        };
    }
    return factory;
}

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)//from w w  w .  jav  a  2  s  .  c o m
public HttpClientBuilder prepare(@Nullable final Customizer customizer) {
    final HttpClientPlan plan = httpClientPlan();

    // attach connection manager early, so customizer has chance to replace it if needed
    plan.getClient().setConnectionManager(sharedConnectionManager);

    // apply defaults
    defaultsCustomizer.customize(plan);

    // apply globals
    new ConfigurationCustomizer(getConfigurationInternal()).customize(plan);

    // apply instance customization
    if (customizer != null) {
        customizer.customize(plan);
    }

    // apply plan to builder
    HttpClientBuilder builder = plan.getClient();
    // User agent must be set here to apply to all apache http requests, including over proxies
    String userAgent = plan.getUserAgent();
    if (userAgent != null) {
        setUserAgent(builder, userAgent);
    }
    builder.setDefaultConnectionConfig(plan.getConnection().build());
    builder.setDefaultSocketConfig(plan.getSocket().build());
    builder.setDefaultRequestConfig(plan.getRequest().build());
    builder.setDefaultCredentialsProvider(plan.getCredentials());

    builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> {
        // add custom http-context attributes
        for (Entry<String, Object> entry : plan.getAttributes().entrySet()) {
            // only set context attribute if not already set, to allow per request overrides
            if (context.getAttribute(entry.getKey()) == null) {
                context.setAttribute(entry.getKey(), entry.getValue());
            }
        }

        // add custom http-request headers
        for (Entry<String, String> entry : plan.getHeaders().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    });
    builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
        if (outboundLog.isDebugEnabled()) {
            httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted());
            httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext));
            outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine());
        }
    });
    builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> {
        Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH);
        if (stopwatch != null) {
            outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI),
                    httpResponse.getStatusLine(), stopwatch);
        }
    });

    return builder;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java

@Override
public HttpClient get() {
    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnPerRoute(maxConnectionPerRoute)
            .setMaxConnTotal(maxTotalConnection);

    if (proxy.getProxyUrl() != null) {
        URL url = proxy.getProxyUrl();
        builder.setProxy(new HttpHost(url.getHost(), url.getPort()));
        if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxy.getUsername(),
                    proxy.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);
            builder.setDefaultCredentialsProvider(credsProvider);
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }/*w  w  w  .ja  va  2  s  .c o m*/
    }

    return builder.build();
}

From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java

/**
 * Create http client/* w  w w. ja  v a  2  s.  c o  m*/
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (props.getProperty("http.proxyHost") != null) {
            httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                    Integer.parseInt(props.getProperty("http.proxyPort"))));
        }

        if (props.getProperty("http.proxyUser") != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                    props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        httpClient = httpClientBuilder.build();
    }

    return httpClient;
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);//from  ww  w  .j  a  va2 s  .  c  o  m
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    httpclient.setDefaultCredentialsProvider(credentialsProvider);

    configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create();
        authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build());
        configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build());
    httpclient.setDefaultRequestConfig(
            RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build());
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectTimeout())
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setStaleConnectionCheckEnabled(true)
                .setProxy(myProxy).build();

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }/*from w  ww .  j  a  v a2s  . c  om*/

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort),
                new UsernamePasswordCredentials(_login, _password));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {//  w w  w  . ja  v  a2 s. c o m
        if (_logger.isWarnEnabled()) {
            _logger.warn("Login and password are required");
        }
    }

    try {
        setProxyHost(httpClientBuilder);

        _closeableHttpClient = httpClientBuilder.build();

        if (_logger.isDebugEnabled()) {
            _logger.debug("Configured client for " + _protocol + "://" + _hostName);
        }
    } catch (Exception e) {
        _logger.error("Unable to configure client", e);
    }
}