Example usage for org.apache.http.impl.nio.conn PoolingNHttpClientConnectionManager PoolingNHttpClientConnectionManager

List of usage examples for org.apache.http.impl.nio.conn PoolingNHttpClientConnectionManager PoolingNHttpClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.nio.conn PoolingNHttpClientConnectionManager PoolingNHttpClientConnectionManager.

Prototype

public PoolingNHttpClientConnectionManager(final ConnectingIOReactor ioreactor,
            final NHttpConnectionFactory<ManagedNHttpClientConnection> connFactory) 

Source Link

Usage

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

private static PoolingNHttpClientConnectionManager buildAsyncConnectionManager(HttpClientConfig config,
        SSLContext sslContext) {//from w w  w  .  j av  a2 s. c om
    // scheme configuration
    SchemeIOSessionStrategy sslSocketFactory = new SSLIOSessionStrategy(sslContext);
    Registry<SchemeIOSessionStrategy> asyncSchemeRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
            .register("http", NoopIOSessionStrategy.INSTANCE).register("https", sslSocketFactory).build();

    // pooling settings
    ConnectingIOReactor ioreactor;
    try {
        ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
    } catch (IOReactorException ex) {
        throw new RuntimeException("Unable to initialize IO reactor.", ex);
    }
    PoolingNHttpClientConnectionManager conmgr = new PoolingNHttpClientConnectionManager(ioreactor,
            asyncSchemeRegistry);
    conmgr.setMaxTotal(config.getMaxTotalConnections());
    conmgr.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    return conmgr;
}

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

private PoolingNHttpClientConnectionManager getAsyncConnectionManager() {
    ConnectingIOReactor ioReactor = null;
    PoolingNHttpClientConnectionManager cm = null;
    try {/*from  w  w  w .j  av  a2s  .  c o m*/
        ioReactor = new DefaultConnectingIOReactor();
        // ssl setup
        SSLContext sslcontext = SSLContexts.createSystemDefault();
        X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
        @SuppressWarnings("deprecation")
        Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
                .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
                .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)).build();

        cm = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
    } catch (IOReactorException e) {
        LOG.error("Couldn't initialize multi-threaded async client ", e);
        return null;
    }
    return cm;
}

From source file:com.petalmd.armor.HeaderAwareJestClientFactory.java

protected NHttpClientConnectionManager getAsyncConnectionManager() {
    PoolingNHttpClientConnectionManager retval;

    IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
            .setConnectTimeout(httpClientConfig.getConnTimeout())
            .setSoTimeout(httpClientConfig.getReadTimeout()).build();

    Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", httpClientConfig.getHttpIOSessionStrategy())
            .register("https", httpClientConfig.getHttpsIOSessionStrategy()).build();

    try {/*from  w  w w .  j  a  v  a  2 s.  c o m*/
        retval = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(ioReactorConfig),
                sessionStrategyRegistry);
    } catch (IOReactorException e) {
        throw new IllegalStateException(e);
    }

    final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
    if (maxTotal != null) {
        retval.setMaxTotal(maxTotal);
    }
    final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
    if (defaultMaxPerRoute != null) {
        retval.setDefaultMaxPerRoute(defaultMaxPerRoute);
    }
    final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
    for (Map.Entry<HttpRoute, Integer> entry : maxPerRoute.entrySet()) {
        retval.setMaxPerRoute(entry.getKey(), entry.getValue());
    }

    return retval;
}

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

