Example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager setMaxForRoute

List of usage examples for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager setMaxForRoute

Introduction

In this page you can find the example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager setMaxForRoute.

Prototype

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

Source Link

Usage

From source file:org.iglootools.hchelpers.core.DefaultHttpClientFactory.java

public static ThreadSafeClientConnManager threadSafeClientConnManager(
        Map<HttpRoute, Integer> maxNumberOfConnectionsPerRoute, int maxNumberOfConnections,
        int defaultMaxNumberOfConnectionsPerRoute) {
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(defaultSchemeRegistry());
    cm.setMaxTotal(maxNumberOfConnections);
    cm.setDefaultMaxPerRoute(defaultMaxNumberOfConnectionsPerRoute);

    for (HttpRoute r : maxNumberOfConnectionsPerRoute.keySet()) {
        cm.setMaxForRoute(r, maxNumberOfConnectionsPerRoute.get(r));
    }//  ww w.jav  a2  s  . c o m

    return cm;
}

From source file:com.basho.riak.client.raw.http.HTTPClusterClient.java

@Override
protected RawClient[] fromConfig(ClusterConfig<HTTPClientConfig> clusterConfig) throws IOException {
    List<RawClient> clients = new ArrayList<RawClient>();
    int maxTotal = clusterConfig.getTotalMaximumConnections();

    // IE limitless
    if (maxTotal == ClusterConfig.UNLIMITED_CONNECTIONS) {
        // independent pools, independent clients
        HTTPRiakClientFactory fac = HTTPRiakClientFactory.getInstance();
        for (HTTPClientConfig node : clusterConfig.getClients()) {
            clients.add(fac.newClient(node));
        }/*from   w  ww .  j  a v a 2  s.  c o  m*/
    } else {
        // create a ThreadSafeClientConnManager to be shared by all the
        // RiakClient instances
        // in the cluster
        // add a route per host and a max per route
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
        cm.setMaxTotal(maxTotal);

        for (HTTPClientConfig node : clusterConfig.getClients()) {
            if (node.getMaxConnections() != null) {
                cm.setMaxForRoute(makeRoute(node.getUrl()), node.getMaxConnections());
            }
            DefaultHttpClient httpClient = new DefaultHttpClient(cm);

            if (node.getRetryHandler() != null) {
                httpClient.setHttpRequestRetryHandler(node.getRetryHandler());
            }

            RiakConfig riakConfig = new RiakConfig(node.getUrl());
            riakConfig.setMapReducePath(node.getMapreducePath());
            riakConfig.setTimeout(node.getTimeout());
            riakConfig.setHttpClient(httpClient);

            clients.add(new HTTPClientAdapter(new RiakClient(riakConfig)));
        }
    }
    return clients.toArray(new RawClient[clients.size()]);
}

From source file:com.bigdata.rdf.sail.webapp.client.DefaultClientConnectionManagerFactory.java

public ClientConnectionManager newInstance() {

    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(newSchemeRegistry());

    // Increase max total connection to 200
    cm.setMaxTotal(200);//  w w  w. java2  s.  co m

    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    // Increase max connections for localhost to 50
    final HttpHost localhost = new HttpHost("locahost");

    cm.setMaxForRoute(new HttpRoute(localhost), 50);

    return cm;

}

From source file:com.bigdata.rdf.sail.webapp.AbstractProtocolTest.java

protected ClientConnectionManager newInstance() {

    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(newSchemeRegistry());

    // Increase max total connection to 200
    cm.setMaxTotal(200);//from ww  w.  j a  v  a 2 s .c om

    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    // Increase max connections for localhost to 50
    final HttpHost localhost = new HttpHost("locahost");

    cm.setMaxForRoute(new HttpRoute(localhost), 50);

    return cm;

}

From source file:com.alu.e3.gateway.loadbalancer.E3HttpClientConfigurer.java

