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

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

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

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

JsonObject post(String url, String body, String authHTTPCert) throws Exception {
    url = addCAToURL(url);/*from  www  . java  2 s.com*/
    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 w w  w  .j a v a2s  .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  a  va2  s .c om
    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));
    }/*from   w w  w .  ja v  a 2 s. co  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   ww w .  jav  a 2 s .  co  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;
}

From source file:org.keycloak.connections.httpclient.DefaultHttpClientFactory.java

private void lazyInit(KeycloakSession session) {
    if (httpClient == null) {
        synchronized (this) {
            if (httpClient == null) {
                long socketTimeout = config.getLong("socket-timeout-millis", -1L);
                long establishConnectionTimeout = config.getLong("establish-connection-timeout-millis", -1L);
                int maxPooledPerRoute = config.getInt("max-pooled-per-route", 64);
                int connectionPoolSize = config.getInt("connection-pool-size", 128);
                long connectionTTL = config.getLong("connection-ttl-millis", -1L);
                long maxConnectionIdleTime = config.getLong("max-connection-idle-time-millis", 900000L);
                boolean disableCookies = config.getBoolean("disable-cookies", true);
                String clientKeystore = config.get("client-keystore");
                String clientKeystorePassword = config.get("client-keystore-password");
                String clientPrivateKeyPassword = config.get("client-key-password");
                String[] proxyMappings = config.getArray("proxy-mappings");

                TruststoreProvider truststoreProvider = session.getProvider(TruststoreProvider.class);
                boolean disableTrustManager = truststoreProvider == null
                        || truststoreProvider.getTruststore() == null;
                if (disableTrustManager) {
                    logger.warn("Truststore is disabled");
                }/*from   w  ww . j a  v  a 2 s .c o m*/
                HttpClientBuilder.HostnameVerificationPolicy hostnamePolicy = disableTrustManager ? null
                        : HttpClientBuilder.HostnameVerificationPolicy
                                .valueOf(truststoreProvider.getPolicy().name());

                HttpClientBuilder builder = new HttpClientBuilder();

                builder.socketTimeout(socketTimeout, TimeUnit.MILLISECONDS)
                        .establishConnectionTimeout(establishConnectionTimeout, TimeUnit.MILLISECONDS)
                        .maxPooledPerRoute(maxPooledPerRoute).connectionPoolSize(connectionPoolSize)
                        .connectionTTL(connectionTTL, TimeUnit.MILLISECONDS)
                        .maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS)
                        .disableCookies(disableCookies).proxyMappings(ProxyMappings.valueOf(proxyMappings));

                if (disableTrustManager) {
                    // TODO: is it ok to do away with disabling trust manager?
                    //builder.disableTrustManager();
                } else {
                    builder.hostnameVerification(hostnamePolicy);
                    try {
                        builder.trustStore(truststoreProvider.getTruststore());
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to load truststore", e);
                    }
                }

                if (clientKeystore != null) {
                    clientKeystore = EnvUtil.replace(clientKeystore);
                    try {
                        KeyStore clientCertKeystore = KeystoreUtil.loadKeyStore(clientKeystore,
                                clientKeystorePassword);
                        builder.keyStore(clientCertKeystore, clientPrivateKeyPassword);
                    } catch (Exception e) {
                        throw new RuntimeException("Failed to load keystore", e);
                    }
                }
                httpClient = builder.build();
            }
        }
    }
}

From source file:com.bosch.cr.examples.jwt.CustomProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {//from   w  ww .  j a  v a 2 s. c om
            final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

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

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

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

            final boolean proxyEnabled = configurationProperties
                    .getPropertyAsBoolean(ConfigurationProperty.PROXY_ENABLED);
            if (proxyEnabled) {
                final String proxyHost = configurationProperties
                        .getPropertyAsString(ConfigurationProperty.PROXY_HOST);
                final int proxyPort = configurationProperties
                        .getPropertyAsInt(ConfigurationProperty.PROXY_PORT);
                final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                httpClientBuilder.setProxy(proxy);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:ch.cyberduck.core.s3.RequestEntityRestStorageService.java

public RequestEntityRestStorageService(final S3Session session, final Jets3tProperties properties,
        final HttpClientBuilder configuration) {
    super(session.getHost().getCredentials().isAnonymousLogin() ? null : new AWSCredentials(null, null) {
        @Override/*from   ww  w.j ava2  s. com*/
        public String getAccessKey() {
            return session.getHost().getCredentials().getUsername();
        }

        @Override
        public String getSecretKey() {
            return session.getHost().getCredentials().getPassword();
        }
    }, new PreferencesUseragentProvider().get(), null, properties);
    this.session = session;
    configuration.disableContentCompression();
    configuration.setRetryHandler(
            new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
    configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            if (response.containsHeader("x-amz-bucket-region")) {
                final String host = ((HttpUriRequest) request).getURI().getHost();
                if (!StringUtils.equals(session.getHost().getHostname(), host)) {
                    regionEndpointCache.putRegionForBucketName(
                            StringUtils
                                    .split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(),
                                            session.getHost().getHostname()), ".")[0],
                            response.getFirstHeader("x-amz-bucket-region").getValue());
                }
            }
            return super.getRedirect(request, response, context);
        }
    });
    this.setHttpClient(configuration.build());
}

From source file:de.comlineag.snc.webcrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from   w w w  .j  a  v a  2s  .  c o m

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.debug("Exception thrown while trying to register https:", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());
    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
    }
    clientBuilder.addInterceptorLast(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    httpClient = clientBuilder.build();

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:com.floragunn.searchguard.AbstractUnitTest.java

protected final CloseableHttpClient getHTTPClient() throws Exception {

    final HttpClientBuilder hcb = HttpClients.custom();

    if (enableHTTPClientSSL) {

        log.debug("Configure HTTP client with SSL");

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

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

        final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useTLS();

        if (trustHTTPServerCertificate) {
            sslContextbBuilder.loadTrustMaterial(myTrustStore);
        }

        if (sendHTTPClientCertificate) {
            sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
        }//from   w w  w  . jav a2s .  co  m

        final SSLContext sslContext = sslContextbBuilder.build();

        String[] protocols = null;

        if (enableHTTPClientSSLv3Only) {
            protocols = new String[] { "SSLv3" };
        } else {
            protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
        }

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

        hcb.setSSLSocketFactory(sslsf);
    }

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

    return hcb.build();
}