Example usage for org.apache.http.client.params HttpClientParams setConnectionManagerTimeout

List of usage examples for org.apache.http.client.params HttpClientParams setConnectionManagerTimeout

Introduction

In this page you can find the example usage for org.apache.http.client.params HttpClientParams setConnectionManagerTimeout.

Prototype

public static void setConnectionManagerTimeout(final HttpParams params, final long timeout) 

Source Link

Document

Set the parameter ClientPNames.CONN_MANAGER_TIMEOUT .

Usage

From source file:com.seajas.search.contender.http.ParameterizableHttpClient.java

/**
 * Default constructor.//from  w w  w .  j  a  v  a 2  s.c om
 * 
 * @param connectionManager
 * @param parameters
 * @param httpHost
 * @param httpPort
 * @param userAgent
 * @param connectionTimeout
 */
public ParameterizableHttpClient(final ClientConnectionManager connectionManager, final HttpParams parameters,
        final String httpHost, final Integer httpPort, final String userAgent,
        final Integer connectionTimeout) {
    super(connectionManager, parameters);

    if (!StringUtils.isEmpty(httpHost))
        ConnRouteParams.setDefaultProxy(getParams(), new HttpHost(httpHost, httpPort));
    HttpProtocolParams.setUserAgent(getParams(), userAgent);

    if (connectionTimeout > 0) {
        HttpConnectionParams.setSoTimeout(getParams(), connectionTimeout);
        HttpConnectionParams.setConnectionTimeout(getParams(), connectionTimeout);
        HttpClientParams.setConnectionManagerTimeout(getParams(), connectionTimeout);
    }

    setRedirectStrategy(new DefaultRedirectStrategy());
}

From source file:uk.co.visalia.brightpearl.apiclient.http.httpclient4.HttpClient4ClientFactory.java

private void createClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeoutMs);
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeoutMs);
    HttpClientParams.setRedirecting(httpParams, allowRedirects);
    HttpClientParams.setConnectionManagerTimeout(httpParams, connectionManagerTimeoutMs);

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

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(maxConnections);
    connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);

    this.client = new HttpClient4Client(httpClient);
}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }//from   w  w w . j a v a2  s .c  o m

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param url/*from  w  w  w .j a  v a2 s. c  o  m*/
 *            the remote Solr URL. A default localhost URL is assumed when null.
 * @param coreNames
 *            the Solr core names for the main collection and the webgraph
 * @param defaultCoreName
 *            the core name of the main collection
 * @param timeout
 *            the connection timeout in milliseconds
 * @param trustSelfSignedOnAuthenticatedServer
 *            when true, self-signed certificates are accepcted for an https
 *            connection to a remote server with authentication credentials
 * @param maxBytesPerReponse
 *            maximum acceptable decompressed size in bytes for a response from
 *            the remote Solr server. Negative value or Long.MAX_VALUE means no
 *            limit.
 * @param concurrentUpdates
 *            when true, the instance will be used for update operations. The
 *            Solr client is adjusted for better performance of multiple
 *            updates.
 * @throws IOException
 *             when a connection could not be opened to the remote Solr instance
 */
