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:org.apache.solr.client.solrj.impl.HttpClientUtil.java

/**
 * Creates new http client by using the provided configuration.
 * //  w  w w.j av  a2  s.  c o  m
 */
public static CloseableHttpClient createClient(final SolrParams params, PoolingHttpClientConnectionManager cm,
        boolean sharedConnectionManager) {
    final ModifiableSolrParams config = new ModifiableSolrParams(params);
    if (logger.isDebugEnabled()) {
        logger.debug("Creating new http client, config:" + config);
    }

    cm.setMaxTotal(params.getInt(HttpClientUtil.PROP_MAX_CONNECTIONS, 10000));
    cm.setDefaultMaxPerRoute(params.getInt(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 10000));
    cm.setValidateAfterInactivity(
            Integer.getInteger(VALIDATE_AFTER_INACTIVITY, VALIDATE_AFTER_INACTIVITY_DEFAULT));

    HttpClientBuilder newHttpClientBuilder = HttpClientBuilder.create();

    if (sharedConnectionManager) {
        newHttpClientBuilder.setConnectionManagerShared(true);
    } else {
        newHttpClientBuilder.setConnectionManagerShared(false);
    }

    ConnectionKeepAliveStrategy keepAliveStrat = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // we only close connections based on idle time, not ttl expiration
            return -1;
        }
    };

    if (httpClientBuilder.getAuthSchemeRegistryProvider() != null) {
        newHttpClientBuilder.setDefaultAuthSchemeRegistry(
                httpClientBuilder.getAuthSchemeRegistryProvider().getAuthSchemeRegistry());
    }
    if (httpClientBuilder.getCookieSpecRegistryProvider() != null) {
        newHttpClientBuilder.setDefaultCookieSpecRegistry(
                httpClientBuilder.getCookieSpecRegistryProvider().getCookieSpecRegistry());
    }
    if (httpClientBuilder.getCredentialsProviderProvider() != null) {
        newHttpClientBuilder.setDefaultCredentialsProvider(
                httpClientBuilder.getCredentialsProviderProvider().getCredentialsProvider());
    }

    newHttpClientBuilder.addInterceptorLast(new DynamicInterceptor());

    newHttpClientBuilder = newHttpClientBuilder.setKeepAliveStrategy(keepAliveStrat).evictIdleConnections(
            (long) Integer.getInteger(EVICT_IDLE_CONNECTIONS, EVICT_IDLE_CONNECTIONS_DEFAULT),
            TimeUnit.MILLISECONDS);

    HttpClientBuilder builder = setupBuilder(newHttpClientBuilder, params);

    HttpClient httpClient = builder.setConnectionManager(cm).build();

    assert ObjectReleaseTracker.track(httpClient);
    return (CloseableHttpClient) httpClient;
}

From source file:org.apache.geode.rest.internal.web.GeodeRestClient.java

public HttpResponse doRequest(HttpRequestBase request, String username, String password) throws Exception {
    HttpHost targetHost = new HttpHost(bindAddress, restPort, protocol);

    HttpClientBuilder clientBuilder = HttpClients.custom();
    HttpClientContext clientContext = HttpClientContext.create();

    // configures the clientBuilder and clientContext
    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
    }//from w w w  .j  av  a2s .  c  om

    if (useHttps) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        clientBuilder.setSSLContext(ctx);
        clientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    return clientBuilder.build().execute(targetHost, request, clientContext);
}

From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java

private static void setProxy(HttpClientBuilder httpClientBuilder) {
    HttpHost proxyHost = null;/*  w  ww. j av  a  2s.c o m*/
    if (StringUtils.isNotEmpty(Globals.settings.getProxyPort())) {
        proxyHost = new HttpHost(Globals.settings.getProxyHost(),
                Integer.parseInt(Globals.settings.getProxyPort()));
    } else {
        proxyHost = new HttpHost(Globals.settings.getProxyHost());
    }

    // authenticate
    if (!StringUtils.isEmpty(Globals.settings.getProxyUsername())
            && !StringUtils.isEmpty(Globals.settings.getProxyPassword())) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (Globals.settings.getProxyUsername().contains("\\")) {
            // use NTLM
            int offset = Globals.settings.getProxyUsername().indexOf("\\");
            String domain = Globals.settings.getProxyUsername().substring(0, offset);
            String username = Globals.settings.getProxyUsername().substring(offset + 1,
                    Globals.settings.getProxyUsername().length());

            credentialsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(username, Globals.settings.getProxyPassword(), "", domain));
        } else {
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    Globals.settings.getProxyUsername(), Globals.settings.getProxyPassword()));
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    // set proxy
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
    httpClientBuilder.setRoutePlanner(routePlanner);

    // try to get proxy settings from JRE - is probably added in HttpClient 4.3; fixed with 4.3.3
    // (https://issues.apache.org/jira/browse/HTTPCLIENT-1457)
    // SystemDefaultCredentialsProvider credentialsProvider = new SystemDefaultCredentialsProvider();
    // httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    // SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
    // httpClientBuilder.setRoutePlanner(routePlanner);
}

From source file:org.fcrepo.mint.HttpPidMinter.java

