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

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

Introduction

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

Prototype

public final HttpClientBuilder setConnectionManager(final HttpClientConnectionManager connManager) 

Source Link

Document

Assigns HttpClientConnectionManager instance.

Usage

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);
    }// w ww.j a  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:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;//w w  w . j  a va 2s .  c o  m
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build/* www.  j ava2 s  .  c  om*/
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

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

JsonObject post(String url, String body, String authHTTPCert) throws Exception {
    url = addCAToURL(url);//from w  ww.  j ava 2 s . c om
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig());
    logger.debug(format("httpPost %s, body:%s, authHTTPCert: %s", url, body, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpPost.setEntity(new StringEntity(body));
    httpPost.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpPost, context);

    return getResult(response, body, "POST");
}

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

JsonObject httpGet(String url, User registrar, Map<String, String> queryMap) throws Exception {
    String getURL = getURL(url, queryMap);
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "GET", getURL, "");
    HttpGet httpGet = new HttpGet(getURL);
    httpGet.setConfig(getRequestConfig());
    logger.debug(format("httpGet %s, authHTTPCert: %s", url, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }/*from  ww  w  . jav  a2  s.c o  m*/
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpGet.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpGet, context);

    return getResult(response, "", "GET");
}

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

JsonObject httpDelete(String url, User registrar) throws Exception {
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "DELETE", url, "");
    String deleteURL = addCAToURL(url);
    HttpDelete httpDelete = new HttpDelete(deleteURL);
    httpDelete.setConfig(getRequestConfig());
    logger.debug(format("httpPut %s, authHTTPCert: %s", url, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }//from w  w  w .j  av a  2 s .  c  o m
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpDelete.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpDelete, context);

    return getResult(response, "", "DELETE");
}

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

JsonObject httpPut(String url, String body, User registrar) throws Exception {
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "PUT", url, body);
    String putURL = addCAToURL(url);
    HttpPut httpPut = new HttpPut(putURL);
    httpPut.setConfig(getRequestConfig());
    logger.debug(format("httpPutt %s, body:%s, authHTTPCert: %s", url, body, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }//w w w .  jav  a2  s  . c o  m
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpPut.setEntity(new StringEntity(body));
    httpPut.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpPut, context);

    return getResult(response, body, "PUT");
}

From source file:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

private synchronized CloseableHttpClient httpClient() {

    if (httpClient == null) { // most of the time this will be false, branch-prediction will be very fast and the lock released immediately

        try {/*from   w ww.  j  a v  a 2s .c o m*/
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            SSLContext sslContext = SSLContext.getDefault();

            if (configuration.getTrustStrategy() != null) {

                if (configuration.getTrustStrategy().equals("ACCEPT_UNSIGNED")) {
                    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();

                    LOGGER.warn("Certificate validation has been disabled");
                }
            }

            // setup the default or custom ssl context
            httpClientBuilder.setSSLContext(sslContext);

            HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            // allows multi-threaded use
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);

            Integer connectionPoolSize = configuration.getConnectionPoolSize();

            connectionManager.setMaxTotal(connectionPoolSize);
            connectionManager.setDefaultMaxPerRoute(connectionPoolSize);

            httpClientBuilder.setConnectionManager(connectionManager);

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return httpClient;
}