/**
 * Configures the ClientConnectionManager
 * @param clientConnectionManager to be set
 *///from   ww w. j a  v a2  s .c o m
private void setThreadSafeConnectionManager(ClientConnectionManager clientConnectionManager) {

    ThreadSafeClientConnManager threadSafeclientConnectionManager = (ThreadSafeClientConnManager) clientConnectionManager;

    // set HttpClient connection pool : global and default values
    threadSafeclientConnectionManager.setMaxTotal(getMaxConnectionsPool());
    threadSafeclientConnectionManager.setDefaultMaxPerRoute(getConnectionsPerRoute());

    // set HttpClient connection pool : max connection per route
    if (connectionsPerRoutes != null) {
        Set<TargetHost> targetHosts = connectionsPerRoutes.keySet();

        for (TargetHost targetHost : targetHosts) {
            try {
                HttpRoute route = getHttpRoute(targetHost);
                threadSafeclientConnectionManager.setMaxForRoute(route, connectionsPerRoutes.get(targetHost));
            } catch (MalformedURLException e) {
                LOGGER.warn("Unable to set a max connection for route [" + targetHost.getUrl() + "]", e);
            }
        }
    }
}

From source file:org.mobicents.client.slee.resource.http.HttpClientResourceAdaptor.java

public void raActive() {
    activities = new ConcurrentHashMap<HttpClientActivityHandle, HttpClientActivity>();
    executorService = Executors.newCachedThreadPool();
    if (httpClientFactory != null) {
        httpclient = httpClientFactory.newHttpClient();
    } else {/*from   w  w  w  . j a  va2  s .c  o m*/
        HttpParams params = new SyncBasicHttpParams();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(
                schemeRegistry);
        threadSafeClientConnManager.setMaxTotal(maxTotal);
        for (Entry<HttpRoute, Integer> entry : maxForRoutes.entrySet()) {
            if (tracer.isInfoEnabled()) {
                tracer.info(
                        String.format("Configuring MaxForRoute %s max %d", entry.getKey(), entry.getValue()));
            }
            threadSafeClientConnManager.setMaxForRoute(entry.getKey(), entry.getValue());
        }
        httpclient = new DefaultHttpClient(threadSafeClientConnManager, params);
    }
    isActive = true;
    if (tracer.isInfoEnabled()) {
        tracer.info(String.format("HttpClientResourceAdaptor=%s entity activated.",
                this.resourceAdaptorContext.getEntityName()));
    }
}

From source file:com.marklogic.client.impl.JerseyServices.java

