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

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

Introduction

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

Prototype

public void setDefaultMaxPerRoute(final int max) 

Source Link

Usage

From source file:dk.deck.resolver.ArtifactResolverRemote.java

public ArtifactResolverRemote(List<String> repositories, String username, String password) {
    this.repositories = Collections.unmodifiableList(repositories);
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(MAX_HTTP_THREADS);
    connectionManager.setDefaultMaxPerRoute(MAX_HTTP_THREADS);
    httpclient = new DefaultHttpClient(connectionManager);

    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from   ww w  .  j ava 2 s .com
    authpref.add(AuthPolicy.DIGEST);
    httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

}

From source file:org.sentilo.common.rest.impl.RESTClientImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    if (httpClient == null) {
        final PoolingClientConnectionManager pccm = new PoolingClientConnectionManager();
        // Increase max total connection to 400
        pccm.setMaxTotal(400);/*from  w w  w.j a  v  a  2 s .  c  om*/
        // Increase default max connection per route to 50
        pccm.setDefaultMaxPerRoute(50);

        httpClient = new DefaultHttpClient(pccm);
        // Set the timeouts for read the response and create a connection
        setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
        setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
    }

    if (interceptors != null && httpClient instanceof DefaultHttpClient) {
        for (final HttpRequestInterceptor interceptor : interceptors) {
            ((DefaultHttpClient) httpClient).addRequestInterceptor(interceptor);
        }
    }

    if (credentials != null && httpClient instanceof DefaultHttpClient) {
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);

    }
}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

