List of usage examples for org.apache.http.params HttpConnectionParams setSoKeepalive
public static void setSoKeepalive(HttpParams httpParams, boolean z)
From source file:org.apache.camel.component.box.internal.LongPollingEventsManager.java
public LongPollingEventsManager(CachedBoxClient boxClient, Map<String, Object> httpParams, ExecutorService executorService) { this.cachedBoxClient = boxClient; this.executorService = executorService; this.httpParams = new BasicHttpParams(); HttpConnectionParams.setSoKeepalive(this.httpParams, true); if (httpParams != null) { for (Map.Entry<String, Object> entry : httpParams.entrySet()) { this.httpParams.setParameter(entry.getKey(), entry.getValue()); }/* w w w .ja v a2s.c o m*/ } }
From source file:com.amazonaws.services.dynamodbv2.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/*from w w w .j av a 2 s. c o m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public CloseableHttpAsyncClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive()); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams); CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault(); /* httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton); httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy()); if (config.getConnectionMaxIdleMillis() > 0) { httpClient.setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy( config.getConnectionMaxIdleMillis())); }*/ if (config.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress()); } try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory(); if (sf == null) { sf = new SdkTLSSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to access default SSL context", e); } /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); //httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); /*if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (config.isPreemptiveBasicProxyAuth()){ httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } */ /* Accept Gzip response if configured */ if (config.useGzip()) { /* httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName() .equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity( response.getEntity())); return; } } } } } });*/ } return httpClient; }
From source file:com.amazonaws.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/* w w w . ja v a 2 s .co m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive()); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } final SSLContext sslContext = createSSLContext(config); SSLSocketFactory sslSocketFactory = config.getApacheHttpClientConfig().getSslSocketFactory(); if (sslSocketFactory == null) { sslSocketFactory = new SdkTLSSocketFactory(sslContext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams, sslSocketFactory); SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams); httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton); httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy()); if (config.getConnectionMaxIdleMillis() > 0) { httpClient .setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(config.getConnectionMaxIdleMillis())); } if (config.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress()); } Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); Scheme https = new Scheme("https", 443, sslSocketFactory); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (config.isPreemptiveBasicProxyAuth()) { httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } /* Accept Gzip response if configured */ if (config.useGzip()) { httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); } return httpClient; }
From source file:com.autonomy.aci.client.transport.impl.HttpClientFactory.java
/** * Creates an instance of <tt>DefaultHttpClient</tt> with a <tt>ThreadSafeClientConnManager</tt>. * @return an implementation of the <tt>HttpClient</tt> interface. *///from w w w . j av a 2s .c o m public HttpClient createInstance() { LOGGER.debug("Creating a new instance of DefaultHttpClient with configuration -> {}", toString()); // Create the connection manager which will be default create the necessary schema registry stuff... final PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setMaxTotal(maxTotalConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); // Set the HTTP connection parameters (These are in the HttpCore JavaDocs, NOT the HttpClient ones)... final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setLinger(params, linger); HttpConnectionParams.setSocketBufferSize(params, socketBufferSize); HttpConnectionParams.setSoKeepalive(params, soKeepAlive); HttpConnectionParams.setSoReuseaddr(params, soReuseAddr); HttpConnectionParams.setSoTimeout(params, soTimeout); HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled); HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay); // Create the HttpClient and configure the compression interceptors if required... final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params); if (useCompression) { httpClient.addRequestInterceptor(new RequestAcceptEncoding()); httpClient.addResponseInterceptor(new DeflateContentEncoding()); } return httpClient; }
From source file:com.google.pubsub.clients.common.MetricsHandler.java
private void initialize() { synchronized (this) { try {/*from w w w . j a va 2s. c o m*/ HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped( Collections.singletonList("https://www.googleapis.com/auth/cloud-platform")); } monitoring = new Monitoring.Builder(transport, jsonFactory, credential) .setApplicationName("Cloud Pub/Sub Loadtest Framework").build(); String zoneId; String instanceId; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.addRequestInterceptor(new RequestAcceptEncoding()); httpClient.addResponseInterceptor(new ResponseContentEncoding()); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true); HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false); HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); httpClient.setKeepAliveStrategy((response, ctx) -> 30); HttpGet zoneIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/zone"); zoneIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest); String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity()); if (tempZoneId.lastIndexOf("/") >= 0) { zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1); } else { zoneId = tempZoneId; } HttpGet instanceIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/id"); instanceIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest); instanceId = EntityUtils.toString(instanceIdResponse.getEntity()); } catch (IOException e) { log.info("Unable to connect to metadata server, assuming not on GCE, setting " + "defaults for instance and zone."); instanceId = "local"; zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local. } monitoredResource.setLabels( ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId)); createMetrics(); } catch (IOException e) { log.error("Unable to initialize MetricsHandler, trying again.", e); executor.execute(this::initialize); } catch (GeneralSecurityException e) { log.error("Unable to initialize MetricsHandler permanently, credentials error.", e); } } }
From source file:org.alfresco.http.SharedHttpClientProvider.java
/** * See <a href="http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html">Connection management</a>. * /* w w w . j a va 2s . c om*/ * @param maxNumberOfConnections the maximum number of Http connections in the pool * @param connectionTimeoutMs the time to wait for a connection from the pool before failure * @param socketTimeoutMs the time to wait for data activity on a connection before failure * @param socketTtlMs the time for a socket to remain alive before being forcibly closed (0 for infinite) */ public SharedHttpClientProvider(int maxNumberOfConnections, int connectionTimeoutMs, int socketTimeoutMs, int socketTtlMs) { SSLSocketFactory sslSf = null; try { TrustStrategy sslTs = new TrustAnyTrustStrategy(); sslSf = new SSLSocketFactory(sslTs, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Throwable e) { throw new RuntimeException("Unable to construct HttpClientProvider.", e); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 8080, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, sslSf)); schemeRegistry.register(new Scheme("https", 80, sslSf)); httpClientCM = new PoolingClientConnectionManager(schemeRegistry, (long) socketTtlMs, TimeUnit.MILLISECONDS); // Increase max total connections httpClientCM.setMaxTotal(maxNumberOfConnections); // Ensure that we don't throttle on a per-scheme basis (BENCH-45) httpClientCM.setDefaultMaxPerRoute(maxNumberOfConnections); httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMs); HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMs); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setStaleCheckingEnabled(httpParams, true); HttpConnectionParams.setSoKeepalive(httpParams, true); }
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(); }/*w w w.j a v a 2s . c om*/ // 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: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 ww w . jav a 2s. c om // 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); }