private void connect(String host, int port, String database, String user, String password,
        Authentication authenType, SSLContext context, X509HostnameVerifier verifier) {
    if (logger.isDebugEnabled())
        logger.debug("Connecting to {} at {} as {}", new Object[] { host, port, user });

    if (host == null)
        throw new IllegalArgumentException("No host provided");

    if (authenType == null) {
        if (context != null) {
            authenType = Authentication.BASIC;
        }/* w  w  w.j  ava2s. c  o m*/
    }

    if (authenType != null) {
        if (user == null)
            throw new IllegalArgumentException("No user provided");
        if (password == null)
            throw new IllegalArgumentException("No password provided");
    }

    if (connection != null)
        connection = null;
    if (client != null) {
        client.destroy();
        client = null;
    }

    this.database = database;

    String baseUri = ((context == null) ? "http" : "https") + "://" + host + ":" + port + "/v1/";

    Properties props = System.getProperties();

    if (props.containsKey(MAX_DELAY_PROP)) {
        String maxDelayStr = props.getProperty(MAX_DELAY_PROP);
        if (maxDelayStr != null && maxDelayStr.length() > 0) {
            int max = Integer.parseInt(maxDelayStr);
            if (max > 0) {
                maxDelay = max * 1000;
            }
        }
    }
    if (props.containsKey(MIN_RETRY_PROP)) {
        String minRetryStr = props.getProperty(MIN_RETRY_PROP);
        if (minRetryStr != null && minRetryStr.length() > 0) {
            int min = Integer.parseInt(minRetryStr);
            if (min > 0) {
                minRetry = min;
            }
        }
    }

    // TODO: integrated control of HTTP Client and Jersey Client logging
    if (!props.containsKey("org.apache.commons.logging.Log")) {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    }
    if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http")) {
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "warn");
    }
    if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http.wire")) {
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "warn");
    }

    Scheme scheme = null;
    if (context == null) {
        SchemeSocketFactory socketFactory = PlainSocketFactory.getSocketFactory();
        scheme = new Scheme("http", port, socketFactory);
    } else {
        SSLSocketFactory socketFactory = new SSLSocketFactory(context, verifier);
        scheme = new Scheme("https", port, socketFactory);
    }
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(scheme);

    int maxRouteConnections = 100;
    int maxTotalConnections = 2 * maxRouteConnections;

    /*
     * 4.2 PoolingClientConnectionManager connMgr = new
     * PoolingClientConnectionManager(schemeRegistry);
     * connMgr.setMaxTotal(maxTotalConnections);
     * connMgr.setDefaultMaxPerRoute(maxRouteConnections);
     * connMgr.setMaxPerRoute( new HttpRoute(new HttpHost(baseUri)),
     *     maxRouteConnections);
     */
    // start 4.1
    ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(schemeRegistry);
    connMgr.setMaxTotal(maxTotalConnections);
    connMgr.setDefaultMaxPerRoute(maxRouteConnections);
    connMgr.setMaxForRoute(new HttpRoute(new HttpHost(baseUri)), maxRouteConnections);
    // end 4.1

    // CredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();
    // credentialsProvider.setCredentials(new AuthScope(host, port),
    // new UsernamePasswordCredentials(user, password));

    HttpParams httpParams = new BasicHttpParams();

    if (authenType != null) {
        List<String> authpref = new ArrayList<String>();

        if (authenType == Authentication.BASIC)
            authpref.add(AuthPolicy.BASIC);
        else if (authenType == Authentication.DIGEST)
            authpref.add(AuthPolicy.DIGEST);
        else
            throw new MarkLogicInternalException(
                    "Internal error - unknown authentication type: " + authenType.name());

        httpParams.setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    }

    httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    // HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

    // long-term alternative to isFirstRequest alive
    // HttpProtocolParams.setUseExpectContinue(httpParams, false);
    // httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000);

    DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config();
    Map<String, Object> configProps = config.getProperties();
    configProps.put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, false);
    configProps.put(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES, true);
    configProps.put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, connMgr);
    // ignored?
    configProps.put(ApacheHttpClient4Config.PROPERTY_FOLLOW_REDIRECTS, false);
    // configProps.put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER,
    // credentialsProvider);
    configProps.put(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS, httpParams);
    // switches from buffered to streamed in Jersey Client
    configProps.put(ApacheHttpClient4Config.PROPERTY_CHUNKED_ENCODING_SIZE, 32 * 1024);

    client = ApacheHttpClient4.create(config);

    // System.setProperty("javax.net.debug", "all"); // all or ssl

    if (authenType == null) {
        checkFirstRequest = false;
    } else if (authenType == Authentication.BASIC) {
        checkFirstRequest = false;

        client.addFilter(new HTTPBasicAuthFilter(user, password));
    } else if (authenType == Authentication.DIGEST) {
        checkFirstRequest = true;

        // workaround for JerseyClient bug 1445
        client.addFilter(new DigestChallengeFilter());

        client.addFilter(new HTTPDigestAuthFilter(user, password));
    } else {
        throw new MarkLogicInternalException(
                "Internal error - unknown authentication type: " + authenType.name());
    }

    // client.addFilter(new LoggingFilter(System.err));

    connection = client.resource(baseUri);
}