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

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

Introduction

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

Prototype

public void setMaxPerRoute(final HttpRoute route, final int max) 

Source Link

Usage

From source file:dal.arris.DeviceDAO.java

private void prepare() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);/*from   ww w .  j  a  v  a2  s . c  o m*/
    cm.setDefaultMaxPerRoute(1);
    HttpHost ip = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(ip), 50);

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

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

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

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

}

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  ww  .j  av  a 2 s.co m*/
    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:org.cleverbus.core.common.ws.transport.http.CloseableHttpComponentsMessageSender.java

/**
 * Sets the maximum number of connections per host for the underlying HttpClient. The maximum number of connections
 * per host can be set in a form accepted by the {@code java.util.Properties} class, like as follows:
 * <p/>//from  w  w w.j  a v a2s. c  om
 * <pre>
 * https://esb.cleverbus.org/esb/=1
 * http://esb.cleverbus.org:8080/esb/=7
 * http://esb.cleverbus.org/esb/=10
 * </pre>
 * <p/>
 * The host can be specified as a URI (with scheme and port).
 *
 * @param maxConnectionsPerHost a properties object specifying the maximum number of connection
 * @see PoolingHttpClientConnectionManager#setMaxPerRoute(org.apache.http.conn.routing.HttpRoute, int)
 */
@Override
public void setMaxConnectionsPerHost(Map<String, String> maxConnectionsPerHost) throws URISyntaxException {
    for (Map.Entry<String, String> entry : maxConnectionsPerHost.entrySet()) {
        URI uri = new URI(entry.getKey());
        HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        HttpRoute route = new HttpRoute(host);

        PoolingHttpClientConnectionManager connectionManager = (PoolingHttpClientConnectionManager) getConnPoolControl();

        int max = Integer.parseInt(entry.getValue());
        connectionManager.setMaxPerRoute(route, max);
        BasicScheme basicAuth = new BasicScheme();
        authCache.get().put(host, basicAuth);
    }
}

From source file:org.artifactory.util.HttpClientConfigurator.java

/**
 * Creates custom Http Client connection pool to be used by Http Client
 *
 * @return {@link PoolingHttpClientConnectionManager}
 *///from   ww w. j av a2  s.c om
private PoolingHttpClientConnectionManager createConnectionMgr() {
    PoolingHttpClientConnectionManager connectionMgr;
    connectionMgr = new PoolingHttpClientConnectionManager(INACTIVITY_TIMEOUT, TimeUnit.MILLISECONDS);
    connectionMgr.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionMgr.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_HOST);
    HttpHost localhost = new HttpHost(LOCALHOST, DEFAULT_PORT);
    connectionMgr.setMaxPerRoute(new HttpRoute(localhost), DEFAULT_POOL_MAX_CONNECTIONS_PER_ROUTE);
    return connectionMgr;
}

From source file:org.jasig.cas.util.http.SimpleHttpClientFactoryBean.java

/**
 * Build a HTTP client based on the current properties.
 *
 * @return the built HTTP client// w ww  .  j av a 2  s  .c o m
 */
private CloseableHttpClient buildHttpClient() {
    try {

        final ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        final LayeredConnectionSocketFactory sslsf = this.sslSocketFactory;

        final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslsf).build();

        final PoolingHttpClientConnectionManager connMgmr = new PoolingHttpClientConnectionManager(registry);
        connMgmr.setMaxTotal(this.maxPooledConnections);
        connMgmr.setDefaultMaxPerRoute(this.maxConnectionsPerRoute);

        final HttpHost httpHost = new HttpHost(InetAddress.getLocalHost());
        final HttpRoute httpRoute = new HttpRoute(httpHost);
        connMgmr.setMaxPerRoute(httpRoute, MAX_CONNECTIONS_PER_ROUTE);

        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.readTimeout)
                .setConnectTimeout(this.connectionTimeout).setConnectionRequestTimeout(this.connectionTimeout)
                .setStaleConnectionCheckEnabled(true).setCircularRedirectsAllowed(this.circularRedirectsAllowed)
                .setRedirectsEnabled(this.redirectsEnabled).setAuthenticationEnabled(this.authenticationEnabled)
                .build();

        final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connMgmr)
                .setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf)
                .setSSLHostnameVerifier(this.hostnameVerifier).setRedirectStrategy(this.redirectionStrategy)
                .setDefaultCredentialsProvider(this.credentialsProvider).setDefaultCookieStore(this.cookieStore)
                .setConnectionReuseStrategy(this.connectionReuseStrategy)
                .setConnectionBackoffStrategy(this.connectionBackoffStrategy)
                .setServiceUnavailableRetryStrategy(this.serviceUnavailableRetryStrategy)
                .setProxyAuthenticationStrategy(this.proxyAuthenticationStrategy)
                .setDefaultHeaders(this.defaultHeaders).useSystemProperties();

        return builder.build();

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.floragunn.searchguard.HeaderAwareJestClientFactory.java

