/** * 每次返回一个新的HttpClient实例 * @author nan.li * @return */ public static DefaultHttpClient 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); cm.setMaxTotal(500); cm.setDefaultMaxPerRoute(200); HttpParams params = new BasicHttpParams(); params.setParameter("http.connection.timeout", Integer.valueOf(CON_TIMEOUT)); params.setParameter("http.socket.timeout", Integer.valueOf(SO_TIMEOUT)); params.setParameter("http.useragent", UA_WINDOW7_CHROME); DefaultHttpClient client = new DefaultHttpClient(cm, params); return client; }
/** * Creates an HttpClient with a Pooling Client connection manager. * * @param maxConnections the max number of connections * @param connectionTimeoutInMs the connection timeout in ms. * @param socketTimeoutInMs the socket timeout in ms. * @return an HttpClient with a Pooling Client connection manager. */ public static HttpClient pooledConnectionHttpClient(int maxConnections, int connectionTimeoutInMs, int socketTimeoutInMs) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); cm.setDefaultMaxPerRoute(maxConnections); cm.setMaxTotal(maxConnections); HttpClient httpClient = new DefaultHttpClient(cm); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutInMs); HttpConnectionParams.setSoTimeout(params, socketTimeoutInMs); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Created Pooled HTTP Client. Max Connections per route=" + maxConnections + ", Max Connections=" + maxConnections + ", Connection Timeout in ms=" + connectionTimeoutInMs + ", Socket Timeout in ms=" + socketTimeoutInMs); } return httpClient; }
@Override public boolean start() { try { httpClient = new DefaultHttpClient(new PoolingClientConnectionManager()); bulkUri = makeURI(elasticSearchBaseUrl, "_bulk"); /* only for debugging */ if (deleteAllIndexWhenStart) { try { deleteIndex(null); } catch (Exception ex) { logger.warn(String.format("Failed to delete all index"), ex); } } populateExtensions(); populateTriggerVOs(); populateInventoryIndexer(); dumpInventoryIndexer(); createIndexIfNotExists(); bus.registerService(this); } catch (Exception e) { throw new CloudRuntimeException(e); } return true; }
/** * Constructor. * @param ssl True if SSL connections are desired. False otherwise. */ public HttpClientFactory(boolean ssl) { // create the logger logger = Logger.getLogger(HttpClientFactory.class); if (ssl) { sslConnectionsManager = new PoolingClientConnectionManager(getSchemeRegistry()); sslConnectionsManager.setMaxTotal(Constants.MAX_CONNS); sslConnectionsManager.setDefaultMaxPerRoute(Constants.MAX_CONNS_PER_ROUTE); } else { connectionsManager = new PoolingClientConnectionManager(); connectionsManager.setMaxTotal(Constants.MAX_CONNS); connectionsManager.setDefaultMaxPerRoute(Constants.MAX_CONNS_PER_ROUTE); } // if else logger.info("Setting max total connections (" + Constants.MAX_CONNS + ")"); logger.info("Setting default max connections per route (" + Constants.MAX_CONNS_PER_ROUTE + ")"); }
@Test public void testSetParams() { ModifiableSolrParams params = new ModifiableSolrParams(); params.set(HttpClientUtil.PROP_ALLOW_COMPRESSION, true); params.set(HttpClientUtil.PROP_BASIC_AUTH_PASS, "pass"); params.set(HttpClientUtil.PROP_BASIC_AUTH_USER, "user"); params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, 12345); params.set(HttpClientUtil.PROP_FOLLOW_REDIRECTS, true); params.set(HttpClientUtil.PROP_MAX_CONNECTIONS, 22345); params.set(HttpClientUtil.PROP_MAX_CONNECTIONS_PER_HOST, 32345); params.set(HttpClientUtil.PROP_SO_TIMEOUT, 42345); params.set(HttpClientUtil.PROP_USE_RETRY, false); DefaultHttpClient client = (DefaultHttpClient) HttpClientUtil.createClient(params); assertEquals(12345, HttpConnectionParams.getConnectionTimeout(client.getParams())); assertEquals(PoolingClientConnectionManager.class, client.getConnectionManager().getClass()); assertEquals(22345, ((PoolingClientConnectionManager)client.getConnectionManager()).getMaxTotal()); assertEquals(32345, ((PoolingClientConnectionManager)client.getConnectionManager()).getDefaultMaxPerRoute()); assertEquals(42345, HttpConnectionParams.getSoTimeout(client.getParams())); assertEquals(HttpClientUtil.NO_RETRY, client.getHttpRequestRetryHandler()); assertEquals("pass", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getPassword()); assertEquals("user", client.getCredentialsProvider().getCredentials(new AuthScope("127.0.0.1", 1234)).getUserPrincipal().getName()); assertEquals(true, client.getParams().getParameter(ClientPNames.HANDLE_REDIRECTS)); client.getConnectionManager().shutdown(); }
public UpdateShardHandler(ConfigSolr cfg) { clientConnectionManager = new PoolingClientConnectionManager(SchemeRegistryFactory.createSystemDefault()); if (cfg != null ) { clientConnectionManager.setMaxTotal(cfg.getMaxUpdateConnections()); clientConnectionManager.setDefaultMaxPerRoute(cfg.getMaxUpdateConnectionsPerHost()); } ModifiableSolrParams params = new ModifiableSolrParams(); if (cfg != null) { params.set(HttpClientUtil.PROP_SO_TIMEOUT, cfg.getDistributedSocketTimeout()); params.set(HttpClientUtil.PROP_CONNECTION_TIMEOUT, cfg.getDistributedConnectionTimeout()); } // in the update case, we want to do retries, and to use // the default Solr retry handler that createClient will // give us params.set(HttpClientUtil.PROP_USE_RETRY, true); log.info("Creating UpdateShardHandler HTTP client with params: {}", params); client = HttpClientUtil.createClient(params, clientConnectionManager); }
/** Method to execute a request */ public HttpResponse execute(HttpRequestBase request) throws Exception { if (processQueue.tryAcquire()) { HttpResponse response; try { // Inject timestamp in milliseconds just before sending request on wire. // This will help in measuring latencies between client and server. if (request.getHeaders(TIMESTAMP_HEADER).length == 0) { request.addHeader(TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis())); } response = client.execute(request); } catch (Exception e) { logger.error("Connections: {} AvailableRequests: {}", ((PoolingClientConnectionManager) this.client.getConnectionManager()).getTotalStats(), processQueue.availablePermits()); throw e; } finally { processQueue.release(); } return response; } else { throw new Exception("PROCESS_QUEUE_FULL POOL:"+name); } }
private void init(String host, int port, String userName, String password) { this.host = host; this.port = port; this.userName = userName; this.password = password; this.baseUrl = SCHEME_HTTP + host + ":" + port + KYLIN_API_PATH; final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs); HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs); final PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); KylinConfig config = KylinConfig.getInstanceFromEnv(); cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute()); cm.setMaxTotal(config.getRestClientMaxTotal()); client = new DefaultHttpClient(cm, httpParams); if (userName != null && password != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password); provider.setCredentials(AuthScope.ANY, credentials); client.setCredentialsProvider(provider); } }
/** * create a proxy client * * @return either a client or null if none is configured * @throws KeyManagementException * @throws NumberFormatException * if that port could not be parsed. * @throws NoSuchAlgorithmException */ private static HttpClient createProxyClient(PlayProfile profile) throws KeyManagementException, NoSuchAlgorithmException { if (profile.getProxyAddress() == null) { return null; } PoolingClientConnectionManager connManager = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); connManager.setMaxTotal(100); connManager.setDefaultMaxPerRoute(30); DefaultHttpClient client = new DefaultHttpClient(connManager); client.getConnectionManager().getSchemeRegistry() .register(Utils.getMockedScheme()); HttpHost proxy = new HttpHost(profile.getProxyAddress(), profile.getProxyPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (profile.getProxyUser() != null && profile.getProxyPassword() != null) { client.getCredentialsProvider().setCredentials( new AuthScope(proxy), new UsernamePasswordCredentials(profile.getProxyUser(), profile .getProxyPassword())); } return client; }
@Override public HttpClient getHttpClient(AccountConfig accountConfig, HasProxySettings proxySettings) { PoolingClientConnectionManager connectionManager = initConnectionManager(); if(accountConfig.isDisableSslValidation()) { disableSslValidation(connectionManager); } org.apache.http.client.HttpClient httpClient = newHttpClient (connectionManager) ; int socketTimeout = accountConfig.getSocketTimeout() ; if (socketTimeout != -1) { logger.info("Set socket timeout on HttpClient: " + socketTimeout); HttpParams params = httpClient.getParams(); HttpConnectionParams.setSoTimeout(params, socketTimeout); } // proxy setting if (proxySettings != null) setProxySettings (httpClient, proxySettings, "http") ; return httpClient ; }
@Inject public SparqlPersistance(@Named("r2r.fusekiUrl") String sparqlQuery, SparqlPostClient sparqlClient) throws Exception { this.sparqlQuery = new SparqlQueryClient(sparqlQuery + "/query"); this.sparqlClient = sparqlClient; // putting this here for now HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 40000); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); cm.setDefaultMaxPerRoute(20); cm.setMaxTotal(200); HttpOp.setDefaultHttpClient(new DefaultHttpClient(cm, params)); // make sure we have the latest model // for some reason we need to do post to capture the prefixes sparqlClient.post(R2ROntology.createR2ROntModel()); sparqlClient.update("CREATE GRAPH <" + R2R_DERIVED_GRAPH + ">"); // by loading these now, we make sure that we do not collide with calls to upsertAffiliation knownAffiliations = loadAffiliations(); }
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); } return httpClient; }
@Override public void afterPropertiesSet() throws Exception { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); taobaoHttpManager = new PoolingClientConnectionManager(schemeRegistry); taobaoHttpManager.setMaxTotal(taobaoMaxConnection); taobaoHttpManager.setDefaultMaxPerRoute(taobaoMaxConnection); // 每条通道最大并发连接数 log.info("Feedback http connection pool has start up..., max total is:" + taobaoMaxConnection); verifyReceiptDataHttpManager = new PoolingClientConnectionManager(schemeRegistry);; verifyReceiptDataHttpManager.setMaxTotal(verifyReceiptMaxConnection); verifyReceiptDataHttpManager.setDefaultMaxPerRoute(verifyReceiptMaxConnection); log.info("Feedback http connection pool has start up..., max total is:" + verifyReceiptDataHttpManager); commonHttpManager = new PoolingClientConnectionManager(schemeRegistry);; commonHttpManager.setMaxTotal(commonMaxConnection); commonHttpManager.setDefaultMaxPerRoute(commonMaxConnection); log.info("Feedback http connection pool has start up..., max total is:" + commonHttpManager); }
public HttpClient getHttpsClientTrustAll() { try { SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){ @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); PlainSocketFactory psf = PlainSocketFactory.getSocketFactory(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, psf)); registry.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); return new DefaultHttpClient(ccm); } catch (Exception ex) { log.error("Failed to create TrustAll https client", ex); return new DefaultHttpClient(); } }
@Deprecated public HttpClient getHttpsClientDefaulTrustStore() { try { PlainSocketFactory psf = PlainSocketFactory.getSocketFactory(); SSLContext ctx = SSLContext.getInstance("TLS"); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, psf)); registry.register(new Scheme("https", 443, ssf)); ClientConnectionManager ccm = new PoolingClientConnectionManager(registry); return new DefaultHttpClient(ccm); } catch (Exception ex) { log.error("Failed to create https client", ex); return new DefaultHttpClient(); } }
/** * Constructor. * @param ssl True if SSL connections are desired. False otherwise. * @param loginConfFile * @param krb5ConfFile * @param maxConns * @param maxConnsPerRoute */ public HttpClientFactory(boolean ssl, String loginConfFile, String krb5ConfFile, int maxConns, int maxConnsPerRoute) { // set the Kerberos parameters this.loginConfFile = loginConfFile; this.krb5ConfFile = krb5ConfFile; // create the appropriate connections manager if (ssl) { sslConnectionsManager = new PoolingClientConnectionManager(getSSLSchemeRegistry()); sslConnectionsManager.setMaxTotal(maxConns); sslConnectionsManager.setDefaultMaxPerRoute(maxConnsPerRoute); } else { connectionsManager = new PoolingClientConnectionManager(); connectionsManager.setMaxTotal(maxConns); connectionsManager.setDefaultMaxPerRoute(maxConnsPerRoute); } // if else LOGGER.info("Setting max total connections (" + maxConns + ")"); LOGGER.info("Setting default max connections per route (" + maxConnsPerRoute + ")"); }
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); }
private ClientConfig createClientConfig(final DNSAPIClientConfig config, final JacksonJsonProvider jacksonJsonProvider, final HttpParams httpParams, final PoolingClientConnectionManager clientConnectionManager) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(jacksonJsonProvider); clientConfig.property( ClientProperties.BUFFER_RESPONSE_ENTITY_ON_EXCEPTION, true); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, config.getTimeout()); clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, false); clientConfig.property(ClientProperties.JSON_PROCESSING_FEATURE_DISABLE, false); clientConfig.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true); clientConfig.property(ClientProperties.MOXY_JSON_FEATURE_DISABLE, true); clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, clientConnectionManager); clientConfig.property(ApacheClientProperties.DISABLE_COOKIES, true); clientConfig.property(ApacheClientProperties.HTTP_PARAMS, httpParams); clientConfig.property( ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, false); return clientConfig; }
public DefaultHttpClientImpl() { cm = new PoolingClientConnectionManager(); cm.setMaxTotal(100); cm.setDefaultMaxPerRoute(100); client = new SystemDefaultHttpClient() { @Override protected ClientConnectionManager createClientConnectionManager() { return cm; } }; client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); client.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, true); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000); }
public DefaultWmsHttpClientFactory() { final PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); cm.setMaxTotal(100); cm.setDefaultMaxPerRoute(100); client = new SystemDefaultHttpClient() { @Override protected ClientConnectionManager createClientConnectionManager() { return cm; } }; client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); client.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, true); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000); }
public static ClientConnectionManager getClientConnectionManager() { // TrustStrategy acceptingTrustStrategy = new TrustStrategy() { // @Override // public boolean isTrusted(X509Certificate[] certificate, String authType) { // return true; // } // }; // SSLSocketFactory sf = null; // try { // sf = new SSLSocketFactory(acceptingTrustStrategy, // SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { // throw new RuntimeException(e); // } // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("https", 8443, sf)); // return new PoolingClientConnectionManager(registry); return new PoolingClientConnectionManager(); }
/** * Creates an authenticated JIRA client with custom HttpClient. * * @param httpClient Custom HttpClient to be used * @param uri Base URI of the JIRA server * @param creds Credentials to authenticate with * @throws JiraException */ public JiraClient(HttpClient httpClient, String uri, ICredentials creds) throws JiraException { if (httpClient == null) { PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(); connManager.setDefaultMaxPerRoute(20); connManager.setMaxTotal(40); httpClient = new DefaultHttpClient(connManager); } restclient = new RestClient(httpClient, creds, URI.create(uri)); if (creds != null) { username = creds.getLogonName(); //intialize connection if required creds.initialize(restclient); } }
private String getUpdateJson() { try { // battle-royale.jutge.org has an untrusted cert final TrustStrategy easyStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] certificate, final String authType) throws CertificateException { return true; } }; final SSLSocketFactory socketFactory = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, socketFactory)); final ClientConnectionManager connectionManager = new PoolingClientConnectionManager(registry); // Get data final HttpClient httpClient = new DefaultHttpClient(connectionManager); final HttpGet get = new HttpGet(UPDATE_URL); final HttpResponse response = httpClient.execute(get); final HttpEntity entity = response.getEntity(); final String responseBody = EntityUtils.toString(entity); return responseBody; } catch(Exception exception) { this.logger.error(exception.getMessage()); } return null; }
public JenkinsHttpClient(String username, String authToken) { DocumentBuilder builder; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ProcessingException(e); } handler = new XMLResponseHandler(builder); PoolingClientConnectionManager manager = new PoolingClientConnectionManager(); manager.setDefaultMaxPerRoute(20); httpClient = new DefaultHttpClient(manager); if (username != null) { Credentials credentials = new UsernamePasswordCredentials(username, authToken); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.addRequestInterceptor(preemptiveAuth, 0); } }
private Set<SolrClient> createSolrClients(Map<String, String> indexConnectionParams) throws MalformedURLException { String solrMode = getSolrMode(indexConnectionParams); if (solrMode.equals("cloud")) { String indexZkHost = indexConnectionParams.get(SolrConnectionParams.ZOOKEEPER); String collectionName = indexConnectionParams.get(SolrConnectionParams.COLLECTION); CloudSolrClient solrServer = new CloudSolrClient.Builder().withZkHost(indexZkHost).build(); int zkSessionTimeout = HBaseIndexerConfiguration.getSessionTimeout(getConf()); solrServer.setZkClientTimeout(zkSessionTimeout); solrServer.setZkConnectTimeout(zkSessionTimeout); solrServer.setDefaultCollection(collectionName); return Collections.singleton((SolrClient)solrServer); } else if (solrMode.equals("classic")) { PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(getSolrMaxConnectionsPerRoute(indexConnectionParams)); connectionManager.setMaxTotal(getSolrMaxConnectionsTotal(indexConnectionParams)); HttpClient httpClient = new DefaultHttpClient(connectionManager); return new HashSet<SolrClient>(createHttpSolrClients(indexConnectionParams, httpClient)); } else { throw new RuntimeException("Only 'cloud' and 'classic' are valid values for solr.mode, but got " + solrMode); } }
public BasicClient(String name, Hosts hosts, StreamingEndpoint endpoint, Authentication auth, boolean enableGZip, HosebirdMessageProcessor processor, ReconnectionManager reconnectionManager, RateTracker rateTracker, ExecutorService executorService, @Nullable BlockingQueue<Event> eventsQueue, HttpParams params, SchemeRegistry schemeRegistry) { Preconditions.checkNotNull(auth); HttpClient client; if (enableGZip) { client = new RestartableHttpClient(auth, enableGZip, params, schemeRegistry); } else { DefaultHttpClient defaultClient = new DefaultHttpClient(new PoolingClientConnectionManager(schemeRegistry), params); /** Set auth **/ auth.setupConnection(defaultClient); client = defaultClient; } this.canRun = new AtomicBoolean(true); this.executorService = executorService; this.clientBase = new ClientBase(name, client, hosts, endpoint, auth, processor, reconnectionManager, rateTracker, eventsQueue); }
/** * The timeout should be adjusted by network condition. * @return */ private static HttpClient createClient() { SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schReg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schReg); ccm.setMaxTotal(Config.maxUpload); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10 * 1000); HttpConnectionParams.setSoTimeout(params, Config.timeOut); return new DefaultHttpClient(ccm, params); }
public ClientConnectionManager configureConnectionManager( HttpParams params) throws ArangoDb4JException { if (conman == null) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(configureScheme()); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(maxConnections); cm.setDefaultMaxPerRoute(maxConnections); conman = cm; } if (cleanupIdleConnections) { IdleConnectionMonitor.monitor(conman); } return conman; }
@Override public void prepare(Benchmark benchmark) { super.prepare(benchmark); ClientConnectionManager connectionManager = new PoolingClientConnectionManager(); if (benchmark.tls) { SslClient sslClient = SslClient.localhost(); connectionManager.getSchemeRegistry().register( new Scheme("https", 443, new SSLSocketFactory(sslClient.sslContext))); } client = new DefaultHttpClient(connectionManager); }
@Override protected ClientConnectionManager createClientConnectionManager() { PoolingClientConnectionManager connmgr = new PoolingClientConnectionManager( SchemeRegistryFactory.createSystemDefault()); String s = System.getProperty("http.keepAlive"); if ("true".equalsIgnoreCase(s)) { s = System.getProperty("http.maxConnections", "5"); int max = Integer.parseInt(s); connmgr.setDefaultMaxPerRoute(max); connmgr.setMaxTotal(2 * max); } return connmgr; }
@Override public void prepare(Benchmark benchmark) { super.prepare(benchmark); ClientConnectionManager connectionManager = new PoolingClientConnectionManager(); if (benchmark.tls) { SSLContext sslContext = SslContextBuilder.localhost(); connectionManager.getSchemeRegistry().register( new Scheme("https", 443, new SSLSocketFactory(sslContext))); } client = new DefaultHttpClient(connectionManager); }
/** * Creates a BeyondJ manager wrapper for the specified URL, username, password and URL encoding. * * @param url the full URL of the BeyondJ manager instance to use * @param username the username to use when authenticating with BeyondJ manager * @param password the password to use when authenticating with BeyondJ manager * @param charset the URL encoding charset to use when communicating with BeyondJ manager * @param verbose if the build is in verbose mode (quiet mode otherwise) * @since 2.2 */ public DeploymentManager(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); } }
public static PoolingClientConnectionManager createPoolingClientConnManager( ClientConfiguration config, HttpParams httpClientParams ) { PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setDefaultMaxPerRoute(config.getMaxConnections()); connectionManager.setMaxTotal(config.getMaxConnections()); if (config.useReaper()) { IdleConnectionReaper.registerConnectionManager(connectionManager); } return connectionManager; }
/** * Get a connection manager to use for this connection. * <p> * Called late in initialization. * <p> * Default implementation uses a shared PoolingClientConnectionManager. * * @return The connection manager to use. */ private ClientConnectionManager getConnectionManager() { synchronized (this.getClass()) { if (sharedCM == null) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); cm.setMaxTotal(maxConnections); cm.setDefaultMaxPerRoute(maxConnections); sharedCM = cm; } return sharedCM; } }
/** * CONSTRUCTOR * @param logger * @param address * @throws MalformedURLException */ public MieleGatewayDispatcher( String gatewayHostAndPort, String username, String password, OSHGlobalLogger logger) { super(); this.homebusUrl = "http://" + gatewayHostAndPort + "/homebus/?language=en"; this.httpCredsProvider = new BasicCredentialsProvider(); this.httpCredsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); this.httpcontext = new BasicHttpContext(); this.httpcontext.setAttribute(ClientContext.CREDS_PROVIDER, httpCredsProvider); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); this.httpclient = new DefaultHttpClient(cm); this.httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Default to HTTP 1.1 (connection persistence) this.httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); this.httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); this.httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); this.logger = logger; //this.parser = new MieleGatewayParser("http://" + device + "/homebus"); this.deviceData = new HashMap<Integer, MieleDeviceHomeBusData>(); new Thread(this, "MieleGatewayDispatcher for " + gatewayHostAndPort).start(); }
/** * CONSTRUCTOR * @param logger * @param address * @throws MalformedURLException */ public MieleGatewayRESTDispatcher( String gatewayHostAndPort, String username, String password, IGlobalLogger logger) { super(); this.homebusUrl = "http://" + gatewayHostAndPort + "/homebus/?language=en"; this.httpCredsProvider = new BasicCredentialsProvider(); this.httpCredsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); this.httpcontext = new BasicHttpContext(); this.httpcontext.setAttribute(ClientContext.CREDS_PROVIDER, httpCredsProvider); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); this.httpclient = new DefaultHttpClient(cm); this.httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // Default to HTTP 1.1 (connection persistence) this.httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); this.httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); this.httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); this.logger = logger; //this.parser = new MieleGatewayParser("http://" + device + "/homebus"); this.deviceData = new HashMap<Integer, MieleDeviceHomeBusDataREST>(); new Thread(this, "MieleGatewayDispatcher for " + gatewayHostAndPort).start(); }