org.apache.http.impl.conn.PoolingClientConnectionManager Java Examples

The following examples show how to use org.apache.http.impl.conn.PoolingClientConnectionManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: oxAuth   Author: GluuFederation   File: HttpService.java    License: MIT License 7 votes vote down vote up
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();
    }
}
 
Example #2
Source Project: kylin-on-parquet-v2   Author: Kyligence   File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #3
Source Project: zstack   Author: zstackio   File: InventoryIndexManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source Project: Poseidon   Author: flipkart-incubator   File: HttpConnectionPool.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
    }
}
 
Example #5
Source Project: kylin   Author: apache   File: RestClient.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #6
Source Project: raccoon4   Author: onyxbits   File: PlayManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source Project: swift-explorer   Author: roikku   File: HttpClientFactoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 ;
}
 
Example #8
Source Project: fiware-cygnus   Author: telefonicaid   File: HttpClientFactory.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 + ")");
}
 
Example #9
Source Project: hbase-indexer   Author: NGDATA   File: HBaseMapReduceIndexerTool.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }

}
 
Example #10
Source Project: docker-java   Author: kpelykh   File: DockerClient.java    License: Apache License 2.0 6 votes vote down vote up
private DockerClient(Config config) {
	restEndpointUrl = config.url + "/v" + config.version;
	ClientConfig clientConfig = new DefaultClientConfig();
	//clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

	SchemeRegistry schemeRegistry = new SchemeRegistry();
	schemeRegistry.register(new Scheme("http", config.url.getPort(), PlainSocketFactory.getSocketFactory()));
	schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

	PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
	// Increase max total connection
	cm.setMaxTotal(1000);
	// Increase default max connection per route
	cm.setDefaultMaxPerRoute(1000);

	HttpClient httpClient = new DefaultHttpClient(cm);
	client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig);

	client.setReadTimeout(10000);
	//Experimental support for unix sockets:
	//client = new UnixSocketClient(clientConfig);

	client.addFilter(new JsonClientFilter());
	client.addFilter(new LoggingFilter());
}
 
Example #11
Source Project: hbc   Author: twitter   File: BasicClient.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #12
Source Project: kylin-on-parquet-v2   Author: Kyligence   File: LivyRestClient.java    License: Apache License 2.0 5 votes vote down vote up
private void init() {
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
    HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
    cm.setMaxTotal(config.getRestClientMaxTotal());

    baseUrl = config.getLivyUrl();
    client = new DefaultHttpClient(cm, httpParams);
}
 
Example #13
Source Project: TVRemoteIME   Author: kingthy   File: StreamClientImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    HttpProtocolParams.setUseExpectContinue(globalParams, false);

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);

    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
    if (getConfiguration().getSocketBufferSize() != -1)
        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());

    // Only register 80, not 443 and SSL
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    clientConnectionManager = new PoolingClientConnectionManager(registry);
    clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
    clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());

    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
            new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)
        );
    }
}
 
Example #14
Source Project: dummydroid   Author: onyxbits   File: GooglePlayAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Connection manager to allow concurrent connections.
 *
 * @return {@link ClientConnectionManager} instance
 */
public static ClientConnectionManager getConnectionManager() {
	PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
			SchemeRegistryFactory.createDefault());
	connManager.setMaxTotal(100);
	connManager.setDefaultMaxPerRoute(30);
	return connManager;
}
 
Example #15
Source Project: DroidDLNA   Author: offbye   File: StreamClientImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    HttpProtocolParams.setUseExpectContinue(globalParams, false);

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);

    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
    if (getConfiguration().getSocketBufferSize() != -1)
        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());

    // Only register 80, not 443 and SSL
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    clientConnectionManager = new PoolingClientConnectionManager(registry);
    clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
    clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());

    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
            new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)
        );
    }
}
 
