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:hoot.services.controllers.job.JobControllerBase.java

public void postChainJobRquest(String jobId, String requestParams) {
    // Request should come back immediately but if something is wrong then
    // timeout and clean up.to make UI responsive
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(JOB_RES_CONNECTION_TIMEOUT)
            .setSocketTimeout(JOB_RES_CONNECTION_TIMEOUT).build();

    try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build()) {// w  w  w  . j ava2 s  .  co  m
        httpclient.start();

        HttpPost httpPost = new HttpPost(CORE_JOB_SERVER_URL + "/hoot-services/job/chain/" + jobId);
        logger.debug("postChainJobRquest : {}/hoot-services/job/chain/{}", CORE_JOB_SERVER_URL, jobId);

        StringEntity se = new StringEntity(requestParams);
        httpPost.setEntity(se);

        Future<HttpResponse> future = httpclient.execute(httpPost, null);

        // wait till we get response
        HttpResponse r = future.get();

        logger.debug("postChainJobRquest Response x: {}", r.getStatusLine());
    } catch (Exception ex) {
        String msg = "Failed upload: " + ex;
        throw new WebApplicationException(ex, Response.serverError().entity(msg).build());
    }
}

From source file:com.codeabovelab.dm.gateway.proxy.common.BalancerConfiguration.java

/**
 * Creates and configures HttpProxy// w  ww.j  a  v  a 2s. co m
 */
@Bean
HttpProxy httpProxy() {
    ProxyClient proxyClient = null;
    if (async) {
        if (metricsEbanled) {
            //Building HTTP Async client wrapper for gathering metrics
            proxyClient = new AsyncProxyClient(configuredHttpAsyncClient(
                    new InstrumentedNHttpClientBuilder(metricRegistry, QUERYLESS_URL)));
            LOG.info("metrics enabled");
        } else {
            //Building Default HTTP Async client
            LOG.warn("metrics disabled");
            proxyClient = new AsyncProxyClient(configuredHttpAsyncClient(HttpAsyncClients.custom()));
        }
    } else {
        if (metricsEbanled) {
            //Building HTTP sync client wrapper for gathering metrics
            proxyClient = new SyncProxyClient(
                    configuredHttpClient(InstrumentedHttpClients.custom(metricRegistry, QUERYLESS_URL)));
            LOG.info("metrics enabled");
        } else {
            //Building Default HTTP sync client
            LOG.warn("metrics disabled");
            proxyClient = new SyncProxyClient(configuredHttpClient(HttpClients.custom()));
        }
    }
    return proxyInstance = new HttpProxy(proxyClient);
}

From source file:com.mycompany.wolf.Room.java

public void removePlayer(String playerId) throws IOException {
    synchronized (mutex) {
        sessions.removeIf(equalityPredicate(playerId));
        List<Map<String, String>> roomInfo = sessions.stream()
                .map(s -> ImmutableMap.of("playerId", getPlayerId(s)))
                .collect(Collectors.toCollection(LinkedList::new));
        Map<String, Object> m = ImmutableMap.of("code", "exitResp", "properties", roomInfo);
        String json = new Gson().toJson(m);
        sessions.stream().forEach(s -> {
            s.getAsyncRemote().sendText(json);
        });//from  w  w w . ja  v  a  2 s . c  o  m
    }
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
            .build();
    httpclient.start();
    try {
        String routerAddress = SpringContext.getBean("routerAddress");

        httpclient.execute(new HttpGet(routerAddress), new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse t) {
            }

            @Override
            public void failed(Exception excptn) {
            }

            @Override
            public void cancelled() {
            }
        });
    } finally {
        httpclient.close();
    }
}

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

public void afterPropertiesSet() throws IOReactorException {
    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder = httpAsyncClientBuilder.useSystemProperties();

    NHttpClientConnectionManager nHttpClientConnectionManager = getPoolingNHttpClientConnectionManager();

    httpAsyncClientBuilder.setConnectionManager(nHttpClientConnectionManager);

    httpAsyncClientBuilder.setDefaultCredentialsProvider(_getCredentialsProvider());

    setProxyHost(httpAsyncClientBuilder);

    try {//from ww  w.  j  a  v  a 2 s . c  o  m
        _closeableHttpAsyncClient = httpAsyncClientBuilder.build();

        _closeableHttpAsyncClient.start();

        _idleConnectionMonitorThread = new IdleConnectionMonitorThread(nHttpClientConnectionManager);

        _idleConnectionMonitorThread.start();

        if (_logger.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();

            sb.append("Configured client for ");
            sb.append(_protocol);
            sb.append("://");
            sb.append(_hostName);
            sb.append(":");
            sb.append(_hostPort);

            _logger.debug(sb.toString());
        }
    } catch (Exception e) {
        _logger.error("Unable to configure client", e);
    }
}