private HttpClient getHttpClient() {
    if (this.httpClient == null) {
        DefaultHttpClient newDefaultHttpClient = null;

        if (getUsername() != null || getPassword() != null) {
            try {
                final IProxyService proxyService = LiferayCore.getProxyService();

                URI uri = new URI("http://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                IProxyData[] proxyDataForHost = proxyService.select(uri);

                for (IProxyData data : proxyDataForHost) {
                    if (data.getHost() != null && data.getPort() > 0) {
                        SchemeRegistry schemeRegistry = new SchemeRegistry();
                        schemeRegistry.register(
                                new Scheme("http", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
                        cm.setMaxTotal(200);
                        cm.setDefaultMaxPerRoute(20);

                        DefaultHttpClient newHttpClient = new DefaultHttpClient(cm);
                        HttpHost proxy = new HttpHost(data.getHost(), data.getPort());

                        newHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        newDefaultHttpClient = newHttpClient;
                        break;
                    }//from  ww w  .  j av  a2s. c om
                }

                if (newDefaultHttpClient == null) {
                    uri = new URI("SOCKS://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                    proxyDataForHost = proxyService.select(uri);

                    for (IProxyData data : proxyDataForHost) {
                        if (data.getHost() != null) {
                            DefaultHttpClient newHttpClient = new DefaultHttpClient();
                            newHttpClient.getParams().setParameter("socks.host", data.getHost()); //$NON-NLS-1$
                            newHttpClient.getParams().setParameter("socks.port", data.getPort()); //$NON-NLS-1$
                            newHttpClient.getConnectionManager().getSchemeRegistry().register(
                                    new Scheme("socks", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                            newDefaultHttpClient = newHttpClient;
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                LiferayCore.logError("Unable to read proxy data", e); //$NON-NLS-1$
            }

            if (newDefaultHttpClient == null) {
                newDefaultHttpClient = new DefaultHttpClient();
            }

            this.httpClient = newDefaultHttpClient;
        } else {
            this.httpClient = new DefaultHttpClient();
        }
    }

    return this.httpClient;
}

From source file:org.string_db.psicquic.ws.StringdbSolrBasedPsicquicRestService.java

protected HttpClient createHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);

    HttpClient httpClient = new DefaultHttpClient(cm);

    String proxyHost = config.getProxyHost();
    String proxyPort = config.getProxyPort();

    if (isValueSet(proxyHost) && proxyHost.trim().length() > 0 && isValueSet(proxyPort)
            && proxyPort.trim().length() > 0) {
        try {//from w  w  w . j a  v a 2 s . c o m
            HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            logger.error("Impossible to create proxy host:" + proxyHost + ", port:" + proxyPort, e);
        }
    }

    return httpClient;
}

From source file:edu.cornell.mannlib.vitro.webapp.dao.jena.SparqlGraph.java

/**
 * Returns a SparqlGraph for a particular named graph in a remote repository 
 * @param endpointURI/*from  w  w  w  .java 2  s .  com*/
 * @param graphURI
 */
public SparqlGraph(String endpointURI, String graphURI) {
    this.endpointURI = endpointURI;
    this.graphURI = graphURI;

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setDefaultMaxPerRoute(50);
    this.httpClient = new DefaultHttpClient(cm);
}

From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java

/**
 * Creates PoolingClientConnectionManager
 *
 * @param url//from  ww w  .j a  v a2  s  . co m
 * @param port
 *
 * @return {@link ClientConnectionManager}
 */
private ClientConnectionManager createPoolingClientConnectionManager(String url, int port) {
    SchemeRegistry schemeRegistry = createSchemeRegistry(url, port);

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(MAX_CONNECTIONS);
    cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    cm.setMaxPerRoute(new HttpRoute(new HttpHost(getHost(url), getPort(url, port))), MAX_CONNECTIONS_PER_HOST);

    return cm;
}

From source file:com.alibaba.dubbo.rpc.protocol.rest.RestProtocol.java

protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }/*from  www  .j a  v a2 s. c o  m*/

    // TODO more configs to add

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

    connectionMonitor.addConnectionManager(connectionManager);

    //        BasicHttpContext localContext = new BasicHttpContext();

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

    httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
        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")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            // TODO constant
            return 30 * 1000;
        }
    });

    HttpParams params = httpClient.getParams();
    // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
    HttpConnectionParams.setConnectionTimeout(params,
            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
    HttpConnectionParams.setSoTimeout(params,
            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSoKeepalive(params, true);

    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);

    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }

    // TODO protocol
    ResteasyWebTarget target = client
            .target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
    return target.proxy(serviceType);
}

From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java

public LDClient(ClientConfiguration config) {
    log.info("Initialising Linked Data Client Service ...");

    this.config = config;

    endpoints = new ArrayList<>();
    for (Endpoint endpoint : defaultEndpoints) {
        endpoints.add(endpoint);/*  w  w  w . ja  va  2s . co m*/
    }
    endpoints.addAll(config.getEndpoints());

    Collections.sort(endpoints);
    if (log.isInfoEnabled()) {
        for (Endpoint endpoint : endpoints) {
            log.info("- LDClient Endpoint: {}", endpoint.getName());
        }
    }

    providers = new ArrayList<>();
    for (DataProvider provider : defaultProviders) {
        providers.add(provider);
    }
    providers.addAll(config.getProviders());
    if (log.isInfoEnabled()) {
        for (DataProvider provider : providers) {
            log.info("- LDClient Provider: {}", provider.getName());
        }
    }

    retrievalSemaphore = new Semaphore(config.getMaxParallelRequests());

    if (config.getHttpClient() != null) {
        log.debug("Using HttpClient provided in the configuration");
        this.client = config.getHttpClient();
    } else {
        log.debug("Creating default HttpClient based on the configuration");

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient");

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", 443, sf));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(10);

        DefaultHttpClient client = new DefaultHttpClient(cm, httpParams);
        client.setRedirectStrategy(new LMFRedirectStrategy());
        client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager());
        idleConnectionMonitorThread.start();

        this.client = client;
    }
}

From source file:org.apache.stratos.integration.tests.rest.RestClient.java

public RestClient() {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    // Increase max total connection to 200
    cm.setMaxTotal(200);//  ww  w  . j  a v a 2s. c  o  m
    // Increase default max connection per route to 50
    cm.setDefaultMaxPerRoute(50);

    httpClient = new DefaultHttpClient(cm);
    httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient);
}

From source file:com.alibaba.dubbo.rpc.protocol.resteasy.RestProtocol.java

protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }/*from   w ww .ja v a  2 s .  c  o m*/

    // TODO more configs to add

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

    connectionMonitor.addConnectionManager(connectionManager);

    // BasicHttpContext localContext = new BasicHttpContext();

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

    httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
        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")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            // TODO constant
            return 30 * 1000;
        }
    });

    HttpParams params = httpClient.getParams();
    // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
    HttpConnectionParams.setConnectionTimeout(params,
            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
    HttpConnectionParams.setSoTimeout(params,
            url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSoKeepalive(params, true);

    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/* , localContext */);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);

    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }

    // dubbo ?
    String version = url.getParameter(Constants.VERSION_KEY);
    String versionPath = "";
    if (StringUtils.isNotEmpty(version)) {
        versionPath = version + "/";
    }
    // TODO protocol
    ResteasyWebTarget target = client
            .target("http://" + url.getHost() + ":" + url.getPort() + "/" + versionPath + getContextPath(url));
    return target.proxy(serviceType);
}