Example #16
Source Project: verigreen   Author: Verigreen   File: JenkinsHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create an unauthenticated Jenkins HTTP client
 * 
 * @param uri
 *            Location of the jenkins server (ex. http://localhost:8080)
 */
public JenkinsHttpClient(URI uri) {
    this.context = uri.getPath();
    if (!context.endsWith("/")) {
        context += "/";
    }
    this.uri = uri;
    this.mapper = getDefaultMapper();
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    this.client = new DefaultHttpClient(new PoolingClientConnectionManager(), httpParameters);
}
 
Example #17
Source Project: kylin   Author: apache   File: LivyRestClient.java    License: Apache License 2.0 5 votes vote down vote up
private void init() {
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, httpSocketTimeoutMs);
    HttpConnectionParams.setConnectionTimeout(httpParams, httpConnectionTimeoutMs);

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setDefaultMaxPerRoute(config.getRestClientDefaultMaxPerRoute());
    cm.setMaxTotal(config.getRestClientMaxTotal());

    baseUrl = config.getLivyUrl();
    client = new DefaultHttpClient(cm, httpParams);
}
 
Example #18
Source Project: raccoon4   Author: onyxbits   File: GooglePlayAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Connection manager to allow concurrent connections.
 * 
 * @return {@link ClientConnectionManager} instance
 */
public static ClientConnectionManager getConnectionManager() {
	PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
			SchemeRegistryFactory.createDefault());
	connManager.setMaxTotal(100);
	connManager.setDefaultMaxPerRoute(30);
	return connManager;
}
 