From source file:com.guardtime.ksi.service.client.http.apache.ApacheHttpClient.java

/**
 * Creates asynchronous Apache HTTP client.
 *
 * @param settings//from  www. jav a 2 s  .  c  o m
 *         - settings to use to create client
 * @param conf
 *         - configuration related to async connection
 * @return instance of {@link CloseableHttpAsyncClient}
 */
private CloseableHttpAsyncClient createClient(AbstractHttpClientSettings settings,
        ApacheHttpClientConfiguration conf) {
    IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom().useSystemProperties()
            // allow POST redirects
            .setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount())
            .setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .setDefaultRequestConfig(createDefaultRequestConfig(settings));
    if (settings.getProxyUrl() != null) {
        DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }
    CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
    httpClient.start();
    return httpClient;
}

From source file:org.fuin.esc.eshttp.ESHttpEventStore.java

@Override
public void open() {
    if (open) {/*from  w  w w.  jav a  2s . c om*/
        // Ignore
        return;
    }
    final HttpAsyncClientBuilder builder = HttpAsyncClients.custom().setThreadFactory(threadFactory);
    if (credentialsProvider != null) {
        builder.setDefaultCredentialsProvider(credentialsProvider);
    }
    httpclient = builder.build();
    httpclient.start();
    this.open = true;
}

From source file:org.grycap.gpf4med.DownloadService.java

/**
 * Uses a group of URIs to retrieve objects and writes them to the same number of files. This method will do 
 * its best effort to optimally handle the downloads, opening a pool of connections to the servers and reusing 
 * them as much as possible. Also, it will create several concurrent threads in the JVM in order to perform 
 * simultaneous downloads./*from   ww  w.  ja  v a2 s  .  co  m*/
 * @param requests a key-value map with the list of requests to handle. The source of the object is the key of
 *        the map, while the value is the destination file.
 * @param validator checks the file for correctness.
 * @param config download settings.
 * @param encryptionProvider an optional encryption provider that, when available, is used to encrypt the 
 *        files after download.
 * @param task an optional task that will be executed passing each individual file as parameter, when the download 
 *        of the file ends.
 * @return the requests that could not be served after exhausting the individual retries.
 * @throws IOException if an error occurs in the execution of the operation.
 */
