Search in sources :

Example 31 with ClientConnectionManager

use of org.apache.http.conn.ClientConnectionManager in project custom-cert-https by nelenkov.

the class MainActivity method createHttpClient.

private HttpClient createHttpClient(SocketFactory socketFactory) {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
    ConnPerRoute connPerRoute = new ConnPerRouteBean(MAX_CONN_PER_ROUTE);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTIONS);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    if (socketFactory != null) {
        sslSocketFactory = socketFactory;
    }
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(cm, params);
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) SocketFactory(org.apache.http.conn.scheme.SocketFactory) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) ConnPerRoute(org.apache.http.conn.params.ConnPerRoute) BasicHttpParams(org.apache.http.params.BasicHttpParams) ConnPerRouteBean(org.apache.http.conn.params.ConnPerRouteBean) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 32 with ClientConnectionManager

use of org.apache.http.conn.ClientConnectionManager in project gfm_viewer by satyagraha.

the class TestWebServiceClientDefault method shouldHandleSimpleRequest.

@Test
public void shouldHandleSimpleRequest() throws Exception {
    ServletHolder sh = new ServletHolder(ServletContainer.class);
    sh.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS, StubResourceConfig.class.getName());
    sh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
    Server server = new Server(0);
    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    context.addServlet(sh, "/*");
    server.start();
    Connector[] connectors = server.getConnectors();
    int port = ((NetworkConnector) connectors[0]).getLocalPort();
    LOGGER.info("server port: " + port);
    Config config = mock(Config.class);
    String apiUrl = "http://localhost:" + port;
    given(config.getApiUrl()).willReturn(apiUrl);
    WebProxyConfig webProxyConfig = mock(WebProxyConfig.class);
    SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class);
    ClientConnectionManager connectionManager = new ClientConnManagerDefault(sslSocketFactory);
    WebServiceClient webServiceClient = new WebServiceClientDefault(config, webProxyConfig, connectionManager);
    Random random = new Random();
    // construct the tasks to run
    int threadCount = 50;
    List<WebServiceClientCallable> tasks = new ArrayList<WebServiceClientCallable>();
    for (int threadIndex = 0; threadIndex < threadCount; threadIndex++) {
        String mdText = RandomStringUtils.randomAlphanumeric(random.nextInt(100));
        WebServiceClientCallable task = new WebServiceClientCallable(webServiceClient, mdText);
        tasks.add(task);
    }
    // run the tasks
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    List<Future<String>> futures = executorService.invokeAll(tasks, 10, TimeUnit.SECONDS);
    // verify results
    assertThat(futures, hasSize(threadCount));
    for (int threadIndex = 0; threadIndex < threadCount; threadIndex++) {
        String result = futures.get(threadIndex).get();
        WebServiceClientCallable task = tasks.get(threadIndex);
        assertThat(result, is(performSampleTransformation(task.mdText)));
    }
    server.stop();
}
Also used : NetworkConnector(org.eclipse.jetty.server.NetworkConnector) Connector(org.eclipse.jetty.server.Connector) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) WebProxyConfig(code.satyagraha.gfm.support.api.WebProxyConfig) DefaultResourceConfig(com.sun.jersey.api.core.DefaultResourceConfig) Config(code.satyagraha.gfm.support.api.Config) ArrayList(java.util.ArrayList) WebServiceClient(code.satyagraha.gfm.support.api.WebServiceClient) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) ClientConnManagerDefault(code.satyagraha.gfm.support.impl.conn.ClientConnManagerDefault) WebProxyConfig(code.satyagraha.gfm.support.api.WebProxyConfig) Random(java.util.Random) ExecutorService(java.util.concurrent.ExecutorService) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) Future(java.util.concurrent.Future) WebServiceClientDefault(code.satyagraha.gfm.support.impl.WebServiceClientDefault) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) Test(org.junit.Test)

Example 33 with ClientConnectionManager

use of org.apache.http.conn.ClientConnectionManager in project SmartAndroidSource by jaychou2012.

the class MySSLSocketFactory method getNewHttpClient.

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
 *
 * @param keyStore custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 34 with ClientConnectionManager

use of org.apache.http.conn.ClientConnectionManager in project ribbon by Netflix.

the class RestClient method apacheHttpClientSpecificInitialization.

