Example usage for org.apache.http.impl.nio.client HttpAsyncClientBuilder setProxy

List of usage examples for org.apache.http.impl.nio.client HttpAsyncClientBuilder setProxy

Introduction

In this page you can find the example usage for org.apache.http.impl.nio.client HttpAsyncClientBuilder setProxy.

Prototype

public final HttpAsyncClientBuilder setProxy(final HttpHost proxy) 

Source Link

Document

Assigns default proxy value.

Usage

From source file:io.wcm.caravan.commons.httpasyncclient.impl.HttpAsyncClientItem.java

private static CloseableHttpAsyncClient buildHttpAsyncClient(HttpClientConfig config,
        PoolingNHttpClientConnectionManager connectionManager, CredentialsProvider credentialsProvider) {

    // prepare HTTPClient builder
    HttpAsyncClientBuilder httpClientAsyncBuilder = HttpAsyncClientBuilder.create()
            .setConnectionManager(connectionManager);

    // timeout settings
    httpClientAsyncBuilder.setDefaultRequestConfig(RequestConfig.custom()
            .setConnectTimeout(config.getConnectTimeout()).setSocketTimeout(config.getSocketTimeout()).build());

    httpClientAsyncBuilder.setDefaultCredentialsProvider(credentialsProvider);

    // optional proxy support
    if (StringUtils.isNotEmpty(config.getProxyHost())) {
        httpClientAsyncBuilder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));

        // optional proxy authentication
        if (StringUtils.isNotEmpty(config.getProxyUser())) {
            httpClientAsyncBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
        }//w  w  w  . ja v  a 2 s .c  o m
    }

    return httpClientAsyncBuilder.build();
}

From source file:io.getlime.push.service.fcm.FcmClient.java

/**
 * Set information about proxy.// ww  w .  jav a2s  . co m
 * @param host Proxy host URL.
 * @param port Proxy port.
 * @param username Proxy username, use 'null' for proxy without authentication.
 * @param password Proxy user password, ignored in case username is 'null'
 */
public void setProxy(String host, int port, String username, String password) {

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();
    clientBuilder.useSystemProperties();
    clientBuilder.setProxy(new HttpHost(host, port));

    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials user = new UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(new AuthScope(host, port), user);
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
    }

    CloseableHttpAsyncClient client = clientBuilder.build();

    HttpComponentsAsyncClientHttpRequestFactory factory = new HttpComponentsAsyncClientHttpRequestFactory();
    factory.setAsyncClient(client);

    restTemplate.setAsyncRequestFactory(factory);
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpAsyncClient buildAsync(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpAsyncClientBuilder builder = HttpAsyncClients.custom();

    // Certificate Validation
    // TODO//  w  w  w  .j  av  a 2  s. com
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLStrategy(new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {
        // Disable
        SSLIOSessionStrategy sslStrategy = new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLStrategy(sslStrategy);
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java

private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) {
    LOG.info("Creating async proxy http client");
    PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager();
    HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort());

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
    if (cm != null) {
        clientBuilder = clientBuilder.setConnectionManager(cm);
    }//  ww  w  .j  a  v  a2s .c  o m

    if (proxy != null) {
        clientBuilder = clientBuilder.setProxy(proxy);
    }
    clientBuilder = setRedirects(clientBuilder);
    return clientBuilder.build();
}

From source file:org.elasticsearch.client.documentation.RestClientDocumentation.java

@SuppressWarnings("unused")
public void testUsage() throws IOException, InterruptedException {

    //tag::rest-client-init
    RestClient restClient = RestClient/*  ww w .j  a  v a 2s .c o m*/
            .builder(new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build();
    //end::rest-client-init

    //tag::rest-client-close
    restClient.close();
    //end::rest-client-close

    {
        //tag::rest-client-init-default-headers
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        Header[] defaultHeaders = new Header[] { new BasicHeader("header", "value") };
        builder.setDefaultHeaders(defaultHeaders); // <1>
        //end::rest-client-init-default-headers
    }
    {
        //tag::rest-client-init-max-retry-timeout
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setMaxRetryTimeoutMillis(10000); // <1>
        //end::rest-client-init-max-retry-timeout
    }
    {
        //tag::rest-client-init-failure-listener
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setFailureListener(new RestClient.FailureListener() {
            @Override
            public void onFailure(HttpHost host) {
                // <1>
            }
        });
        //end::rest-client-init-failure-listener
    }
    {
        //tag::rest-client-init-request-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setSocketTimeout(10000); // <1>
            }
        });
        //end::rest-client-init-request-config-callback
    }
    {
        //tag::rest-client-init-client-config-callback
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                return httpClientBuilder.setProxy(new HttpHost("proxy", 9000, "http")); // <1>
            }
        });
        //end::rest-client-init-client-config-callback
    }

    {
        //tag::rest-client-sync
        Request request = new Request("GET", // <1>
                "/"); // <2>
        Response response = restClient.performRequest(request);
        //end::rest-client-sync
    }
    {
        //tag::rest-client-async
        Request request = new Request("GET", // <1>
                "/"); // <2>
        restClient.performRequestAsync(request, new ResponseListener() {
            @Override
            public void onSuccess(Response response) {
                // <3>
            }

            @Override
            public void onFailure(Exception exception) {
                // <4>
            }
        });
        //end::rest-client-async
    }
    {
        Request request = new Request("GET", "/");
        //tag::rest-client-parameters
        request.addParameter("pretty", "true");
        //end::rest-client-parameters
        //tag::rest-client-body
        request.setEntity(new NStringEntity("{\"json\":\"text\"}", ContentType.APPLICATION_JSON));
        //end::rest-client-body
        //tag::rest-client-body-shorter
        request.setJsonEntity("{\"json\":\"text\"}");
        //end::rest-client-body-shorter
        {
            //tag::rest-client-headers
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.addHeader("Accept", "text/plain");
            options.addHeader("Cache-Control", "no-cache");
            request.setOptions(options);
            //end::rest-client-headers
        }
        {
            //tag::rest-client-response-consumer
            RequestOptions.Builder options = request.getOptions().toBuilder();
            options.setHttpAsyncResponseConsumerFactory(
                    new HttpAsyncResponseConsumerFactory.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
            request.setOptions(options);
            //end::rest-client-response-consumer
        }
    }
    {
        HttpEntity[] documents = new HttpEntity[10];
        //tag::rest-client-async-example
        final CountDownLatch latch = new CountDownLatch(documents.length);
        for (int i = 0; i < documents.length; i++) {
            Request request = new Request("PUT", "/posts/doc/" + i);
            //let's assume that the documents are stored in an HttpEntity array
            request.setEntity(documents[i]);
            restClient.performRequestAsync(request, new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    // <1>
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    // <2>
                    latch.countDown();
                }
            });
        }
        latch.await();
        //end::rest-client-async-example
    }
    {
        //tag::rest-client-response2
        Response response = restClient.performRequest("GET", "/");
        RequestLine requestLine = response.getRequestLine(); // <1>
        HttpHost host = response.getHost(); // <2>
        int statusCode = response.getStatusLine().getStatusCode(); // <3>
        Header[] headers = response.getHeaders(); // <4>
        String responseBody = EntityUtils.toString(response.getEntity()); // <5>
        //end::rest-client-response2
    }
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

protected void setProxyHost(HttpAsyncClientBuilder httpClientBuilder) {
    if ((_proxyHostName == null) || _proxyHostName.equals("")) {
        return;//from ww  w .  j  a  v  a  2  s.  c  om
    }

    httpClientBuilder.setProxy(new HttpHost(_proxyHostName, _proxyHostPort));
    httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
}