Example usage for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

List of usage examples for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager.

Prototype

public PoolingClientConnectionManager(final SchemeRegistry schreg) 

Source Link

Usage

From source file:org.nuxeo.scim.server.tests.ScimServerTest.java

protected static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);//from w w  w. j  av a 2s  .  c  o  m
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftAuthClient.java

public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot)
        throws AuthenticationException {

    try {//from w w w . j a v a  2  s. c om
        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        //skip host name verification
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        //REGISTERS SCHEMES FOR BOTH HTTP AND HTTPS
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", sf, Integer.parseInt(remoteServerPort)));

        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        HttpClient httpClient = new DefaultHttpClient(manager);

        //If the webContextRoot is null or /
        if (webContextRoot == null || "/".equals(webContextRoot)) {
            //Assign it an empty value since it is part of the thriftServiceURL.
            webContextRoot = "";
        }
        String thriftServiceURL = "https://" + serverIP + ':' + remoteServerPort + webContextRoot + '/'
                + "thriftAuthenticator";
        client = new THttpClient(thriftServiceURL, httpClient);

    } catch (TTransportException e) {
        throw new AuthenticationException("Error in creating thrift authentication client..", e);
    } catch (Exception e) {
        throw new AuthenticationException("Error in creating thrift authentication client..", e);
    }
}

From source file:org.greencheek.spring.rest.SSLCachingHttpComponentsClientHttpRequestFactory.java

/**
 * Create a new instance of the HttpComponentsClientHttpRequestFactory with a default
 * {@link HttpClient} that uses a default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}.
 *//*from   w  ww. j ava2s  . c o  m*/
public SSLCachingHttpComponentsClientHttpRequestFactory(boolean useSSLCaching) {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSystemSocketFactory()));

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    this.httpClient = new DefaultHttpClient(connectionManager);
    ((DefaultHttpClient) this.httpClient).removeRequestInterceptorByClass(RequestDefaultHeaders.class);

    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
    setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLISECONDS);
    this.useSSLCaching = useSSLCaching;
    setTcpNoDelay(DEFAULT_TCP_NO_DELAY);
}

From source file:pt.lsts.neptus.util.http.client.HttpClientConnectionHelper.java

/**
 * Call this to initialize the comms.//w  w  w .ja  v a2s  .c o m
 */
public void initializeComm() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, PlainSocketFactory.getSocketFactory()));
    httpConnectionManager = new PoolingClientConnectionManager(schemeRegistry);
    httpConnectionManager.setMaxTotal(maxTotalConnections);
    httpConnectionManager.setDefaultMaxPerRoute(defaultMaxConnectionsPerRoute);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    client = new DefaultHttpClient(httpConnectionManager, params);

    if (initializeProxyRoutePlanner)
        ProxyInfoProvider.setRoutePlanner(client);
}

From source file:org.xdi.oxauth.service.net.HttpService.java

@Deprecated
public HttpClient getHttpsClientDefaulTrustStore() {
    try {/*w  ww  . ja va 2  s.c  om*/
        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();
    }
}

From source file:com.liferay.ide.core.remote.RemoteConnection.java

