Example usage for org.apache.http.impl.conn PoolingHttpClientConnectionManager setDefaultMaxPerRoute

List of usage examples for org.apache.http.impl.conn PoolingHttpClientConnectionManager setDefaultMaxPerRoute

Introduction

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

Prototype

public void setDefaultMaxPerRoute(final int max) 

Source Link

Usage

From source file:dal.arris.RequestArrisAlter.java

public RequestArrisAlter(Integer deviceId, Autenticacao autenticacao, String frequency)
        throws UnsupportedEncodingException, IOException {
    Autenticacao a = AuthFactory.getEnd();
    String auth = a.getUser() + ":" + a.getPassword();
    String url = a.getLink() + "capability/execute?capability="
            + URLEncoder.encode("\"getLanWiFiInfo\"", "UTF-8") + "&deviceId=" + deviceId + "&input="
            + URLEncoder.encode(frequency, "UTF-8");

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);//from  w w w .j  a  va 2s.  c  om
    cm.setDefaultMaxPerRoute(1);
    HttpHost localhost = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(globalConfig).build();

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    String authHeader = "Basic " + new String(encodedAuth);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpget.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
        httpget.setHeader("Cookie", "JSESSIONID=aaazqNDcHoduPbavRvVUv; AX-CARE-AGENTS-20480=HECDMIAKJABP");

        RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .build();

        HttpGet httpGet = new HttpGet("/");
        httpGet.setConfig(localConfig);

        //            httpget.setHeader(n);
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                    }
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
            for (Header allHeader : response.getAllHeaders()) {
                System.out.println("Nome: " + allHeader.getName() + " Valor: " + allHeader.getValue());
            }
        }
    } finally {
        httpclient.close();
    }
    httpclient.close();
}

From source file:com.continuuity.loom.scheduler.callback.HttpPostClusterCallback.java

public void initialize(Configuration conf, ClusterStoreService clusterStoreService) {
    this.clusterStoreService = clusterStoreService;
    this.onStartUrl = conf.get(Constants.HttpCallback.START_URL);
    this.onSuccessUrl = conf.get(Constants.HttpCallback.SUCCESS_URL);
    this.onFailureUrl = conf.get(Constants.HttpCallback.FAILURE_URL);
    this.startTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.START_TRIGGERS, Constants.HttpCallback.DEFAULT_START_TRIGGERS));
    this.successTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.SUCCESS_TRIGGERS, Constants.HttpCallback.DEFAULT_SUCCESS_TRIGGERS));
    this.failureTriggerActions = parseActionsString(
            conf.get(Constants.HttpCallback.FAILURE_TRIGGERS, Constants.HttpCallback.DEFAULT_FAILURE_TRIGGERS));
    if (onStartUrl != null) {
        LOG.debug("before hook will be triggered on actions {}", Joiner.on(',').join(startTriggerActions));
    }//  w w w. ja  v a 2s. co m
    if (onSuccessUrl != null) {
        LOG.debug("after hook will be triggered on actions {}", Joiner.on(',').join(successTriggerActions));
    }
    if (onFailureUrl != null) {
        LOG.debug("after hook will be triggered on actions {}", Joiner.on(',').join(failureTriggerActions));
    }

    int maxConnections = conf.getInt(Constants.HttpCallback.MAX_CONNECTIONS,
            Constants.HttpCallback.DEFAULT_MAX_CONNECTIONS);
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(maxConnections);
    connectionManager.setMaxTotal(maxConnections);

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(
            conf.getInt(Constants.HttpCallback.SOCKET_TIMEOUT, Constants.HttpCallback.DEFAULT_SOCKET_TIMEOUT))
            .build();
    connectionManager.setDefaultSocketConfig(socketConfig);
    this.httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}

