List of usage examples for org.apache.http.conn.routing HttpRoute HttpRoute
public HttpRoute(final HttpHost target)
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 ww w. ja v a 2s. 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:com.sangupta.jerry.http.HttpExecutor.java
/** * Set maximum connections that will be operated over the given host on * given port, that will be handled by the underlying connection manager. * // w w w .j ava 2 s. c o m * @param hostName * the host name for which the limit needs to be set * * @param port * the port on which the limit needs to be set * * @param numConnections * the number of connections to set * * @throws IllegalArgumentException * if the number of connections is less than <code>ZERO</code> * * @throws IllegalArgumentException * if the host name is <code>null</code> or empty. */ public static void setMaxConnectionsOnHost(String hostName, int port, int numConnections) { if (AssertUtils.isEmpty(hostName)) { throw new IllegalArgumentException("Hostname cannot be null/empty"); } HttpRoute route = new HttpRoute(new HttpHost(hostName, port)); setMaxConnectionsOnHost(route, numConnections); }
From source file:org.bedework.util.http.BasicHttpClient.java
/** * @param host the host/*from www. j a v a2s . c o m*/ * @param port the port number * @param max number connections */ public static void setHostLimit(final String host, final int port, final int max) { HttpHost hostPort = new HttpHost(host, port); connManager.setMaxPerRoute(new HttpRoute(hostPort), max); }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
/** * Initialize the maximum connections for the given pool * //from ww w . j a va 2 s.c o 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.da.daum.DaumCafeBungImgList.java
private HttpClient getPoolHttpClient() { HttpClient httpclient;/*from w w w .j a v a2 s . c o m*/ 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); // Increase max total connection to 200 cm.setMaxTotal(200); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20); // Increase max connections for localhost:80 to 50 HttpHost localhost = new HttpHost("locahost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); //DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient = new DefaultHttpClient(cm); return httpclient; }
From source file:org.mobicents.client.slee.resource.http.HttpClientResourceAdaptor.java
@SuppressWarnings("unchecked") public void raVerifyConfiguration(ConfigProperties properties) throws InvalidConfigurationException { String httpClientFactoryClassName = (String) properties.getProperty(CFG_PROPERTY_HTTP_CLIENT_FACTORY) .getValue();/*from w ww. jav a 2 s.co m*/ if (httpClientFactoryClassName.isEmpty()) { try { Integer i = (Integer) properties.getProperty(CFG_PROPERTY_MAX_CONNECTIONS_TOTAL).getValue(); if (i < 1) { throw new InvalidConfigurationException(CFG_PROPERTY_MAX_CONNECTIONS_TOTAL + " must be > 0"); } } catch (InvalidConfigurationException e) { throw e; } catch (Exception e) { tracer.severe("failure in config validation", e); throw new InvalidConfigurationException(e.getMessage()); } try { String maxForRoutesString = (String) properties.getProperty(CFG_PROPERTY_MAX_CONNECTIONS_FOR_ROUTES) .getValue(); String[] maxForRoutesStrings = maxForRoutesString.split(","); for (String maxForRoute : maxForRoutesStrings) { if (maxForRoute.isEmpty()) { continue; } String[] maxForRouteParts = maxForRoute.split(":"); if (maxForRouteParts.length != MAX_CONNECTIONS_FOR_ROUTES_TOKEN_LENGTH) { throw new InvalidConfigurationException(CFG_PROPERTY_MAX_CONNECTIONS_FOR_ROUTES + " format is scheme:host:port:maxForRoute separated by comma"); } String scheme = maxForRouteParts[HTTP_SCHEME_INDEX]; if (scheme == null || scheme.equals("")) { scheme = HttpHost.DEFAULT_SCHEME_NAME; } String host = maxForRouteParts[HTTP_HOST_INDEX]; if (host == null || host.equals("")) { throw new InvalidConfigurationException(CFG_PROPERTY_MAX_CONNECTIONS_FOR_ROUTES + " format is scheme:host:port:maxForRoute separated by comma. Passing host is mandatory"); } String portStr = maxForRouteParts[HTTP_PORT_INDEX]; if (portStr == null || portStr.equals("")) { portStr = "80"; } int port = Integer.parseInt(portStr); String maxForRoutePartsStr = maxForRouteParts[HTTP_MAXFORROUTE_INDEX]; Integer max = Integer.valueOf(maxForRoutePartsStr); if (max < 1) { throw new InvalidConfigurationException(CFG_PROPERTY_MAX_CONNECTIONS_FOR_ROUTES + " format is scheme:host:port:maxForRoute separated by comma. Passing maxForRoute is mandatory and must be greater than 0"); } new HttpRoute(new HttpHost(host, port, scheme)); } } catch (InvalidConfigurationException e) { throw e; } catch (Exception e) { tracer.severe("failure in config validation", e); throw new InvalidConfigurationException(e.getMessage()); } } else { try { Class<? extends HttpClientFactory> c = (Class<? extends HttpClientFactory>) Class .forName(httpClientFactoryClassName); c.newInstance(); } catch (Exception e) { tracer.severe("failed to load http client factory class", e); throw new InvalidConfigurationException("failed to load http client factory class", e); } } }
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); }/* w ww.j av a2 s. c o m*/ 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:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java
/** * Configure the proxy with the required credential if needed * * @param httpClientBuilder/*from ww w. java2s.c om*/ * @param credentialsProvider * @param url * @return */ private HttpClientBuilder configureProxy(HttpClientBuilder httpClientBuilder, CredentialsProvider credentialsProvider, String url) throws DSSException { if (proxyPreferenceManager == null) { return httpClientBuilder; } try { final String protocol = new URL(url).getProtocol(); final boolean proxyHTTPS = Protocol.isHttps(protocol) && proxyPreferenceManager.isHttpsEnabled(); final boolean proxyHTTP = Protocol.isHttp(protocol) && proxyPreferenceManager.isHttpEnabled(); if (!proxyHTTPS && !proxyHTTP) { return httpClientBuilder; } String proxyHost = null; int proxyPort = 0; String proxyUser = null; String proxyPassword = null; String proxyExcludedHosts = null; if (proxyHTTPS) { LOG.debug("Use proxy https parameters"); final Long port = proxyPreferenceManager.getHttpsPort(); proxyPort = port != null ? port.intValue() : 0; proxyHost = proxyPreferenceManager.getHttpsHost(); proxyUser = proxyPreferenceManager.getHttpsUser(); proxyPassword = proxyPreferenceManager.getHttpsPassword(); proxyExcludedHosts = proxyPreferenceManager.getHttpsExcludedHosts(); } else if (proxyHTTP) { // noinspection ConstantConditions LOG.debug("Use proxy http parameters"); final Long port = proxyPreferenceManager.getHttpPort(); proxyPort = port != null ? port.intValue() : 0; proxyHost = proxyPreferenceManager.getHttpHost(); proxyUser = proxyPreferenceManager.getHttpUser(); proxyPassword = proxyPreferenceManager.getHttpPassword(); proxyExcludedHosts = proxyPreferenceManager.getHttpExcludedHosts(); } if (StringUtils.isNotEmpty(proxyUser) && StringUtils.isNotEmpty(proxyPassword)) { AuthScope proxyAuth = new AuthScope(proxyHost, proxyPort); UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); credentialsProvider.setCredentials(proxyAuth, proxyCredentials); } LOG.debug("proxy host/port: " + proxyHost + ":" + proxyPort); // TODO SSL peer shut down incorrectly when protocol is https final HttpHost proxy = new HttpHost(proxyHost, proxyPort, Protocol.HTTP.getName()); if (StringUtils.isNotEmpty(proxyExcludedHosts)) { final String[] hosts = proxyExcludedHosts.split("[,; ]"); HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) { @Override public HttpRoute determineRoute(final HttpHost host, final HttpRequest request, final HttpContext context) throws HttpException { String hostname = (host != null ? host.getHostName() : null); if ((hosts != null) && (hostname != null)) { for (String h : hosts) { if (hostname.equalsIgnoreCase(h)) { // bypass proxy for that hostname return new HttpRoute(host); } } } return super.determineRoute(host, request, context); } }; httpClientBuilder.setRoutePlanner(routePlanner); } final HttpClientBuilder httpClientBuilder1 = httpClientBuilder.setProxy(proxy); updated = false; return httpClientBuilder1; } catch (MalformedURLException e) { throw new DSSException(e); } }
From source file:org.mulgara.scon.Connection.java
/** * Set up some basic properties for a thread-safe client connection factory. * @return A new connection manager//from w w w . j a va 2 s .c om */ private ClientConnectionManager getConnectionManager() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 200); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); int port = endpoint.getPort(); if (port == -1) port = endpoint.getDefaultPort(); HttpHost host = new HttpHost(endpoint.getHost(), port); connPerRoute.setMaxForRoute(new HttpRoute(host), 50); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); return new ThreadSafeClientConnManager(params, schemeRegistry); }
From source file:com.networknt.client.Client.java
private CloseableHttpAsyncClient httpAsyncClient() throws ClientException { PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor(), asyncRegistry());//from w w w. java 2 s.c om Map<String, Object> asyncHttpClientMap = (Map<String, Object>) config.get(ASYNC); connectionManager.setMaxTotal((Integer) asyncHttpClientMap.get(MAX_CONNECTION_TOTAL)); connectionManager.setDefaultMaxPerRoute((Integer) asyncHttpClientMap.get(MAX_CONNECTION_PER_ROUTE)); // Now handle all the specific route defined. Map<String, Object> routeMap = (Map<String, Object>) asyncHttpClientMap.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); } final int timeout = (Integer) asyncHttpClientMap.get(TIMEOUT); RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build(); final long keepAliveMilliseconds = (Integer) asyncHttpClientMap.get(KEEP_ALIVE); return HttpAsyncClientBuilder.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(); }