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:com.petalmd.armor.AbstractUnitTest.java

protected final HeaderAwareJestHttpClient getJestClient(final String serverUri, final String username,
        final String password) throws Exception {// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();

    final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build();

    // Construct a new Jest client according to configuration via factory
    final HeaderAwareJestClientFactory factory1 = new HeaderAwareJestClientFactory();

    factory1.setHttpClientConfig(clientConfig1);

    final HeaderAwareJestHttpClient c = factory1.getObject();

    final HttpClientBuilder hcb = HttpClients.custom();

    if (username != null) {
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
    }//from  w w  w. ja va  2 s  . co  m

    if (useSpnego) {
        //SPNEGO/Kerberos setup
        log.debug("SPNEGO activated");
        final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true, false);//  new NegotiateSchemeProvider();
        final Credentials jaasCreds = new JaasCredentials();
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
        credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM),
                new NTCredentials("Guest", "Guest", "Guest", "Guest"));
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

        hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
    }

    hcb.setDefaultCredentialsProvider(credsProvider);

    if (serverUri.startsWith("https")) {
        log.debug("Configure Jest with SSL");

        final KeyStore myTrustStore = KeyStore.getInstance("JKS");
        myTrustStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorTS.jks")),
                "changeit".toCharArray());

        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(SecurityUtil.getAbsoluteFilePathFromClassPath("ArmorKS.jks")),
                "changeit".toCharArray());

        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(keyStore, "changeit".toCharArray()).loadTrustMaterial(myTrustStore).build();

        String[] protocols = null;

        if (enableSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = SecurityUtil.ENABLED_SSL_PROTOCOLS;
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols,
                SecurityUtil.ENABLED_SSL_CIPHERS, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        hcb.setSSLSocketFactory(sslsf);

    }

    hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

    final CloseableHttpClient httpClient = hcb.build();

    c.setHttpClient(httpClient);
    return c;

}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/*from   w  w  w . j  av a2s  .  co  m*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}

From source file:org.apache.zeppelin.livy.BaseLivyInterpreter.java

private RestTemplate createRestTemplate() {
    String keytabLocation = getProperty("zeppelin.livy.keytab");
    String principal = getProperty("zeppelin.livy.principal");
    boolean isSpnegoEnabled = StringUtils.isNotEmpty(keytabLocation) && StringUtils.isNotEmpty(principal);

    HttpClient httpClient = null;/*  w  ww  .ja  va 2  s.com*/
    if (livyURL.startsWith("https:")) {
        String keystoreFile = getProperty("zeppelin.livy.ssl.trustStore");
        String password = getProperty("zeppelin.livy.ssl.trustStorePassword");
        if (StringUtils.isBlank(keystoreFile)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStore specified for livy ssl");
        }
        if (StringUtils.isBlank(password)) {
            throw new RuntimeException("No zeppelin.livy.ssl.trustStorePassword specified " + "for livy ssl");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(keystoreFile);
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(keystoreFile), password.toCharArray());
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(csf);
            RequestConfig reqConfig = new RequestConfig() {
                @Override
                public boolean isAuthenticationEnabled() {
                    return true;
                }
            };
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            Credentials credentials = new Credentials() {
                @Override
                public String getPassword() {
                    return null;
                }

                @Override
                public Principal getUserPrincipal() {
                    return null;
                }
            };
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY, credentials);
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            if (isSpnegoEnabled) {
                Registry<AuthSchemeProvider> authSchemeProviderRegistry = RegistryBuilder
                        .<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .build();
                httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeProviderRegistry);
            }

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create SSL HttpClient", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LOGGER.error("Failed to close keystore file", e);
                }
            }
        }
    }

    RestTemplate restTemplate = null;
    if (isSpnegoEnabled) {
        if (httpClient == null) {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal);
        } else {
            restTemplate = new KerberosRestTemplate(keytabLocation, principal, httpClient);
        }
    } else {
        if (httpClient == null) {
            restTemplate = new RestTemplate();
        } else {
            restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
    return restTemplate;
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main//from   ww w.j a va 2s .c o  m
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:com.igormaznitsa.mvngolang.AbstractGolangMojo.java

@Nonnull
private synchronized HttpClient getHttpClient(@Nullable final ProxySettings proxy) {
    if (this.httpClient == null) {
        final HttpClientBuilder builder = HttpClients.custom();

        if (proxy != null) {
            if (proxy.hasCredentials()) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxy.host, proxy.port),
                        new UsernamePasswordCredentials(proxy.username, proxy.password));
                builder.setDefaultCredentialsProvider(credentialsProvider);
                getLog().debug(//from   w ww.  j a  va2 s . co m
                        String.format("Credentials provider has been created for proxy (username : %s): %s",
                                proxy.username, proxy.toString()));
            }

            final String[] ignoreForAddresses = proxy.nonProxyHosts == null ? new String[0]
                    : proxy.nonProxyHosts.split("\\|");
            if (ignoreForAddresses.length > 0) {
                final WildCardMatcher[] matchers = new WildCardMatcher[ignoreForAddresses.length];
                for (int i = 0; i < ignoreForAddresses.length; i++) {
                    matchers[i] = new WildCardMatcher(ignoreForAddresses[i]);
                }

                final HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                        new HttpHost(proxy.host, proxy.port, proxy.protocol)) {
                    @Override
                    @Nonnull
                    public HttpRoute determineRoute(@Nonnull final HttpHost host,
                            @Nonnull final HttpRequest request, @Nonnull final HttpContext context)
                            throws HttpException {
                        final String hostName = host.getHostName();
                        for (final WildCardMatcher m : matchers) {
                            if (m.match(hostName)) {
                                getLog().debug("Ignoring proxy for host : " + hostName);
                                return new HttpRoute(host);
                            }
                        }
                        return super.determineRoute(host, request, context);
                    }
                };
                builder.setRoutePlanner(routePlanner);
                getLog().debug(
                        "Route planner tuned to ignore proxy for addresses : " + Arrays.toString(matchers));
            }
        }

        builder.setUserAgent("mvn-golang-wrapper-agent/1.0");
        this.httpClient = builder.build();

    }
    return this.httpClient;
}

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

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

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            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();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Http Post Request.//from  ww  w . ja v a  2s.  com
 *
 * @param url         Target URL to POST to.
 * @param body        Body to be sent with the post.
 * @param credentials Credentials to use for basic auth.
 * @return Body of post returned.
 * @throws Exception
 */