public ImmutableMap<URI, File> download(final ImmutableMap<URI, File> requests,
        final @Nullable FileValidator validator, final DownloadConfiguration config,
        final @Nullable FileEncryptionProvider encryptionProvider, final @Nullable PostProcessTask<File> task)
        throws IOException {
    checkArgument(requests != null, "Uninitialized request");
    checkArgument(config != null, "Uninitialized configuration");
    ImmutableMap<URI, File> pending = ImmutableMap.copyOf(requests);
    final List<URI> cancelled = new ArrayList<URI>();
    try {
        for (int attempt = 0; attempt < config.getRetries() && !pending.isEmpty()
                && pending.size() > cancelled.size(); attempt++) {
            LOGGER.info("Attempt " + (attempt + 1) + " to download " + requests.size() + " files");
            // create connection manager
            final PoolingNHttpClientConnectionManager connectionManager = createConnectionManager();
            // create HTTP asynchronous client
            int eSoTimeoutMs = config.soToMs + (int) (config.soToMs * attempt
                    * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent
                            : 0.0d));
            int eConnTimeoutMs = config.connToMs + (int) (config.connToMs * attempt
                    * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent
                            : 0.0d));
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(eConnTimeoutMs)
                    .setConnectionRequestTimeout(eConnTimeoutMs).setSocketTimeout(eSoTimeoutMs).build();
            final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
                    .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
            httpclient.start();
            // attempt to perform download
            try {
                final CountDownLatch latch = new CountDownLatch(pending.size());
                for (final Map.Entry<URI, File> entry : pending.entrySet()) {
                    final URI uri = entry.getKey();
                    if (cancelled.contains(uri)) {
                        continue;
                    }
                    final File file = entry.getValue();
                    FileUtils.forceMkdir(file.getParentFile());
                    final HttpGet request = new HttpGet(uri);
                    final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(
                            new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), request);
                    final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(file) {
                        @Override
                        protected File process(final HttpResponse response, final File file,
                                final ContentType contentType) throws Exception {
                            releaseResources();
                            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                                FileUtils.deleteQuietly(file);
                                throw new ClientProtocolException(
                                        "Download failed: " + response.getStatusLine());
                            }
                            if (validator != null && !validator.isValid(file)) {
                                FileUtils.deleteQuietly(file);
                                cancelled.add(uri);
                                throw new IOException(
                                        file.getCanonicalPath() + " not recognised as a supported file format");
                            }
                            if (encryptionProvider != null) {
                                try {
                                    final File cipherFile = File
                                            .createTempFile(RandomStringUtils.random(8, true, true), ".tmp");
                                    encryptionProvider.encrypt(new FileInputStream(file),
                                            new FileOutputStream(cipherFile));
                                    FileUtils.deleteQuietly(file);
                                    FileUtils.moveFile(cipherFile, file);
                                    LOGGER.info("File encrypted: " + file.getCanonicalPath());
                                } catch (Exception e) {
                                    FileUtils.deleteQuietly(file);
                                    cancelled.add(uri);
                                    LOGGER.warn("Failed to encrypt: " + file.getCanonicalPath(), e);
                                    throw new IOException("File encryption failed");
                                }
                            }
                            LOGGER.info("Download succeed to file: " + file.getCanonicalPath());
                            return file;
                        }
                    };
                    httpclient.execute(producer, consumer, new FutureCallback<File>() {
                        @Override
                        public void completed(final File result) {
                            request.releaseConnection();
                            latch.countDown();
                            if (task != null) {
                                task.apply(result);
                            }
                            LOGGER.info("Request succeed: " + request.getRequestLine()
                                    + " => Response file length: " + result.length());
                        }

                        @Override
                        public void failed(final Exception ex) {
                            request.releaseConnection();
                            FileUtils.deleteQuietly(file);
                            latch.countDown();
                            LOGGER.error("Request failed: " + request.getRequestLine() + "=>" + ex);
                        }

                        @Override
                        public void cancelled() {
                            request.releaseConnection();
                            FileUtils.deleteQuietly(file);
                            latch.countDown();
                            LOGGER.error("Request cancelled: " + request.getRequestLine());
                        }
                    });
                }
                latch.await();
            } finally {
                try {
                    httpclient.close();
                } catch (Exception ignore) {
                }
                try {
                    shutdown(connectionManager, 0l);
                } catch (Exception ignore) {
                }
            }
            // populate the pending list with the files that does not exist
            final ImmutableMap.Builder<URI, File> builder = new ImmutableMap.Builder<URI, File>();
            for (final Map.Entry<URI, File> entry : requests.entrySet()) {
                if (!entry.getValue().exists()) {
                    builder.put(entry.getKey(), entry.getValue());
                }
            }
            pending = builder.build();
            if ((attempt + 1) < config.retries && !pending.isEmpty() && pending.size() > cancelled.size()) {
                final long waitingTime = (long) (config.soToMs * 0.1d);
                LOGGER.info("Waiting " + waitingTime + " ms before attempt " + (attempt + 2) + " to download "
                        + requests.size() + " pending files");
                Thread.sleep(waitingTime);
            }
        }
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        throw new IOException("Download has failed", e);
    }
    return pending;
}

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

@Override
protected void configureClient() {

    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();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {/*ww  w  . j  a  va2 s  .  com*/

        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:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java

private void startHttpClient() {
    if (httpClient != null) {
        // http client is already started
        return;//  w w w  . ja  va  2  s  .co  m
    }
    // limit max  number of async requests in sequential mode, 0 means "use
    // default limit"
    int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0;
    if (!disableCertificateValidation) {
        // create an http client that validates certificates
        httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).build();
    } else {
        // create strategy that accepts all certificates
        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] certificate, String type) {
                return true;
            }
        };
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal)
                    .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                    .setSSLContext(sslContext).build();
        } catch (Exception e) {
        }
    }
    httpClient.start();
}

From source file:org.springframework.integration.splunk.support.SplunkHECWriter.java

@Override
public void start() {

    try {//from  w  w w.java2 s  . c  o m
        this.batchBuffer = Collections.synchronizedList(new LinkedList<String>());
        this.lastEventReceivedTime = System.currentTimeMillis();

        Registry<SchemeIOSessionStrategy> sslSessionStrategy = RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register("http", NoopIOSessionStrategy.INSTANCE)
                .register("https", new SSLIOSessionStrategy(getSSLContext(), HOSTNAME_VERIFIER)).build();

        ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
        PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor,
                sslSessionStrategy);
        cm.setMaxTotal(getPoolsize());

        HttpHost splunk = new HttpHost(getHost(), getPort());
        cm.setMaxPerRoute(new HttpRoute(splunk), getPoolsize());

        httpClient = HttpAsyncClients.custom().setConnectionManager(cm).build();

        uri = new URIBuilder().setScheme(isHttps() ? "https" : "http").setHost(getHost()).setPort(getPort())
                .setPath("/services/collector").build();

        httpClient.start();

        if (isBatchMode()) {
            new BatchBufferActivityCheckerThread(this).start();
        }
    } catch (Exception e) {
    }

    this.running = true;

}