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 File: HttpService.java    From oxAuth with 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 File: RestClient.java    From kylin-on-parquet-v2 with 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 File: HttpClientFactoryImpl.java    From swift-explorer with 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 #4
Source File: PlayManager.java    From raccoon4 with 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 #5
Source File: RestClient.java    From kylin with 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 File: HttpClientFactory.java    From fiware-cygnus with 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 #7
Source File: HttpConnectionPool.java    From Poseidon with 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 #8
Source File: InventoryIndexManagerImpl.java    From zstack with 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 #9
Source File: HBaseMapReduceIndexerTool.java    From hbase-indexer with 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 File: DockerClient.java    From docker-java with 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 File: BasicClient.java    From hbc with 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 File: HBaseIndexerMapper.java    From hbase-indexer with 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 #13
Source File: IndexerSupervisor.java    From hbase-indexer with 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 #14
Source File: HttpClientPoolFactory.java    From monasca-common with 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 #15
Source File: TalosClientFactory.java    From galaxy-sdk-java with 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 #16
Source File: RestartableHttpClient.java    From hbc with 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 #17
Source File: HttpUtil.java    From Leo with 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);
}
 
Example #18
Source File: LivyRestClient.java    From kylin-on-parquet-v2 with 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 #19
Source File: RestClient.java    From attic-stratos with 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 #20
Source File: SosAdapterFactory.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
private static HttpClient createHttpClient(SOSMetadata metadata) {
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
    cm.setMaxTotal(metadata.getHttpConnectionPoolSize());

    int timeout = metadata.getTimeout();
    SimpleHttpClient simpleClient = new SimpleHttpClient(timeout, timeout, cm);
    return new GzipEnabledHttpClient(new ProxyAwareHttpClient(simpleClient));
}
 
Example #21
Source File: ApacheHttpClient.java    From jus with 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 #22
Source File: GooglePlayAPI.java    From Raccoon with 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 File: Archive.java    From Raccoon with 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 #24
Source File: StreamClientImpl.java    From DroidDLNA with 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 #25
Source File: StreamClientImpl.java    From TVRemoteIME with 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 #26
Source File: GooglePlayAPI.java    From dummydroid with 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 #27
Source File: MwsConnection.java    From amazon-mws-orders with 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 #28
Source File: JenkinsHttpClient.java    From verigreen with 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 #29
Source File: LivyRestClient.java    From kylin with 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 #30
Source File: GooglePlayAPI.java    From raccoon4 with 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;
}