List of usage examples for org.apache.http.impl.conn PoolingClientConnectionManager setDefaultMaxPerRoute
public void setDefaultMaxPerRoute(final int max)
From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java
/** * Configure HttpClient with set of defaults as well as configuration * from MarketplaceWebServiceConfig instance * *//* w w w.j ava 2 s.co m*/ private HttpClient configureHttpClient(String applicationName, String applicationVersion) { // respect a user-provided User-Agent header as-is, but if none is provided // then generate one satisfying the MWS User-Agent requirements if (config.getUserAgent() == null) { config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion), quoteAttributeValue("Java/" + System.getProperty("java.version") + "/" + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")), quoteAttributeName("Platform"), quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch") + "/" + System.getProperty("os.version")), quoteAttributeName("MWSClientVersion"), quoteAttributeValue(mwsClientLibraryVersion)); } defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent())); /* Set http client parameters */ BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent()); /* Set connection parameters */ HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpParams, config.getSoTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpParams, true); HttpConnectionParams.setTcpNoDelay(httpParams, true); /* Set connection manager */ PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setMaxTotal(config.getMaxAsyncQueueSize()); connectionManager.setDefaultMaxPerRoute(config.getMaxAsyncQueueSize()); /* Set http client */ httpClient = new DefaultHttpClient(connectionManager, httpParams); httpContext = new BasicHttpContext(); /* Set proxy if configured */ if (config.isSetProxyHost() && config.isSetProxyPort()) { log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + "Proxy Port: " + config.getProxyPort()); final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(), (usesHttps(config.getServiceURL()) ? "https" : "http")); httpContext = new BasicHttpContext(); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration); if (config.isSetProxyUsername() && config.isSetProxyPassword()) { credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); } } return httpClient; }
From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java
/** * Configure HttpClient with set of defaults as well as configuration * from MarketplaceWebServiceConfig instance * *//*from www .jav a 2 s . c om*/ private HttpClient configureHttpClient(String applicationName, String applicationVersion) { // respect a user-provided User-Agent header as-is, but if none is provided // then generate one satisfying the MWS User-Agent requirements if (config.getUserAgent() == null) { config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion), quoteAttributeValue("Java/" + System.getProperty("java.version") + "/" + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")), quoteAttributeName("Platform"), quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch") + "/" + System.getProperty("os.version")), quoteAttributeName("MWSClientVersion"), quoteAttributeValue(mwsClientLibraryVersion)); } defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent())); /* Set http client parameters */ BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent()); /* Set connection parameters */ HttpConnectionParams.setConnectionTimeout(httpParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpParams, config.getSoTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpParams, true); HttpConnectionParams.setTcpNoDelay(httpParams, true); /* Set connection manager */ PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setMaxTotal(config.getMaxAsyncQueueSize()); connectionManager.setDefaultMaxPerRoute(config.getMaxAsyncQueueSize()); /* Set http client */ httpClient = new DefaultHttpClient(connectionManager, httpParams); httpContext = new BasicHttpContext(); /* Set proxy if configured */ if (config.isSetProxyHost() && config.isSetProxyPort()) { String proxyProtocol = null; if (config.isSetProxyProtocol()) { //User explicitly set how to talk to proxy proxyProtocol = config.getProxyProtocol().toString().toLowerCase(); } else { // assume that the mws endpoint url determines the protocol // for the proxy as well proxyProtocol = usesHttps(config.getServiceURL()) ? "https" : "http"; } log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + " Proxy Port: " + config.getProxyPort() + " Proxy protocol: " + proxyProtocol); final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(), proxyProtocol); httpContext = new BasicHttpContext(); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration); if (config.isSetProxyUsername() && config.isSetProxyPassword()) { credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); } } return httpClient; }
From source file:org.craftercms.profile.impl.ProfileRestClientService.java
private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) { try {/* ww w . ja v a 2 s .c o m*/ HttpParams httpParams = new BasicHttpParams(); setParams(httpParams, connectionTimeOut, sockeTimeOut); SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", sslPort, sf)); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(registry); HttpHost localhost = new HttpHost(host, port); ccm.setMaxPerRoute(new HttpRoute(localhost), maxPerRoute); ccm.setMaxTotal(maxTotal); ccm.setDefaultMaxPerRoute(defaultMaxPerRoute); return new DefaultHttpClient(ccm, httpParams); } catch (Exception e) { log.error(e.getMessage(), e); return new DefaultHttpClient(); } }
From source file:org.fcrepo.client.utils.HttpHelper.java
private static HttpClient buildClient(final String fedoraUsername, final String fedoraPassword, final String repositoryURL) { final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager(); connMann.setMaxTotal(MAX_VALUE);/*from w w w . j a va 2 s . c o m*/ connMann.setDefaultMaxPerRoute(MAX_VALUE); final DefaultHttpClient httpClient = new DefaultHttpClient(connMann); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false)); // If the Fedora instance requires authentication, set it up here if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) { LOGGER.debug("Adding BASIC credentials to client for repo requests."); final URI fedoraUri = URI.create(repositoryURL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()), new UsernamePasswordCredentials(fedoraUsername, fedoraPassword)); httpClient.setCredentialsProvider(credsProvider); } return httpClient; }
From source file:org.fcrepo.indexer.IndexerGroup.java
@VisibleForTesting protected DefaultHttpClient httpClient(final String repositoryURL) { // try to find existing client if (clients.size() > 0) { for (final Iterator<String> it = clients.keySet().iterator(); it.hasNext();) { final String base = it.next(); if (repositoryURL.startsWith(base)) { return clients.get(base); }/*from w ww .ja va2s.c om*/ } } if (defaultClient != null) { return defaultClient; } // if no existing client matched, create a new one final String baseURL; if (repositoryURL.indexOf(REST_PREFIX) > 0) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf(REST_PREFIX) + REST_PREFIX.length()); } else if (repositoryURL.indexOf("/", FCREPO_PREFIX.length()) > 0) { baseURL = repositoryURL.substring(0, repositoryURL.indexOf("/", FCREPO_PREFIX.length()) + 1); } else { baseURL = repositoryURL; } final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager(); connMann.setMaxTotal(MAX_VALUE); connMann.setDefaultMaxPerRoute(MAX_VALUE); final DefaultHttpClient httpClient = new DefaultHttpClient(connMann); httpClient.setRedirectStrategy(new DefaultRedirectStrategy()); httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false)); // If the Fedora instance requires authentication, set it up here if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) { LOGGER.debug("Adding BASIC credentials to client for repo requests."); final URI fedoraUri = URI.create(baseURL); final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()), new UsernamePasswordCredentials(fedoraUsername, fedoraPassword)); httpClient.setCredentialsProvider(credsProvider); } clients.put(baseURL, httpClient); return httpClient; }
From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java
/** * Constructor for Authentication Token mechanism * //w w w.j a va 2s . co m * @param apiUrl * url for API * @param authenticationToken * authentication token value * @param maxTotalConnection * max total connections for client * @param defaultMaxConnectionPerRoute * default max connection per route for client */ public DefaultFreshBooksClient(String apiUrl, String authenticationToken, int maxTotalConnection, int defaultMaxConnectionPerRoute) { Validate.notEmpty(apiUrl); Validate.notEmpty(authenticationToken); try { this.apiUrl = new URL(apiUrl); } catch (MalformedURLException e) { throw new FreshBooksException(e.getMessage()); } 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); // max total connections cm.setMaxTotal(maxTotalConnection); // default max connection per route cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute); client = new DefaultHttpClient(cm); this.client.getCredentialsProvider().setCredentials( new AuthScope(this.apiUrl.getHost(), 443, AuthScope.ANY_REALM), new UsernamePasswordCredentials(authenticationToken, "")); client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 3) { logger.warn("Maximum tries reached for client http pool "); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { logger.warn("No response from server on " + executionCount + " call"); return true; } return false; } }); }
From source file:org.mule.modules.freshbooks.api.DefaultFreshBooksClient.java
/** * Constructor for OAuth1.0a mechanism/*from w w w . ja v a2s .co m*/ * * @param apiUrl * url for API * @param consumerKey * consumerKey value * @param consumerSecret * consumerSecret value * @param maxTotalConnection * max total connections for client * @param defaultMaxConnectionPerRoute * default max connection per route for client */ public DefaultFreshBooksClient(String apiUrl, String consumerKey, String consumerSecret, int maxTotalConnection, int defaultMaxConnectionPerRoute) { Validate.notEmpty(apiUrl); try { this.apiUrl = new URL(apiUrl); } catch (MalformedURLException e) { throw new FreshBooksException(e.getMessage()); } this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; 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); // max total connections cm.setMaxTotal(maxTotalConnection); // default max connection per route cm.setDefaultMaxPerRoute(defaultMaxConnectionPerRoute); client = new DefaultHttpClient(cm); client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 3) { logger.warn("Maximum tries reached for client http pool "); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { logger.warn("No response from server on " + executionCount + " call"); return true; } return false; } }); }
From source file:org.rhq.modules.plugins.wildfly10.ASConnection.java
public ASConnection(ASConnectionParams params) { asConnectionParams = params;/* w w w. ja v a 2 s . c om*/ // Check and store the basic parameters if (asConnectionParams.getHost() == null) { throw new IllegalArgumentException("Management host cannot be null."); } if (asConnectionParams.getPort() <= 0 || asConnectionParams.getPort() > 65535) { throw new IllegalArgumentException("Invalid port: " + asConnectionParams.getPort()); } UsernamePasswordCredentials credentials = null; if (asConnectionParams.getUsername() != null && asConnectionParams.getPassword() != null) { credentials = new UsernamePasswordCredentials(asConnectionParams.getUsername(), asConnectionParams.getPassword()); } keepAliveTimeout = asConnectionParams.getKeepAliveTimeout(); managementUri = buildManagementUri(); // Each ASConnection instance will have its own HttpClient instance. Setup begins here SchemeRegistry schemeRegistry = new SchemeRegistryBuilder(asConnectionParams).buildSchemeRegistry(); // HttpClient will use a pooling connection manager to allow concurrent request processing PoolingClientConnectionManager httpConnectionManager = new PoolingClientConnectionManager(schemeRegistry); httpConnectionManager.setDefaultMaxPerRoute(MAX_POOLED_CONNECTIONS); httpConnectionManager.setMaxTotal(MAX_POOLED_CONNECTIONS); httpClient = new DefaultHttpClient(httpConnectionManager); HttpParams httpParams = httpClient.getParams(); // Disable stale connection checking on connection lease to get better performance // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); httpClient.setReuseStrategy(new CustomConnectionReuseStrategy(this)); if (keepAliveTimeout > 0) { httpClient.setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy(this)); // Initial schedule of a cleaning task. Subsequent executions will be scheduled as needed. // See ConnectionManagerCleaner implementation. cleanerExecutor.schedule(new ConnectionManagerCleaner(this), keepAliveTimeout / 2, TimeUnit.MILLISECONDS); } HttpClientParams.setRedirecting(httpParams, false); if (credentials != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(asConnectionParams.getHost(), asConnectionParams.getPort()), credentials); } mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); shutdown = false; }
From source file:rapture.common.client.BaseHttpApi.java
private static HttpClient getHttpClient() { 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);/*from w w w . j av a 2 s . c om*/ // 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(cm); // Use a proxy if it is defined - we need to pass this on to the // HttpClient if (System.getProperties().containsKey("http.proxyHost")) { String host = System.getProperty("http.proxyHost"); String port = System.getProperty("http.proxyPort", "8080"); HttpHost proxy = new HttpHost(host, Integer.parseInt(port)); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext arg1) 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 { if (log.isTraceEnabled()) { log.trace("Response Headers:"); for (Header h : response.getAllHeaders()) { log.trace(h.getName() + " : " + h.getValue()); } } 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; }