public RemoteInstance(final String url, final Collection<String> coreNames, final String defaultCoreName,
        final int timeout, final boolean trustSelfSignedOnAuthenticatedServer, final long maxBytesPerResponse,
        final boolean concurrentUpdates) throws IOException {
    this.timeout = timeout;
    this.concurrentUpdates = concurrentUpdates;
    this.server = new HashMap<String, SolrClient>();
    this.solrurl = url == null ? "http://127.0.0.1:8983/solr/" : url; // that should work for the example configuration of solr 4.x.x
    this.coreNames = coreNames == null ? new ArrayList<String>() : coreNames;
    if (this.coreNames.size() == 0) {
        this.coreNames.add(CollectionSchema.CORE_NAME);
        this.coreNames.add(WebgraphSchema.CORE_NAME);
    }
    this.defaultCoreName = defaultCoreName == null ? CollectionSchema.CORE_NAME : defaultCoreName;
    if (!this.coreNames.contains(this.defaultCoreName))
        this.coreNames.add(this.defaultCoreName);

    // check the url
    if (this.solrurl.endsWith("/")) {
        // this could mean that we have a path without a core name (correct)
        // or that the core name is appended and contains a badly '/' at the end (must be corrected)
        if (this.solrurl.endsWith(this.defaultCoreName + "/")) {
            this.solrurl = this.solrurl.substring(0, this.solrurl.length() - this.defaultCoreName.length() - 1);
        }
    } else {
        // this could mean that we have an url which ends with the core name (must be corrected)
        // or that the url has a mising '/' (must be corrected)
        if (this.solrurl.endsWith(this.defaultCoreName)) {
            this.solrurl = this.solrurl.substring(0, this.solrurl.length() - this.defaultCoreName.length());
        } else {
            this.solrurl = this.solrurl + "/";
        }
    }

    // Make a http client, connect using authentication. An url like
    // http://127.0.0.1:8983/solr/shard0
    // is proper, and contains the core name as last element in the path
    final MultiProtocolURL u;
    try {
        u = new MultiProtocolURL(this.solrurl + this.defaultCoreName);
    } catch (final MalformedURLException e) {
        throw new IOException(e.getMessage());
    }
    String solraccount, solrpw;
    String host = u.getHost();
    final String userinfo = u.getUserInfo();
    if (userinfo == null || userinfo.isEmpty()) {
        solraccount = "";
        solrpw = "";
    } else {
        final int p = userinfo.indexOf(':');
        if (p < 0) {
            solraccount = userinfo;
            solrpw = "";
        } else {
            solraccount = userinfo.substring(0, p);
            solrpw = userinfo.substring(p + 1);
        }
    }
    if (solraccount.length() > 0) {
        this.client = buildCustomHttpClient(timeout, u, solraccount, solrpw, host,
                trustSelfSignedOnAuthenticatedServer, maxBytesPerResponse);
    } else if (u.isHTTPS()) {
        /* Here we must trust self-signed certificates as most peers with SSL enabled use such certificates */
        this.client = buildCustomHttpClient(timeout, u, solraccount, solrpw, host, true, maxBytesPerResponse);
    } else {
        /* Build a http client using the Solr utils as in the HttpSolrClient constructor implementation. 
         * The main difference is that a shared connection manager is used (configured in the buildConnectionManager() function) */
        final ModifiableSolrParams params = new ModifiableSolrParams();
        params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false);
        /* Accept gzip compression of responses to reduce network usage */
        params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true);

        /* Set the maximum time to establish a connection to the remote server */
        params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, this.timeout);
        /* Set the maximum time between data packets reception once a connection has been established */
        params.set(HttpClientUtil.PROP_SO_TIMEOUT, this.timeout);

        this.client = HttpClientUtil.createClient(params, CONNECTION_MANAGER);
        if (this.client instanceof DefaultHttpClient) {
            if (this.client.getParams() != null) {
                /* Set the maximum time to get a connection from the shared connections pool */
                HttpClientParams.setConnectionManagerTimeout(this.client.getParams(), timeout);
            }

            if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
                /*
                 * Add in last position the eventual interceptor limiting the response size, so
                 * that this is the decompressed amount of bytes that is considered
                 */
                ((DefaultHttpClient) this.client).addResponseInterceptor(
                        new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                        ((DefaultHttpClient) this.client).getResponseInterceptorCount());
            }
        }
    }

    this.defaultServer = getServer(this.defaultCoreName);
    if (this.defaultServer == null)
        throw new IOException("cannot connect to url " + url + " and connect core " + defaultCoreName);
}

From source file:com.centurylink.cloud.sdk.core.client.SdkClientBuilder.java

private BasicHttpParams initHttpParams() {
    BasicHttpParams params = new BasicHttpParams();
    if (socketTimeout > -1) {
        HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
    }//from w  ww  .jav  a  2s. com

    if (establishConnectionTimeout > -1) {
        HttpConnectionParams.setConnectionTimeout(params,
                (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
    }

    if (connectionCheckoutTimeoutMs > -1) {
        HttpClientParams.setConnectionManagerTimeout(params, connectionCheckoutTimeoutMs);
    }

    return params;
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse/*from  w w  w.  jav a2s  . c om*/
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}