List of usage examples for org.apache.http.impl.conn PoolingClientConnectionManager setMaxTotal
public void setMaxTotal(final int max)
From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java
/** * Configure HttpClient with set of defaults as well as configuration * from MarketplaceWebServiceConfig instance * *//*from w ww . jav a2 s. c o 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()) { 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.apache.tomcat.maven.common.deployer.TomcatManager.java
/** * Creates a Tomcat manager wrapper for the specified URL, username, password and URL encoding. * * @param url the full URL of the Tomcat manager instance to use * @param username the username to use when authenticating with Tomcat manager * @param password the password to use when authenticating with Tomcat manager * @param charset the URL encoding charset to use when communicating with Tomcat manager * @param verbose if the build is in verbose mode (quiet mode otherwise) * @since 2.2//from ww w .ja v a 2s . co m */ public TomcatManager(URL url, String username, String password, String charset, boolean verbose) { this.url = url; this.username = username; this.password = password; this.charset = charset; this.verbose = verbose; PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager(); poolingClientConnectionManager.setMaxTotal(5); this.httpClient = new DefaultHttpClient(poolingClientConnectionManager); if (StringUtils.isNotEmpty(username)) { Credentials creds = new UsernamePasswordCredentials(username, password); String host = url.getHost(); int port = url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT; httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), creds); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); authCache.put(targetHost, basicAuth); localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); } }
From source file:org.craftercms.profile.impl.ProfileRestClientService.java
private DefaultHttpClient getHttpClient(int connectionTimeOut, int sockeTimeOut) { try {/*ww w. j ava 2s . co 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); 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); }/*w w w. ja v a 2 s. c o m*/ 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); }/* w w w. ja v a 2s . c o m*/ } } 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 * // www .j a v a 2s.c o 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 ww w . j av a 2s. c o 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); // Increase default max connection per route to 20 cm.setDefaultMaxPerRoute(20);//w w w . ja va 2 s. co m // 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; }