protected HttpClientConnectionManager createConnectionManager() {
    if (httpClientConfig.isMultiThreaded()) {
        log.debug("Multi-threaded http connection manager created");
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
        if (maxTotal != null) {
            cm.setMaxTotal(maxTotal);/*from   w  w  w  .  j ava  2  s.co m*/
        }
        final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
        if (defaultMaxPerRoute != null) {
            cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        }
        final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
        for (final HttpRoute route : maxPerRoute.keySet()) {
            cm.setMaxPerRoute(route, maxPerRoute.get(route));
        }
        return cm;
    }
    log.debug("Default http connection is created without multi threaded option");
    return new BasicHttpClientConnectionManager();
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Initialize the maximum connections for the given pool
 * // w w  w  . j av  a  2s. co  m
 * @param pool
 *            a pooling connection manager. Must not be null.
 * @param maxConnections.
 *            The new maximum connections values. Must be greater than 0.
 * @throws IllegalArgumentException
 *             when pool is null or when maxConnections is lower than 1
 */
public static void initPoolMaxConnections(final PoolingHttpClientConnectionManager pool, int maxConnections) {
    if (pool == null) {
        throw new IllegalArgumentException("pool parameter must not be null");
    }
    if (maxConnections <= 0) {
        throw new IllegalArgumentException("maxConnections parameter must be greater than zero");
    }
    pool.setMaxTotal(maxConnections);
    // for statistics same value should also be set here
    ConnectionInfo.setMaxcount(maxConnections);

    // connections per host (2 default)
    pool.setDefaultMaxPerRoute((int) (2 * Memory.cores()));

    // Increase max connections for localhost
    final HttpHost localhost = new HttpHost(Domains.LOCALHOST);
    pool.setMaxPerRoute(new HttpRoute(localhost), maxConnections);
}

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

private CloseableHttpClient httpClient() throws ClientException {

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry());

    Map<String, Object> httpClientMap = (Map<String, Object>) config.get(SYNC);
    connectionManager.setMaxTotal((Integer) httpClientMap.get(MAX_CONNECTION_TOTAL));
    connectionManager.setDefaultMaxPerRoute((Integer) httpClientMap.get(MAX_CONNECTION_PER_ROUTE));
    // Now handle all the specific route defined.
    Map<String, Object> routeMap = (Map<String, Object>) httpClientMap.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);
    }/*from  w w  w  .ja v  a 2s . c om*/
    final int timeout = (Integer) httpClientMap.get(TIMEOUT);
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build();
    final long keepAliveMilliseconds = (Integer) httpClientMap.get(KEEP_ALIVE);
    return HttpClientBuilder.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:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java

public AbstractRestClient(URL httpUrl) {
    super(httpUrl);

    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
        @Override// www  . j a va2 s  .  c o  m
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {
                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }
            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {
                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }
            };
        }
    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    SSLContext sslcontext = SSLContexts.createSystemDefault();
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost") || host.equalsIgnoreCase("localhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);

    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    CookieStore cookieStore = new BasicCookieStore();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectionRequestTimeout(3000)
            .setConnectTimeout(3000).setSocketTimeout(3000).build();

    client = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider)
            //            .setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();
}