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:leap.lang.http.client.apache.ApacheHttpClient.java

protected CloseableHttpClient initHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cm.setMaxTotal(maxConnectionTotal);//from ww w .  j a  v  a2  s.c  o  m
    cm.setDefaultMaxPerRoute(maxConnectionPerRoute);

    if (bufferSize > 0) {
        ConnectionConfig cc = ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

        cm.setDefaultConnectionConfig(cc);
    }

    cb.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });

    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(requestConfig);

    return cb.build();
}

From source file:sk.datalan.solr.impl.HttpSolrServer.java

public HttpSolrServer(String baseURL, HttpClientBuilder builder, ResponseParser parser) {
    this.baseUrl = baseURL;
    if (baseUrl.endsWith("/")) {
        baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
    }/*from  w w w. j  a va  2 s. c  o  m*/
    if (baseUrl.indexOf('?') >= 0) {
        throw new RuntimeException(
                "Invalid base url for solrj.  The base URL must not contain parameters: " + baseUrl);
    }

    if (builder != null) {
        httpClient = builder.build();
        internalClient = false;
    } else {
        internalClient = true;
        HttpClientConfiguration config = new HttpClientConfiguration();
        config.setMaxConnections(128);
        config.setMaxConnectionsPerRoute(32);
        config.setFollowRedirects(followRedirects);
        httpClient = HttpClientUtil.createClient(config);
    }

    this.parser = parser;
}

From source file:com.liferay.sync.engine.session.Session.java

public Session(URL url, String login, String password, boolean trustSelfSigned, int maxConnections) {

    if (maxConnections == Integer.MAX_VALUE) {
        _executorService = Executors.newCachedThreadPool();
    } else {// ww  w.  jav a 2s . c  o m
        _executorService = Executors.newFixedThreadPool(maxConnections);
    }

    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections);

    httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned));

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    credentialsProvider.setCredentials(new AuthScope(_httpHost),
            new UsernamePasswordCredentials(login, password));

    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    _httpClient = httpClientBuilder.build();

    _oAuthEnabled = false;
}

From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static HttpClient getHttpClient() {
    if (httpClient == null) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties();
        if (sslRequired) {
            if (sslsf != null) {
                clientBuilder.setSSLSocketFactory(sslsf);
            }//from  ww  w  .  j  a  v  a 2  s  .c o m
        } else {
            SSLContext sslContext;
            try {
                sslContext = SSLContext.getInstance("SSL");

                // set up a TrustManager that trusts everything
                sslContext.init(null, new TrustManager[] { new X509TrustManager() {

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                } }, new SecureRandom());
            } catch (NoSuchAlgorithmException ex) {
                throw new AuthenticationException("Cannot get SSLContext instance for \"SSL\" protocol.", ex);
            } catch (KeyManagementException ex) {
                throw new AuthenticationException("SSLContext initialization failed.", ex);
            }

            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext);
        }
        httpClient = clientBuilder.build();
    }
    return httpClient;
}

From source file:com.brsanthu.googleanalytics.GoogleAnalytics.java

protected CloseableHttpClient createHttpClient(GoogleAnalyticsConfig config) {
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute(config));

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager);

    if (isNotEmpty(config.getUserAgent())) {
        builder.setUserAgent(config.getUserAgent());
    }//from   w ww  .  ja  va2s.c o  m

    if (isNotEmpty(config.getProxyHost())) {
        builder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));

        if (isNotEmpty(config.getProxyUserName())) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUserName(), config.getProxyPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }

    return builder.build();
}

From source file:com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder.java

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();/*from   w  ww.  ja  v  a  2 s .co m*/
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(
            systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;/* w ww.  j a  v  a2 s  . c om*/
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java

private Requisition getRequisition(String url, String userName, String password) {
    Requisition requisition = null;// w  w  w  .  j a v a2  s. co  m

    if (url != null) {
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();

            // If username and password was found, inject the credentials
            if (userName != null && password != null) {

                CredentialsProvider provider = new BasicCredentialsProvider();

                // Create the authentication scope
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                // Create credential pair
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);

                // Inject the credentials
                provider.setCredentials(scope, credentials);

                // Set the default credentials provider
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            try {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

            } catch (JAXBException e) {
                LOGGER.error("The response did not contain a valid requisition as xml.", e);
            }
            LOGGER.debug("Got Requisition {}", requisition);
        } catch (IOException ex) {
            LOGGER.error("Requesting requisition from {} failed", url, ex);
            return null;
        }
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
        return null;
    }
    return requisition;
}