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:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

/**
 * Define the Credentials/*w w w .  jav  a  2 s .  c om*/
 *
 * @param httpClientBuilder
 * @param url
 * @return
 */
private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url)
        throws DSSException {

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry : authenticationMap.entrySet()) {

        final HttpHost httpHost = entry.getKey();
        final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
        final AuthScope authscope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
        credentialsProvider.setCredentials(authscope, usernamePasswordCredentials);
    }
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credentialsProvider, url);
    return httpClientBuilder;
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ClientCredentials} and optional {@code Proxy}
 * configuration./*  w  ww.  j  a v  a2  s.c o m*/
 * @param clientCredentials the Okta account API Key that will be used to authenticate the client with Okta's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Okta API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Okta API server.
 *                             If null, then SSWS will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Okta configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:com.stormpath.sdk.impl.http.httpclient.HttpClientRequestExecutor.java

/**
 * Creates a new {@code HttpClientRequestExecutor} using the specified {@code ApiKey} and optional {@code Proxy}
 * configuration.//w  w  w .j  a  v  a  2s  .c o  m
 * @param clientCredentials the Stormpath account API Key that will be used to authenticate the client with Stormpath's API sever
 * @param proxy the HTTP proxy to be used when communicating with the Stormpath API server (can be null)
 * @param authenticationScheme the HTTP authentication scheme to be used when communicating with the Stormpath API server.
 *                             If null, then Sauthc1 will be used.
 */
public HttpClientRequestExecutor(ClientCredentials clientCredentials, Proxy proxy,
        AuthenticationScheme authenticationScheme, RequestAuthenticatorFactory requestAuthenticatorFactory,
        Integer connectionTimeout) {
    Assert.notNull(clientCredentials, "clientCredentials argument is required.");
    Assert.isTrue(connectionTimeout >= 0, "Timeout cannot be a negative number.");

    RequestAuthenticatorFactory factory = (requestAuthenticatorFactory != null) ? requestAuthenticatorFactory
            : new DefaultRequestAuthenticatorFactory();

    this.requestAuthenticator = factory.create(authenticationScheme, clientCredentials);

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();

    if (MAX_CONNECTIONS_TOTAL >= MAX_CONNECTIONS_PER_ROUTE) {
        connMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    } else {
        connMgr.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
        connMgr.setMaxTotal(DEFAULT_MAX_CONNECTIONS_TOTAL);

        log.warn(
                "{} ({}) is less than {} ({}). "
                        + "Reverting to defaults: connectionMaxTotal ({}) and connectionMaxPerRoute ({}).",
                MAX_CONNECTIONS_TOTAL_PROPERTY_KEY, MAX_CONNECTIONS_TOTAL,
                MAX_CONNECTIONS_PER_ROUTE_PROPERTY_KEY, MAX_CONNECTIONS_PER_ROUTE,
                DEFAULT_MAX_CONNECTIONS_TOTAL, DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    }

    // The connectionTimeout value is specified in seconds in Stormpath configuration settings.
    // Therefore, multiply it by 1000 to be milliseconds since RequestConfig expects milliseconds.
    int connectionTimeoutAsMilliseconds = connectionTimeout * 1000;

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeoutAsMilliseconds)
            .setSocketTimeout(connectionTimeoutAsMilliseconds).setRedirectsEnabled(false).build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(Consts.UTF_8).build();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .disableCookieManagement().setDefaultConnectionConfig(connectionConfig)
            .setConnectionManager(connMgr);

    this.httpClientRequestFactory = new HttpClientRequestFactory(requestConfig);

    if (proxy != null) {
        //We have some proxy setting to use!
        HttpHost httpProxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        httpClientBuilder.setProxy(httpProxyHost);

        if (proxy.isAuthenticationRequired()) {
            AuthScope authScope = new AuthScope(proxy.getHost(), proxy.getPort());
            Credentials credentials = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword());
            CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
            credentialsProviderProvider.setCredentials(authScope, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderProvider);
        }
    }

    this.httpClient = httpClientBuilder.build();
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param client JAX-RS client instance for which the connector is being created.
 * @param config client configuration./*from   w  w w.j a va  2  s .  c  om*/
 */