protected Client apacheHttpClientSpecificInitialization() {
    httpClient4 = NFHttpClientFactory.getNamedNFHttpClient(restClientName, this.ncc, true);
    if (httpClient4 instanceof AbstractHttpClient) {
        // DONT use our NFHttpClient's default Retry Handler since we have
        // retry handling (same server/next server) in RestClient itself
        ((AbstractHttpClient) httpClient4).setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(restClientName, 0, false, 0));
    } else {
        logger.warn("Unexpected error: Unable to disable NFHttpClient " + "retry handler, this most likely will not cause an " + "issue but probably should be looked at");
    }
    HttpParams httpClientParams = httpClient4.getParams();
    // initialize Connection Manager cleanup facility
    NFHttpClient nfHttpClient = (NFHttpClient) httpClient4;
    // should we enable connection cleanup for idle connections?
    try {
        enableConnectionPoolCleanerTask = ncc.getOrDefault(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled);
        nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
    }
    if (enableConnectionPoolCleanerTask) {
        try {
            connectionCleanerRepeatInterval = ncc.getOrDefault(CommonClientConfigKey.ConnectionCleanerRepeatInterval);
            nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
        }
        try {
            connIdleEvictTimeMilliSeconds = ncc.getDynamicProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds);
            nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
        } catch (Exception e1) {
            throwInvalidValue(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
        }
        nfHttpClient.initConnectionCleanerTask();
    }
    try {
        maxConnectionsperHost = ncc.getOrDefault(CommonClientConfigKey.MaxHttpConnectionsPerHost);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setDefaultMaxPerRoute(maxConnectionsperHost);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
    }
    try {
        maxTotalConnections = ncc.getOrDefault(CommonClientConfigKey.MaxTotalHttpConnections);
        ClientConnectionManager connMgr = httpClient4.getConnectionManager();
        if (connMgr instanceof ThreadSafeClientConnManager) {
            ((ThreadSafeClientConnManager) connMgr).setMaxTotal(maxTotalConnections);
        }
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.MaxTotalHttpConnections, e1);
    }
    try {
        connectionTimeout = ncc.getOrDefault(CommonClientConfigKey.ConnectTimeout);
        HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ConnectTimeout, e1);
    }
    try {
        readTimeout = ncc.getOrDefault(CommonClientConfigKey.ReadTimeout);
        HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
    } catch (Exception e1) {
        throwInvalidValue(CommonClientConfigKey.ReadTimeout, e1);
    }
    // httpclient 4 seems to only have one buffer size controlling both
    // send/receive - so let's take the bigger of the two values and use
    // it as buffer size
    int bufferSize = Integer.MIN_VALUE;
    if (ncc.get(CommonClientConfigKey.ReceiveBufferSize) != null) {
        try {
            bufferSize = ncc.getOrDefault(CommonClientConfigKey.ReceiveBufferSize);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ReceiveBufferSize, e);
        }
        if (ncc.get(CommonClientConfigKey.SendBufferSize) != null) {
            try {
                int sendBufferSize = ncc.getOrDefault(CommonClientConfigKey.SendBufferSize);
                if (sendBufferSize > bufferSize) {
                    bufferSize = sendBufferSize;
                }
            } catch (Exception e) {
                throwInvalidValue(CommonClientConfigKey.SendBufferSize, e);
            }
        }
    }
    if (bufferSize != Integer.MIN_VALUE) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams, bufferSize);
    }
    if (ncc.get(CommonClientConfigKey.StaleCheckingEnabled) != null) {
        try {
            HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.StaleCheckingEnabled));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.StaleCheckingEnabled, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.Linger) != null) {
        try {
            HttpConnectionParams.setLinger(httpClientParams, ncc.getOrDefault(CommonClientConfigKey.Linger));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.Linger, e);
        }
    }
    if (ncc.get(CommonClientConfigKey.ProxyHost) != null) {
        try {
            proxyHost = (String) ncc.getOrDefault(CommonClientConfigKey.ProxyHost);
            proxyPort = ncc.getOrDefault(CommonClientConfigKey.ProxyPort);
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpClient4.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.ProxyHost, e);
        }
    }
    if (isSecure) {
        final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
        final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
        final ClientConnectionManager currentManager = httpClient4.getConnectionManager();
        AbstractSslContextFactory abstractFactory = null;
        if (// if client is not is not required, we only need a keystore OR a truststore to warrant configuring
        (isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null)) || (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))) {
            try {
                abstractFactory = new URLSslContextFactory(trustStoreUrl, ncc.get(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, ncc.get(CommonClientConfigKey.KeyStorePassword));
            } catch (ClientSslSocketFactoryException e) {
                throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
            }
        }
        KeyStoreAwareSocketFactory awareSocketFactory;
        try {
            awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractFactory) : new KeyStoreAwareSocketFactory(abstractFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            currentManager.getSchemeRegistry().register(new Scheme("https", 443, awareSocketFactory));
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
        }
    }
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html
    if (ignoreUserToken) {
        ((DefaultHttpClient) httpClient4).setUserTokenHandler(new UserTokenHandler() {

            @Override
            public Object getUserToken(HttpContext context) {
                return null;
            }
        });
    }
    // custom SSL Factory handler
    String customSSLFactoryClassName = ncc.get(CommonClientConfigKey.CustomSSLSocketFactoryClassName);
    if (customSSLFactoryClassName != null) {
        try {
            SSLSocketFactory customSocketFactory = (SSLSocketFactory) ClientFactory.instantiateInstanceWithClientConfig(customSSLFactoryClassName, ncc);
            httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, customSocketFactory));
        } catch (Exception e) {
            throwInvalidValue(CommonClientConfigKey.CustomSSLSocketFactoryClassName, e);
        }
    }
    ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpClient4, new BasicCookieStore(), false);
    return new ApacheHttpClient4(handler, config);
}
Also used : ApacheHttpClient4Handler(com.sun.jersey.client.apache4.ApacheHttpClient4Handler) Scheme(org.apache.http.conn.scheme.Scheme) AbstractSslContextFactory(com.netflix.client.ssl.AbstractSslContextFactory) NFHttpClient(com.netflix.http4.NFHttpClient) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) KeyStoreAwareSocketFactory(com.netflix.http4.ssl.KeyStoreAwareSocketFactory) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) ApacheHttpClient4(com.sun.jersey.client.apache4.ApacheHttpClient4) UserTokenHandler(org.apache.http.client.UserTokenHandler) NFHttpMethodRetryHandler(com.netflix.http4.NFHttpMethodRetryHandler) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) HttpContext(org.apache.http.protocol.HttpContext) URLSslContextFactory(com.netflix.client.ssl.URLSslContextFactory) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) URISyntaxException(java.net.URISyntaxException) ClientException(com.netflix.client.ClientException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) ClientSslSocketFactoryException(com.netflix.client.ssl.ClientSslSocketFactoryException) AbstractHttpClient(org.apache.http.impl.client.AbstractHttpClient) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)