@Override
public void start() {

    try {//from  ww w  .j  a va  2s  . c  om
        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;

}

From source file:net.tirasa.wink.client.asynchttpclient.ApacheHttpAsyncClientConnectionHandler.java

private synchronized CloseableHttpAsyncClient openConnection(ClientRequest request)
        throws NoSuchAlgorithmException, KeyManagementException, IOException {

    if (this.httpclient != null) {
        return this.httpclient;
    }//from   w  w w . j a  va 2s. c om

    HttpAsyncClientBuilder clientBuilder = HttpAsyncClientBuilder.create();

    // cast is safe because we're on the client
    ApacheHttpAsyncClientConfig config = (ApacheHttpAsyncClientConfig) request
            .getAttribute(WinkConfiguration.class);

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
            .setConnectTimeout(config.getConnectTimeout()).setSocketTimeout(config.getReadTimeout());
    if (config.isFollowRedirects()) {
        requestConfigBuilder.setRedirectsEnabled(true).setCircularRedirectsAllowed(true);
    }

    // setup proxy
    if (config.getProxyHost() != null) {
        requestConfigBuilder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));
    }

    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    Registry<SchemeIOSessionFactory> connManagerRegistry;
    if (config.getBypassHostnameVerification()) {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);

        connManagerRegistry = RegistryBuilder.<SchemeIOSessionFactory>create()
                .register("http", PlainIOSessionFactory.INSTANCE)
                .register("https", new SSLIOSessionFactory(sslcontext, new X509HostnameVerifier() {

                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }

                    @Override
                    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    }

                    @Override
                    public void verify(String host, X509Certificate cert) throws SSLException {
                    }

                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }
                })).build();
    } else {
        connManagerRegistry = RegistryBuilder.<SchemeIOSessionFactory>create()
                .register("http", PlainIOSessionFactory.INSTANCE)
                .register("https", SSLIOSessionFactory.getDefaultStrategy()).build();
    }

    PoolingNHttpClientConnectionManager httpConnectionManager = new PoolingNHttpClientConnectionManager(
            new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT), connManagerRegistry);
    if (config.getMaxPooledConnections() > 0) {
        httpConnectionManager.setMaxTotal(config.getMaxPooledConnections());
        httpConnectionManager.setDefaultMaxPerRoute(config.getMaxPooledConnections());

    }
    clientBuilder.setConnectionManager(httpConnectionManager);

    this.httpclient = clientBuilder.build();
    this.httpclient.start();

    return this.httpclient;
}

From source file:com.networknt.client.Client.java

private CloseableHttpAsyncClient httpAsyncClient() throws ClientException {
    PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor(),
            asyncRegistry());//w w  w .ja v a2s.co  m
    Map<String, Object> asyncHttpClientMap = (Map<String, Object>) config.get(ASYNC);
    connectionManager.setMaxTotal((Integer) asyncHttpClientMap.get(MAX_CONNECTION_TOTAL));
    connectionManager.setDefaultMaxPerRoute((Integer) asyncHttpClientMap.get(MAX_CONNECTION_PER_ROUTE));
    // Now handle all the specific route defined.
    Map<String, Object> routeMap = (Map<String, Object>) asyncHttpClientMap.get(ROUTES);
    Iterator<String> it = routeMap.keySet().iterator();
    while (it.hasNext()) {
        String route = it.next();
        Integer maxConnection = (Integer) routeMap.get(route);
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(route)), maxConnection);
    }
    final int timeout = (Integer) asyncHttpClientMap.get(TIMEOUT);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
    final long keepAliveMilliseconds = (Integer) asyncHttpClientMap.get(KEEP_ALIVE);

    return HttpAsyncClientBuilder.create().setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    HeaderElementIterator it = new BasicHeaderElementIterator(
                            response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                    while (it.hasNext()) {
                        HeaderElement he = it.nextElement();
                        String param = he.getName();
                        String value = he.getValue();
                        if (value != null && param.equalsIgnoreCase("timeout")) {
                            try {
                                logger.trace("Use server timeout for keepAliveMilliseconds");
                                return Long.parseLong(value) * 1000;
                            } catch (NumberFormatException ignore) {
                            }
                        }
                    }
                    //logger.trace("Use keepAliveMilliseconds from config " + keepAliveMilliseconds);
                    return keepAliveMilliseconds;
                }
            }).setDefaultRequestConfig(config).build();
}

From source file:org.apache.http.localserver.AbstractAsyncTest.java

@Before
public void setUp() throws Exception {
    this.serverBootstrap = ServerBootstrap.bootstrap();
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(15000).build();
    this.serverBootstrap.setServerInfo("TEST/1.1");
    this.serverBootstrap.setIOReactorConfig(ioReactorConfig);
    this.serverBootstrap.setExceptionLogger(new ExceptionLogger() {

        private final Log log = LogFactory.getLog(AbstractAsyncTest.class);

        @Override//from ww  w .ja va 2 s .  c o  m
        public void log(final Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    });
    if (this.scheme.equals(ProtocolScheme.https)) {
        this.serverBootstrap.setSslContext(createServerSSLContext());
    }

    final RegistryBuilder<SchemeIOSessionStrategy> builder = RegistryBuilder.create();
    builder.register("http", NoopIOSessionStrategy.INSTANCE);
    if (this.scheme.equals(ProtocolScheme.https)) {
        builder.register("https",
                new SSLIOSessionStrategy(createClientSSLContext(), new DefaultHostnameVerifier()));
    }
    final Registry<SchemeIOSessionStrategy> registry = builder.build();
    final DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
    this.connMgr = new PoolingNHttpClientConnectionManager(ioReactor, registry);
}