ApacheConnector(final Client client, final Configuration config) {
    final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);
    if (connectionManager != null) {
        if (!(connectionManager instanceof HttpClientConnectionManager)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER,
                            connectionManager.getClass().getName(),
                            HttpClientConnectionManager.class.getName()));
        }
    }

    Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
    if (reqConfig != null) {
        if (!(reqConfig instanceof RequestConfig)) {
            LOGGER.log(Level.WARNING,
                    LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                            reqConfig.getClass().getName(), RequestConfig.class.getName()));
            reqConfig = null;
        }
    }

    final SSLContext sslContext = client.getSslContext();
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext));
    clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(),
            ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
    if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
        clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
    }

    final Object proxyUri;
    proxyUri = config.getProperty(ClientProperties.PROXY_URI);
    if (proxyUri != null) {
        final URI u = getProxyUri(proxyUri);
        final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
        final String userName;
        userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                String.class);
        if (userName != null) {
            final String password;
            password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                    String.class);

            if (password != null) {
                final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(userName, password));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        clientBuilder.setProxy(proxy);
    }

    final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
            .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
    this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;

    final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
            ApacheClientProperties.DISABLE_COOKIES);

    if (reqConfig != null) {
        final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);

    /* DK_CLD: Add our connection reuse strategy. */
    clientBuilder.setConnectionReuseStrategy(new UpgradeAwareConnectionReuseStrategy());
    clientBuilder.setRequestExecutor(new HttpRequestExecutor() {
        protected HttpResponse doReceiveResponse(final HttpRequest request,
                final org.apache.http.HttpClientConnection conn, final HttpContext context)
                throws HttpException, IOException {
            Args.notNull(request, "HTTP request");
            Args.notNull(conn, "Client connection");
            Args.notNull(context, "HTTP context");
            HttpResponse response = null;
            int statusCode = 0;

            while (response == null || (statusCode < HttpStatus.SC_OK
                    // DK_CLD: the original implementation provided this loop to retry the HTTP request as long as
                    // an intermediate response is returned (1xx status). This is however not suitable for the
                    // status code 101 returned from Docker (and more generally, WebSockets) to notify that the
                    // connection has been upgraded to raw TCP streaming. In such case the server ultimate response
                    // is not HTTP anymore.
                    && statusCode != HttpStatus.SC_SWITCHING_PROTOCOLS)) {

                response = conn.receiveResponseHeader();
                if (canResponseHaveBody(request, response)) {
                    conn.receiveResponseEntity(response);
                }
                statusCode = response.getStatusLine().getStatusCode();

            } // while intermediate response

            return response;
        }

        @Override
        protected boolean canResponseHaveBody(HttpRequest request, HttpResponse response) {
            boolean canResponseHaveBody = super.canResponseHaveBody(request, response);
            return canResponseHaveBody
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_SWITCHING_PROTOCOLS;
        }
    });

    this.client = clientBuilder.build();
}

From source file:org.syncany.operations.init.ApplicationLink.java