String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception {
    logger.debug(format("httpPost %s, body:%s", url, body));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    CredentialsProvider provider = null;
    if (credentials != null) {
        provider = new BasicCredentialsProvider();

        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (registry != null) {

        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));

    }

    HttpClient client = httpClientBuilder.build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig());

    AuthCache authCache = new BasicAuthCache();

    HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort());

    if (credentials != null) {
        authCache.put(targetHost, new

        BasicScheme());

    }

    final HttpClientContext context = HttpClientContext.create();

    if (null != provider) {
        context.setCredentialsProvider(provider);
    }

    if (credentials != null) {
        context.setAuthCache(authCache);
    }

    httpPost.setEntity(new StringEntity(body));
    if (credentials != null) {
        httpPost.addHeader(new

        BasicScheme().

                authenticate(credentials, httpPost, context));
    }

    HttpResponse response = client.execute(httpPost, context);
    int status = response.getStatusLine().getStatusCode();

    HttpEntity entity = response.getEntity();
    logger.trace(format("httpPost %s  sending...", url));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("httpPost %s  responseBody %s", url, responseBody));

    if (status >= 400) {

        Exception e = new Exception(format(
                "POST request to %s  with request body: %s, " + "failed with status code: %d. Response: %s",
                url, body, status, responseBody));
        logger.error(e.getMessage());
        throw e;
    }
    logger.debug(format("httpPost Status: %d returning: %s ", status, responseBody));

    return responseBody;
}