From source file:org.jboss.additional.testsuite.jdkall.present.jaxrs.client.ApacheHttpClient432TestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)//from ww w  .j  a v  a  2  s  .  c om
public void apacheHttpClient4EngineServletTest(@ArquillianResource URL url) throws Exception {
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true)
            .setSoReuseAddress(true).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

    connManager.setMaxTotal(100);

    connManager.setDefaultMaxPerRoute(100);

    connManager.setDefaultSocketConfig(socketConfig);

    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(100)
            .setConnectionRequestTimeout(3000).setStaleConnectionCheckEnabled(true).build();

    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
            .setConnectionManager(connManager).build();

    final ClientHttpEngine executor;

    executor = new ApacheHttpClient43Engine(httpClient);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(executor).build();

    final ApacheHttpClient43Resource proxy = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName())
            .proxy(ApacheHttpClient43Resource.class);

    WebTarget target = client
            .target("http://127.0.0.1:8080/" + ApacheHttpClient432TestCase.class.getSimpleName() + "/test2");

    Response response = target.request().get();
    Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());

    try {
        Response s = proxy.get();

        assertEquals(200, s.getStatus());
    } catch (ProcessingException e) {
        logger.warn("Exception occured." + e);

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:com.ccreanga.bitbucket.rest.client.http.BitBucketHttpExecutor.java

public BitBucketHttpExecutor(String baseUrl, BitBucketCredentials credentials) {
    this.baseUrl = baseUrl;

    HttpHost targetHost = HttpHost.create(baseUrl);
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(5);/*from   w  w  w.j av  a 2  s.com*/
    connectionManager.setDefaultMaxPerRoute(4);

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    httpClient = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultCredentialsProvider(credentialsProvider).build();

}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

public CloseableHttpClient build() throws InitializationException {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS);

    final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig);

    if (configuration.getHttpProxy() != null) {
        configureProxy(httpClientBuilder, configuration.getHttpProxy());
    }//from  w  w  w. ja v  a 2s  . co  m

    return httpClientBuilder.build();
}

From source file:org.muhia.app.psi.integ.config.ke.obopay.ObopayBulkApiClientConfiguration.java

@Bean(name = "obopayBulkApiHttpClient")
public CloseableHttpClient httpClient() {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(properties.getTransportConnectionTimeout())
            .setConnectionRequestTimeout(properties.getTransportReadTimeout())
            .setSocketTimeout(properties.getTransportSocketTimeout()).build();
    //        CredentialsProvider provider = new BasicCredentialsProvider();
    //        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(properties.getCrbaTransunionTransportUsername(), properties.getCrbaTransunionTransportPassword());
    //        provider.setCredentials(AuthScope.ANY, credentials);

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(properties.getPoolHostMax());
    connManager.setDefaultMaxPerRoute(properties.getPoolDefaultMaxPerhost());
    connManager.setValidateAfterInactivity(properties.getPoolValidateAfterActivity());

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            //                .setDefaultCredentialsProvider(provider)
            .setConnectionManager(connManager).evictExpiredConnections()
            .addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();

}

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {//w  w  w.  j  ava  2  s  .c  o  m
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}

From source file:com.feedeo.web.client.AbstractWebClient.java

protected HttpClient createHttpClient() {

    final SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();

    final ConnectionConfig connectionConfig = ConnectionConfig.custom().build();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
            .setConnectTimeout(30000).setSocketTimeout(30000).setStaleConnectionCheckEnabled(false).build();

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(256);/*from  w  w w. ja  va2s . co m*/
    connectionManager.setDefaultMaxPerRoute(256);

    IdleConnectionMonitorThread staleMonitor = new IdleConnectionMonitorThread(connectionManager);
    staleMonitor.start();

    try {
        staleMonitor.join(1000);
    } catch (InterruptedException ignored) {
    }

    final ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator iterator = new BasicHeaderElementIterator(
                    response.headerIterator(CONN_KEEP_ALIVE));
            while (iterator.hasNext()) {
                HeaderElement header = iterator.nextElement();
                String param = header.getName();
                String value = header.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 5 * 1000;
        }
    };

    return HttpClientBuilder.create().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig)
            .setDefaultConnectionConfig(connectionConfig).setKeepAliveStrategy(connectionKeepAliveStrategy)
            .build();
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }//  w w  w  .j a v  a 2 s . co  m
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:org.apache.gobblin.http.ApacheHttpClient.java

private HttpClientConnectionManager getHttpConnManager(Config config) {
    HttpClientConnectionManager httpConnManager;

    String connMgrStr = config.getString(HTTP_CONN_MANAGER);
    switch (ConnManager.valueOf(connMgrStr.toUpperCase())) {
    case BASIC:/* ww  w  .  jav  a 2  s . c  o m*/
        httpConnManager = new BasicHttpClientConnectionManager();
        break;
    case POOLING:
        PoolingHttpClientConnectionManager poolingConnMgr = new PoolingHttpClientConnectionManager();
        poolingConnMgr.setMaxTotal(config.getInt(POOLING_CONN_MANAGER_MAX_TOTAL_CONN));
        poolingConnMgr.setDefaultMaxPerRoute(config.getInt(POOLING_CONN_MANAGER_MAX_PER_CONN));
        httpConnManager = poolingConnMgr;
        break;
    default:
        throw new IllegalArgumentException(connMgrStr + " is not supported");
    }

    LOG.info("Using " + httpConnManager.getClass().getSimpleName());
    return httpConnManager;
}