private HttpClient getHttpClient() {
    if (this.httpClient == null) {
        DefaultHttpClient newDefaultHttpClient = null;

        if (getUsername() != null || getPassword() != null) {
            try {
                final IProxyService proxyService = LiferayCore.getProxyService();

                URI uri = new URI("http://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                IProxyData[] proxyDataForHost = proxyService.select(uri);

                for (IProxyData data : proxyDataForHost) {
                    if (data.getHost() != null && data.getPort() > 0) {
                        SchemeRegistry schemeRegistry = new SchemeRegistry();
                        schemeRegistry.register(
                                new Scheme("http", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
                        cm.setMaxTotal(200);
                        cm.setDefaultMaxPerRoute(20);

                        DefaultHttpClient newHttpClient = new DefaultHttpClient(cm);
                        HttpHost proxy = new HttpHost(data.getHost(), data.getPort());

                        newHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        newDefaultHttpClient = newHttpClient;
                        break;
                    }/*ww w  .j a  v a  2s  .c om*/
                }

                if (newDefaultHttpClient == null) {
                    uri = new URI("SOCKS://" + getHost() + ":" + getHttpPort()); //$NON-NLS-1$ //$NON-NLS-2$
                    proxyDataForHost = proxyService.select(uri);

                    for (IProxyData data : proxyDataForHost) {
                        if (data.getHost() != null) {
                            DefaultHttpClient newHttpClient = new DefaultHttpClient();
                            newHttpClient.getParams().setParameter("socks.host", data.getHost()); //$NON-NLS-1$
                            newHttpClient.getParams().setParameter("socks.port", data.getPort()); //$NON-NLS-1$
                            newHttpClient.getConnectionManager().getSchemeRegistry().register(
                                    new Scheme("socks", data.getPort(), PlainSocketFactory.getSocketFactory())); //$NON-NLS-1$

                            newDefaultHttpClient = newHttpClient;
                            break;
                        }
                    }
                }
            } catch (URISyntaxException e) {
                LiferayCore.logError("Unable to read proxy data", e); //$NON-NLS-1$
            }

            if (newDefaultHttpClient == null) {
                newDefaultHttpClient = new DefaultHttpClient();
            }

            this.httpClient = newDefaultHttpClient;
        } else {
            this.httpClient = new DefaultHttpClient();
        }
    }

    return this.httpClient;
}

From source file:org.aicer.hibiscus.http.workers.HttpWorkerAbstract.java

/**
 * Transmits the HTTP request from the client to the server
 *
 * @throws HibiscusException/*w w w  .  j ava  2s . com*/
 */
public void execute() throws HibiscusException {

    prepare();

    httpRequest.addHeader("User-Agent", getClass().getName().toUpperCase());
    httpRequest.addHeader("X-Conversation-Id",
            HashGenerator.getMD5Hash(System.currentTimeMillis() + "." + new Thread().getId()));

    // Creates a registry for HTTP and HTTPS setting default ports to 80 and 443 respectively for these schemes
    // HTTP uses org.apache.http.conn.scheme.PlainSocketFactory
    // HTTPS uses org.apache.http.conn.ssl.SSLSocketFactory
    SchemeRegistry registry = SchemeRegistryFactory.createDefault();
    ;

    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(registry);

    // This is necessary because of https://issues.apache.org/jira/browse/HTTPCLIENT-1193
    // We cannot use the Default constructor without overriding the connection manager from the default
    DefaultHttpClient requestClient = new DefaultHttpClient(connManager);

    try {

        final long startTime = System.currentTimeMillis();
        final HttpResponse response = requestClient.execute(httpRequest);
        final long elapsedTime = System.currentTimeMillis() - startTime;
        final HttpEntity responseEntity = response.getEntity();

        /* Capture the elapsed time for this request */
        this.responseTime = elapsedTime;

        /* This will reset the response object each time the request is made */
        this.response = new Response();

        /* Sets the status line and response headers */
        this.response.setStatusLine(response.getStatusLine().toString());
        this.response.setResponseHeaders(response.getAllHeaders());

        if (null != responseEntity) {
            this.response.setResponseBody(StreamUtil.inputStreamToString(responseEntity.getContent()));
        }

        if (log.isDebugEnabled()) {
            debugRequest(response);
        }

    } catch (IOException e) {
        throw new HibiscusException(e);
    }
}

From source file:osh.busdriver.mielegateway.MieleGatewayDispatcher.java

/**
 * CONSTRUCTOR/*www  . j  ava2  s .  co  m*/
 * @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();
}

From source file:nextflow.fs.dx.api.DxHttpClient.java

/**
 * Creates the http client using a thread safe {@code PoolingClientConnectionManager}
 *
 * See http://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/connmgmt.html#d5e581
 *
 * @authors Paolo Di Tommaso <paolo.ditommaso@gmail.com>
 *
 * @return/*w w  w . j  a  va  2 s . c om*/
 */
protected DxHttpClient() {
    log.debug("Creating DxHttpClient object");
    try {
        DxEnv env = DxEnv.getInstance();
        securityContext = env.getSecurityContext();
        apiserver = env.getApiserverPath();

        final String PROT = env.getApiserverProtocol();
        final String HOST = env.getApiserverHost();
        final int PORT = env.getApiserverPort();

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        SchemeSocketFactory factory = "https".equals(PROT) ? SSLSocketFactory.getSocketFactory()
                : PlainSocketFactory.getSocketFactory();
        schemeRegistry.register(new Scheme(PROT, PORT, factory));

        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(schemeRegistry);
        manager.setMaxTotal(100);
        manager.setDefaultMaxPerRoute(10);

        manager.setMaxPerRoute(new HttpRoute(new HttpHost(HOST, PORT)), 50);

        httpclient = new DefaultHttpClient(manager);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

}

From source file:com.autonomousturk.crawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }//  w  w w  . j  a  v  a2  s  . c om

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}