Example 35 with ClientConnectionManager

use of org.apache.http.conn.ClientConnectionManager in project platform_external_apache-http by android.

the class SingleClientConnManager method releaseConnection.

// non-javadoc, see interface ClientConnectionManager
public void releaseConnection(ManagedClientConnection conn, long validDuration, TimeUnit timeUnit) {
    assertStillUp();
    if (!(conn instanceof ConnAdapter)) {
        throw new IllegalArgumentException("Connection class mismatch, " + "connection not obtained from this manager.");
    }
    if (log.isDebugEnabled()) {
        log.debug("Releasing connection " + conn);
    }
    ConnAdapter sca = (ConnAdapter) conn;
    if (sca.poolEntry == null)
        // already released
        return;
    ClientConnectionManager manager = sca.getManager();
    if (manager != null && manager != this) {
        throw new IllegalArgumentException("Connection not obtained from this manager.");
    }
    try {
        // BEGIN android-changed
        // When recycling a Socket, we un-tag it to avoid collecting
        // statistics from future users.
        final Socket socket = uniquePoolEntry.connection.getSocket();
        if (socket != null) {
            TrafficStats.untagSocket(socket);
        }
        // make sure that the response has been read completely
        if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable())) {
            if (log.isDebugEnabled()) {
                log.debug("Released connection open but not reusable.");
            }
            // make sure this connection will not be re-used
            // we might have gotten here because of a shutdown trigger
            // shutdown of the adapter also clears the tracked route
            sca.shutdown();
        }
    } catch (IOException iox) {
        // @@@ log as warning? let pass?
        if (log.isDebugEnabled())
            log.debug("Exception shutting down released connection.", iox);
    } finally {
        sca.detach();
        managedConn = null;
        lastReleaseTime = System.currentTimeMillis();
        if (validDuration > 0)
            connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
        else
            connectionExpiresTime = Long.MAX_VALUE;
    }
}
Also used : IOException(java.io.IOException) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) Socket(java.net.Socket)

Aggregations

ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)74 Scheme (org.apache.http.conn.scheme.Scheme)51 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)48 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)39 HttpParams (org.apache.http.params.HttpParams)37 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)35 BasicHttpParams (org.apache.http.params.BasicHttpParams)28 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)26 IOException (java.io.IOException)21 Test (org.junit.Test)15 CertificateException (java.security.cert.CertificateException)14 HttpClient (org.apache.http.client.HttpClient)14 KeyManagementException (java.security.KeyManagementException)13 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 SSLContext (javax.net.ssl.SSLContext)12 HttpResponse (org.apache.http.HttpResponse)11 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)11 KeyStoreException (java.security.KeyStoreException)10 PoolingClientConnectionManager (org.apache.http.impl.conn.PoolingClientConnectionManager)10 UnrecoverableKeyException (java.security.UnrecoverableKeyException)9