/**
 * Setup authentication in httpclient.// w w  w.  j ava 2 s. com
 * @return the setup of authentication
**/
protected HttpClient buildClient() {
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(connManager);
    if (!isBlank(username) && !isBlank(password)) {
        final URI uri = URI.create(url);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:org.fcrepo.kernel.impl.identifiers.HttpPidMinter.java

/**
 * Setup authentication in httpclient./*from   w  w w  .  j a va 2s .c  o m*/
**/
protected HttpClient buildClient() {
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(new PoolingHttpClientConnectionManager());
    if (!isBlank(username) && !isBlank(password)) {
        final URI uri = URI.create(url);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * CloseableHttpResponse/*  w w  w  .  ja va 2s.  co  m*/
 * 
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies)
        throws ClientProtocolException, IOException {

    HttpClientBuilder httpclientBuilder = HttpClients.custom();

    if (withproxy) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                ProxySettings.getProxyUser(), ProxySettings.getProxyPassword()));
        httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build();
    }
    CloseableHttpClient httpclient = httpclientBuilder.build();

    HttpClientContext context = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();

    Iterator<Cookie> iter = cookies.iterator();

    while (iter.hasNext()) {
        Cookie restCookie = iter.next();
        BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue());
        // cookie.setDomain(restCookie.getDomain());
        cookie.setDomain(getDomainName(url));
        cookie.setPath(restCookie.getPath());
        cookie.setSecure(true);
        // cookie.setExpiryDate(restCookie);
        cookieStore.addCookie(cookie);
    }

    context.setCookieStore(cookieStore);

    HttpGet httpget = new HttpGet(url);

    Builder configBuilder = RequestConfig.custom();

    if (withproxy) {
        HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(),
                Integer.parseInt(ProxySettings.getProxyPort()), "http");
        configBuilder.setProxy(proxy).build();
    }

    RequestConfig config = configBuilder.build();
    httpget.setConfig(config);

    return httpclient.execute(httpget, context);

}

From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
    String languageValue = this.getStringFromField(this.language, execution);
    String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
    String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
    String usernameValue = this.getStringFromField(this.username, execution);
    String passwordValue = this.getStringFromField(this.password, execution);

    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
    Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);

    if (endpointUrlValue.startsWith("vm:")) {
        LocalWebServiceClient client = this.getWebServiceContext().getClient();
        WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext());
        WebServiceMessage resultMessage = client.send(endpointUrlValue, message);
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }/*from w w w .ja  va2 s . co  m*/

    } else {

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        if (usernameValue != null && passwordValue != null) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue,
                    passwordValue);
            provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials);
            clientBuilder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = clientBuilder.build();

        HttpPost request = new HttpPost(endpointUrlValue);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(payload);
            oos.flush();
            oos.close();

            request.setEntity(new ByteArrayEntity(baos.toByteArray()));

        } catch (Exception e) {
            throw new ActivitiException("Error setting message payload", e);
        }

        byte[] responseBytes = null;
        try {
            // execute the POST request
            HttpResponse response = client.execute(request);
            responseBytes = IOUtils.toByteArray(response.getEntity().getContent());

        } finally {
            // release any connection resources used by the method
            request.releaseConnection();
        }

        if (responseBytes != null) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
                ObjectInputStream is = new ObjectInputStream(in);
                Object result = is.readObject();
                if (resultVariableValue != null) {
                    execution.setVariable(resultVariableValue, result);
                }
            } catch (Exception e) {
                throw new ActivitiException("Failed to read response value", e);
            }
        }
    }

    this.leave(execution);
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }/*from  www.ja v a  2  s .c o  m*/
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:io.github.thred.climatetray.ClimateTrayProxySettings.java

public CloseableHttpClient createHttpClient(String... additionalProxyExcludes) {
    if (proxyType == ProxyType.NONE) {
        return HttpClients.createDefault();
    }//from  ww  w.  j  a va 2s  .c o  m

    if (proxyType == ProxyType.SYSTEM_DEFAULT) {
        return HttpClients.createSystem();
    }

    HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
    HttpClientBuilder builder = HttpClientBuilder.create().setProxy(proxy);

    if (isProxyAuthorizationNeeded()) {
        Credentials credentials = new UsernamePasswordCredentials(getProxyUser(), getProxyPassword());
        AuthScope authScope = new AuthScope(getProxyHost(), getProxyPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(authScope, credentials);

        builder.setDefaultCredentialsProvider(credsProvider);
    }

    String excludes = proxyExcludes;

    if (Utils.isBlank(excludes)) {
        excludes = "";
    }

    for (String additionalProxyExclude : additionalProxyExcludes) {
        if (excludes.length() > 0) {
            excludes += ", ";
        }

        excludes += additionalProxyExclude;
    }

    if (!Utils.isBlank(excludes)) {
        WildcardPattern pattern = new WildcardPattern(excludes.split("\\s*,\\s*"));
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context)
                    throws HttpException {
                InetAddress address = host.getAddress();

                if (address == null) {
                    try {
                        address = InetAddress.getByName(host.getHostName());
                    } catch (UnknownHostException e) {
                        ClimateTray.LOG.info("Failed to determine address of host \"%s\"", host.getHostName());
                    }
                }

                if (address != null) {
                    String hostAddress = address.getHostAddress();

                    if (pattern.matches(hostAddress)) {
                        return new HttpRoute(host);
                    }
                }

                String hostName = host.getHostName();

                if (pattern.matches(hostName)) {
                    return new HttpRoute(host);
                }

                return super.determineRoute(host, request, context);
            }
        };

        builder.setRoutePlanner(routePlanner);
    }

    return builder.build();
}

From source file:org.hawk.http.HTTPManager.java

private CloseableHttpClient createClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    // Provide username and password if specified
    if (username != null) {
        final BasicCredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(new HttpHost(repositoryURL.getHost())),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credProvider);
    }// w  ww.  ja  v a  2 s . c o  m

    // Follow redirects
    builder.setRedirectStrategy(new LaxRedirectStrategy());

    return builder.build();
}