Example usage for org.apache.http.impl.nio.client HttpAsyncClients custom

List of usage examples for org.apache.http.impl.nio.client HttpAsyncClients custom

Introduction

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

Prototype

public static HttpAsyncClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpAsyncClient instances.

Usage

From source file:org.glowroot.central.SyntheticMonitorService.java

SyntheticMonitorService(ActiveAgentDao activeAgentDao, ConfigRepositoryImpl configRepository,
        AlertingDisabledDao alertingDisabledDao, IncidentDao incidentDao, AlertingService alertingService,
        SyntheticResultDao syntheticResponseDao, ClusterManager clusterManager, Ticker ticker, Clock clock,
        String version) throws Exception {
    this.activeAgentDao = activeAgentDao;
    this.configRepository = configRepository;
    this.alertingDisabledDao = alertingDisabledDao;
    this.incidentDao = incidentDao;
    this.alertingService = alertingService;
    this.syntheticResponseDao = syntheticResponseDao;
    this.ticker = ticker;
    this.clock = clock;
    executionRateLimiter = clusterManager.createReplicatedMap("syntheticMonitorExecutionRateLimiter", 30,
            SECONDS);//from   w  w w . j  ava  2s. co m
    if (version.equals(Version.UNKNOWN_VERSION)) {
        shortVersion = "";
    } else {
        int index = version.indexOf(", built ");
        if (index == -1) {
            shortVersion = "/" + version;
        } else {
            shortVersion = "/" + version.substring(0, index);
        }
    }
    // asyncHttpClient is only used for pings, so safe to ignore cert errors
    asyncHttpClient = HttpAsyncClients.custom().setUserAgent("GlowrootCentral" + shortVersion)
            .setDefaultHeaders(Arrays.asList(new BasicHeader("Glowroot-Transaction-Type", "Synthetic")))
            .setMaxConnPerRoute(10) // increasing from default 2
            .setMaxConnTotal(1000) // increasing from default 20
            .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build())
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    asyncHttpClient.start();
    syncHttpClientHolder = createSyncHttpClientHolder(shortVersion, configRepository.getHttpProxyConfig());
    // these parameters are from com.machinepublishers.jbrowserdriver.UserAgent.CHROME
    // with added GlowrootCentral/<version> for identification purposes
    userAgent = new UserAgent(Family.WEBKIT, "Google Inc.", "Win32", "Windows NT 6.1",
            "5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion);
    // there is one subworker per worker, so using same max
    subWorkerExecutor = MoreExecutors
            .listeningDecorator(MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Sub-Worker-%d"));
    workerExecutor = MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Worker-%d");
    mainLoopExecutor = MoreExecutors2.newSingleThreadExecutor("Synthetic-Monitor-Main-Loop");
    mainLoopExecutor.execute(castInitialized(this));
}

From source file:ee.ria.xroad.proxy.testsuite.MessageTestCase.java

protected CloseableHttpAsyncClient getClient() throws Exception {
    HttpAsyncClientBuilder builder = HttpAsyncClients.custom();

    IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
            .setIoThreadCount(Runtime.getRuntime().availableProcessors()).setConnectTimeout(getClientTimeout())
            .setSoTimeout(30000).build();

    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);

    PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);

    connManager.setMaxTotal(1);//  w w  w .ja  v  a  2 s  .  c om
    connManager.setDefaultMaxPerRoute(1);

    builder.setConnectionManager(connManager);

    return builder.build();
}

From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

private void setupAsyncClient() {
    final HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();

    if (sslContext != null) {
        clientBuilder.setSSLContext(sslContext);
        clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor());
    }/*from w w w . jav  a  2s .  c o  m*/

    httpAsyncClient = clientBuilder.setDefaultCredentialsProvider(getCredentialsProvider()).build();
    httpAsyncClient.start();
}

From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java