private CloseableHttpClient createHttpClient() {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(2000)
            .setConnectTimeout(2000).setRedirectsEnabled(false);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // do we use a https proxy?
    String proxyHost = System.getProperty("https.proxyHost");
    String proxyPortStr = System.getProperty("https.proxyPort");
    String proxyUser = System.getProperty("https.proxyUser");
    String proxyPassword = System.getProperty("https.proxyPassword");

    if (proxyHost != null && proxyPortStr != null) {
        try {//from w w  w.j a va 2 s. c o m
            Integer proxyPort = Integer.parseInt(proxyPortStr);

            requestConfigBuilder.setProxy(new HttpHost(proxyHost, proxyPort));
            logger.log(Level.INFO, "Using proxy: " + proxyHost + ":" + proxyPort);

            if (proxyUser != null && proxyPassword != null) {
                logger.log(Level.INFO, "Proxy required credentials; using '" + proxyUser
                        + "' (username) and *** (hidden password)");

                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new UsernamePasswordCredentials(proxyUser, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }
        } catch (NumberFormatException e) {
            logger.log(Level.WARNING, "Invalid proxy settings found. Not using proxy.", e);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    return httpClientBuilder.build();
}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException {
    return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() {
        @Nullable//from  w  ww.ja v a 2  s .c  o m
        @Override
        public Void apply(@Nonnull HttpClientBuilder input) {
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            if (credentials != null) {
                final URI uri = httpMethod.getURI();
                HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                credentialsProvider.setCredentials(new AuthScope(hh), credentials);

                // Preemptive authentication
                if (isPreemptiveBasicAuth()) {
                    // Create AuthCache instance
                    AuthCache authCache = new BasicAuthCache();
                    // Generate BASIC scheme object and add it to the local auth cache
                    BasicScheme basicAuth = new BasicScheme();
                    authCache.put(hh, basicAuth);

                    // Add AuthCache to the execution context
                    httpClientContext = HttpClientContext.create();
                    httpClientContext.setCredentialsProvider(credentialsProvider);
                    httpClientContext.setAuthCache(authCache);
                } else {
                    input.setDefaultCredentialsProvider(credentialsProvider);
                }
            } else {
                input.setDefaultCredentialsProvider(credentialsProvider);
            }

            if (useProxy) {
                final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                input.setProxy(proxy);
                if (proxyCredentials != null) {
                    credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials);
                }
            }
            input.setRedirectStrategy(new LaxRedirectStrategy());
            return null;
        }
    }, this);
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

/**
 * Create the new Apache HTTP Client connector.
 *
 * @param config client configuration./*from   w  w w.java  2  s . co  m*/
 */
ApacheConnector(Configuration config) {
    Object reqConfig = null;

    if (config != null) {
        final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER);

        if (connectionManager != null) {
            if (!(connectionManager instanceof HttpClientConnectionManager)) {
                LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(
                        ApacheClientProperties.CONNECTION_MANAGER, connectionManager.getClass().getName(),
                        HttpClientConnectionManager.class.getName()));
            }
        }

        reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG);
        if (reqConfig != null) {
            if (!(reqConfig instanceof RequestConfig)) {
                LOGGER.log(Level.WARNING,
                        LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG,
                                reqConfig.getClass().getName(), RequestConfig.class.getName()));
                reqConfig = null;
            }
        }
    }

    final SSLContext sslContext = getSslContext(config);
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    clientBuilder.setConnectionManager(getConnectionManager(config, sslContext));
    clientBuilder.setSslcontext(sslContext);

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    int connectTimeout = 0;
    int socketTimeout = 0;
    boolean ignoreCookies = false;
    if (config != null) {
        connectTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        socketTimeout = ClientProperties.getValue(config.getProperties(), ClientProperties.READ_TIMEOUT, 0);
        ignoreCookies = PropertiesHelper.isProperty(config.getProperties(),
                ApacheClientProperties.DISABLE_COOKIES);

        final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER);
        if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
            clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider);
        }

        Object proxyUri;
        proxyUri = config.getProperty(ClientProperties.PROXY_URI);
        if (proxyUri != null) {
            final URI u = getProxyUri(proxyUri);
            final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());
            String userName;
            userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME,
                    String.class);
            if (userName != null) {
                String password;
                password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD,
                        String.class);

                if (password != null) {
                    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()),
                            new UsernamePasswordCredentials(userName, password));
                    clientBuilder.setDefaultCredentialsProvider(credsProvider);
                }
            }
            clientBuilder.setProxy(proxy);
        }

        final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties()
                .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION);
        this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false;
    } else {
        this.preemptiveBasicAuth = false;
    }

    if (reqConfig != null) {
        RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig);
        if (connectTimeout > 0) {
            reqConfigBuilder.setConnectTimeout(connectTimeout);
        }
        if (socketTimeout > 0) {
            reqConfigBuilder.setSocketTimeout(socketTimeout);
        }
        if (ignoreCookies) {
            reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = reqConfigBuilder.build();
    } else {
        requestConfigBuilder.setConnectTimeout(connectTimeout);
        requestConfigBuilder.setSocketTimeout(socketTimeout);
        if (ignoreCookies) {
            requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES);
        }
        requestConfig = requestConfigBuilder.build();
    }

    if (requestConfig.getCookieSpec() == null
            || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) {
        this.cookieStore = new BasicCookieStore();
        clientBuilder.setDefaultCookieStore(cookieStore);
    } else {
        this.cookieStore = null;
    }
    clientBuilder.setDefaultRequestConfig(requestConfig);
    this.client = clientBuilder.build();
}