Example #19
Source Project: swift-explorer   Author: roikku   File: HttpClientFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
protected void disableSslValidation(PoolingClientConnectionManager connectionManager) {
    try {
        connectionManager.getSchemeRegistry().register(
                new Scheme("https", 443,
                        new SSLSocketFactory(createGullibleSslContext(),
                                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (GeneralSecurityException e) {
        throw new RuntimeException("Could not initialize SSL Context: " + e, e);
    }
}
 
Example #20
Source Project: amazon-mws-orders   Author: integration-technology   File: MwsConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #21
Source Project: Raccoon   Author: onyxbits   File: Archive.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a proxy client, if it is configured.
 * 
 * @return either a client or null
 * @throws IOException
 *           if reading the config file fails
 * @throws KeyManagementException
 * @throws NumberFormatException
 *           if that port could not be parsed.
 * @throws NoSuchAlgorithmException
 */
public HttpClient getProxyClient() throws IOException, KeyManagementException,
		NoSuchAlgorithmException, NumberFormatException {
	File cfgfile = new File(root, NETCFG);
	if (cfgfile.exists()) {
		Properties cfg = new Properties();
		cfg.load(new FileInputStream(cfgfile));
		String ph = cfg.getProperty(PROXYHOST, null);
		String pp = cfg.getProperty(PROXYPORT, null);
		String pu = cfg.getProperty(PROXYUSER, null);
		String pw = cfg.getProperty(PROXYPASS, null);
		if (ph == null || pp == 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(ph, Integer.parseInt(pp));
		client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		if (pu != null && pw != null) {
			client.getCredentialsProvider().setCredentials(new AuthScope(proxy),
					new UsernamePasswordCredentials(pu, pw));
		}
		return client;
	}
	return null;
}
 
Example #22
Source Project: Raccoon   Author: onyxbits   File: GooglePlayAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Connection manager to allow concurrent connections.
 * 
 * @return {@link ClientConnectionManager} instance
 */
public static ClientConnectionManager getConnectionManager() {
	PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
			SchemeRegistryFactory.createDefault());
	connManager.setMaxTotal(100);
	connManager.setDefaultMaxPerRoute(30);
	return connManager;
}
 
Example #23
Source Project: jus   Author: apptik   File: ApacheHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void prepare(States.GenericState state) {
  super.prepare(state);
  ClientConnectionManager connectionManager = new PoolingClientConnectionManager();
  if (state.tls) {
    SslClient sslClient = SslClient.localhost();
    connectionManager.getSchemeRegistry().register(
        new Scheme("https", 443, new SSLSocketFactory(sslClient.sslContext)));
  }
  client = new DefaultHttpClient(connectionManager);
}
 
Example #24
Source Project: attic-stratos   Author: apache   File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
public RestClient() {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    // Increase max total connection to 200
    cm.setMaxTotal(200);
    // Increase default max connection per route to 50
    cm.setDefaultMaxPerRoute(50);

    httpClient = new DefaultHttpClient(cm);
}
 
Example #25
Source Project: galaxy-sdk-java   Author: XiaoMi   File: TalosClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpClient generateHttpClient(final int maxTotalConnections,
    final int maxTotalConnectionsPerRoute, int connTimeout) {
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
  schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

  PoolingClientConnectionManager conMgr = new PoolingClientConnectionManager(schemeRegistry);
  conMgr.setMaxTotal(maxTotalConnections);
  conMgr.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute);

  HttpParams httpParams = new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParams, connTimeout);
  return new DefaultHttpClient(conMgr, httpParams);
}
 
Example #26
Source Project: monasca-common   Author: openstack   File: HttpClientPoolFactory.java    License: Apache License 2.0 5 votes vote down vote up
HttpClientPoolFactory(String host, int port, boolean useHttps, int timeout,
  boolean clientAuth, String keyStore, String keyPass,
  String trustStore, String trustPass, String adminToken,
  int maxActive, long timeBetweenEvictionRunsMillis,
  long minEvictableIdleTimeMillis) {
  // Setup auth URL
  String protocol = useHttps ? "https://" : "http://";
  String urlStr = protocol + host + ":" + port;
  uri = URI.create(urlStr);

  // Setup connection pool
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  if (protocol.startsWith("https")) {
    SSLSocketFactory sslf = sslFactory(keyStore, keyPass, trustStore,
      trustPass, clientAuth);
    schemeRegistry.register(new Scheme("https", port, sslf));
  } else {
    schemeRegistry.register(new Scheme("http", port, PlainSocketFactory
      .getSocketFactory()));
  }
  connMgr = new PoolingClientConnectionManager(schemeRegistry,
    minEvictableIdleTimeMillis, TimeUnit.MILLISECONDS);

  connMgr.setMaxTotal(maxActive);
  connMgr.setDefaultMaxPerRoute(maxActive);

  // Http connection timeout
  HttpParams params = new BasicHttpParams();
  params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
  params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

  // Create a single client
  client = new DefaultHttpClient(connMgr, params);

  // Create and start the connection pool cleaner
  cleaner = new HttpPoolCleaner(connMgr, timeBetweenEvictionRunsMillis,
    minEvictableIdleTimeMillis);
  new Thread(cleaner).start();

}
 
Example #27
Source Project: hbase-indexer   Author: NGDATA   File: IndexerSupervisor.java    License: Apache License 2.0 5 votes vote down vote up
public IndexerHandle(IndexerDefinition indexerDef, Indexer indexer, SepConsumer sepEventSlave,
                     SolrClient solrServer, PoolingClientConnectionManager connectionManager) {
    this.indexerDef = indexerDef;
    this.indexer = indexer;
    this.sepConsumer = sepEventSlave;
    this.solrServer = solrServer;
    this.connectionManager = connectionManager;
}
 
Example #28
Source Project: hbase-indexer   Author: NGDATA   File: HBaseIndexerMapper.java    License: Apache License 2.0 5 votes vote down vote up
private DirectSolrClassicInputDocumentWriter createClassicSolrWriter(Context context,
                                                                     Map<String, String> indexConnectionParams)
        throws IOException {
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(getSolrMaxConnectionsPerRoute(indexConnectionParams));
    connectionManager.setMaxTotal(getSolrMaxConnectionsTotal(indexConnectionParams));

    HttpClient httpClient = new DefaultHttpClient(connectionManager);
    List<SolrClient> solrServers = createHttpSolrClients(indexConnectionParams, httpClient);

    return new DirectSolrClassicInputDocumentWriter(
            context.getConfiguration().get(INDEX_NAME_CONF_KEY), solrServers);
}
 
Example #29
Source Project: hbc   Author: twitter   File: RestartableHttpClient.java    License: Apache License 2.0 5 votes vote down vote up
public void setup() {
  DefaultHttpClient defaultClient = new DefaultHttpClient(new PoolingClientConnectionManager(schemeRegistry), params);

  auth.setupConnection(defaultClient);

  if (enableGZip) {
    underlying.set(new DecompressingHttpClient(defaultClient));
  } else {
    underlying.set(defaultClient);
  }
}
 
Example #30
Source Project: Leo   Author: QihooTest   File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 默认构造函数
 */
public HttpUtil() {
	this.charset = "UTF-8"; 
	PoolingClientConnectionManager pccm = new PoolingClientConnectionManager();
       pccm.setMaxTotal(100); //设置整个连接池最大链接数
	httpClient = new DefaultHttpClient(pccm);
	httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
	httpClient.getConnectionManager().closeIdleConnections(30,TimeUnit.SECONDS);
}