private CloseableHttpAsyncClient createFiberCloseableHttpAsyncClient() {
    return FiberCloseableHttpAsyncClient.wrap(HttpAsyncClients.custom().setMaxConnPerRoute(concurrencyLevel)
            .setMaxConnTotal(concurrencyLevel).build());
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduitFactory.java

public synchronized void setupNIOClient(HTTPClientPolicy clientPolicy) throws IOReactorException {
    if (client != null) {
        return;//w ww .  j  av a 2 s  . c o m
    }

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(ioThreadCount)
            .setSelectInterval(selectInterval).setInterestOpQueued(interestOpQueued).setSoLinger(soLinger)
            .setSoTimeout(soTimeout).setSoKeepAlive(soKeepalive).setTcpNoDelay(tcpNoDelay).build();

    Registry<SchemeIOSessionStrategy> ioSessionFactoryRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", SSLIOSessionStrategy.getSystemDefaultStrategy()).build();

    ManagedNHttpClientConnectionFactory connectionFactory = new ManagedNHttpClientConnectionFactory() {

        @Override
        public ManagedNHttpClientConnection create(final IOSession iosession, final ConnectionConfig config) {
            ManagedNHttpClientConnection conn = super.create(iosession, config);
            return conn;
        }
    };

    DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(config);
    connectionManager = new PoolingNHttpClientConnectionManager(ioreactor, connectionFactory,
            ioSessionFactoryRegistry, DefaultSchemePortResolver.INSTANCE, SystemDefaultDnsResolver.INSTANCE,
            connectionTTL, TimeUnit.MILLISECONDS);

    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnections);

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setBufferSize(clientPolicy.getChunkLength() > 0 ? clientPolicy.getChunkLength() : 16332).build();

    connectionManager.setDefaultConnectionConfig(connectionConfig);

    RedirectStrategy redirectStrategy = new RedirectStrategy() {

        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return false;
        }

        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            return null;
        }
    };

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom()
            .setConnectionManager(connectionManager).setRedirectStrategy(redirectStrategy)
            .setDefaultCookieStore(new BasicCookieStore() {
                private static final long serialVersionUID = 1L;

                public void addCookie(Cookie cookie) {
                }
            });

    adaptClientBuilder(httpAsyncClientBuilder);

    client = httpAsyncClientBuilder.build();
    // Start the client thread
    client.start();
    if (this.connectionTTL == 0) {
        //if the connection does not have an expiry deadline
        //use the ConnectionMaxIdle to close the idle connection
        new CloseIdleConnectionThread(connectionManager, client).start();
    }
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/** Downloads a product. */
private void downloadProduct(Product p) throws IOException, InterruptedException {
    // Creates a client producer that produces HTTP Basic auth aware clients
    HttpAsyncClientProducer cliprod = new HttpAsyncClientProducer() {
        @Override/*w  w w  . j a  va  2  s .  c  o  m*/
        public CloseableHttpAsyncClient generateClient() {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                    new UsernamePasswordCredentials(serviceUser, servicePass));
            CloseableHttpAsyncClient res = HttpAsyncClients.custom()
                    .setDefaultCredentialsProvider(credsProvider).build();
            res.start();
            return res;
        }
    };

    // Asks the Incoming manager for a download path
    Path dir = Paths.get(INCOMING_MANAGER.getNewIncomingPath().toURI());
    Path tmp_pd = dir.resolve(p.getIdentifier() + ".part"); // Temporary names
    Path tmp_ql = dir.resolve(p.getIdentifier() + "-ql.part");
    Path tmp_tn = dir.resolve(p.getIdentifier() + "-tn.part");
    // These files will be moved once download is complete

    InterruptibleHttpClient http_client = new InterruptibleHttpClient(cliprod);
    DownloadResult pd_res = null, ql_res = null, tn_res = null;
    try {
        long delta = System.currentTimeMillis();
        pd_res = downloadValidateRename(http_client, tmp_pd, p.getOrigin());
        logODataPerf(p.getOrigin(), System.currentTimeMillis() - delta);

        // Sets download info in the product (not written in the db here)
        p.setPath(pd_res.data.toUri().toURL());
        p.setDownloadablePath(pd_res.data.toString());
        p.setDownloadableType(pd_res.dataType);
        p.setDownloadableSize(pd_res.dataSize);

        // Downloads and sets the quicklook and thumbnail (if any)
        if (p.getQuicklookFlag()) {
            // Failing at downloading a quicklook must not abort the download!
            try {
                ql_res = downloadValidateRename(http_client, tmp_ql, p.getQuicklookPath());
                p.setQuicklookPath(ql_res.data.toString());
                p.setQuicklookSize(ql_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download quicklook at " + p.getQuicklookPath(), ex);
            }
        }
        if (p.getThumbnailFlag()) {
            // Failing at downloading a thumbnail must not abort the download!
            try {
                tn_res = downloadValidateRename(http_client, tmp_tn, p.getThumbnailPath());
                p.setThumbnailPath(tn_res.data.toString());
                p.setThumbnailSize(tn_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download thumbnail at " + p.getThumbnailPath(), ex);
            }
        }
    } catch (Exception ex) {
        // Removes downloaded files if an error occured
        if (pd_res != null) {
            Files.delete(pd_res.data);
        }
        if (ql_res != null) {
            Files.delete(ql_res.data);
        }
        if (tn_res != null) {
            Files.delete(tn_res.data);
        }
        throw ex;
    }
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create asynchronous http client based on connection manager.
 *
 * @param connectionManager Asynchronous http client connection manager.
 * @return Asynchronous http client based on connection manager.
 *///  www  .  j ava2s .co m
protected CloseableHttpAsyncClient createHttpAsyncClient(NHttpClientConnectionManager connectionManager) {
    HttpAsyncClientBuilder builder = HttpAsyncClients.custom().setConnectionManager(connectionManager);

    int socketBufferSizeInBytes = this.config.getSocketBufferSizeInBytes();
    if (socketBufferSizeInBytes > 0) {
        builder.setDefaultConnectionConfig(
                ConnectionConfig.custom().setBufferSize(socketBufferSizeInBytes).build());
    }
    return builder.build();
}

From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java

protected void configureClient() {

    clientConfig = new DefaultClientConfigImpl();
    clientConfig.loadProperties(getApiName());
    setLoadBalancer(loadBalancer);/*from  ww w  .j  av a 2  s.c  o  m*/
    //        clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName());
    //        clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName());
    //        clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName());
    //        clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName());

    if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) {
        EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName());
        EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + ".");
        DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig);
    }

    loadBalancer.initWithNiwsConfig(clientConfig);

    //        if (HystrixPlugins.getInstance().getMetricsPublisher() == null) {
    //            HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance());
    //        }

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    autoEncodeUri = metadata.isAutoEncodeUri();
    followRedirects = metadata.isFollowRedirects();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:org.rapidoid.http.HttpClient.java

private static CloseableHttpAsyncClient asyncClient(boolean enableCookies, boolean enableRedirects) {
    ConnectionReuseStrategy reuseStrategy = new NoConnectionReuseStrategy();

    HttpAsyncClientBuilder builder = HttpAsyncClients.custom()
            .setThreadFactory(new RapidoidThreadFactory("http-client"));

    if (!enableCookies) {
        builder = builder.disableCookieManagement().disableConnectionState().disableAuthCaching()
                .setConnectionReuseStrategy(reuseStrategy);
    }//from  ww w.ja  va  2s  .  c  o  m

    if (!enableRedirects) {
        builder = builder.setRedirectStrategy(NO_REDIRECTS);
    }

    return builder.build();
}