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.xdi.oxauth.service.net.HttpService.java

public HttpClient getHttpsClientTrustAll() {
    try {//ww w .ja v  a  2  s.  c  o  m
        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();
    }
}

From source file:spring.test.web.HttpComponentsHttpInvokerRequestExecutor.java

/**
* Create a new instance of the HttpComponentsHttpInvokerRequestExecutor with a default
* {@link HttpClient} that uses a default {@link org.apache.http.impl.conn.PoolingClientConnectionManager}.
*///from ww  w  . ja v a 2s  .  com
public HttpComponentsHttpInvokerRequestExecutor() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
    this.httpClient = new DefaultHttpClient(connectionManager);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}

From source file:com.jrodeo.queue.messageset.provider.TestHttpClient5.java

public TestHttpClient5() {
    super();//w w  w  .ja va  2  s . c  om
    HttpParams params = new SyncBasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 15000);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    this.mgr = new PoolingClientConnectionManager(schemeRegistry);
    this.httpclient = new DefaultHttpClient(this.mgr, params);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        public boolean retryRequest(final IOException exception, int executionCount,
                final HttpContext context) {
            return false;
        }

    });
}

From source file:se.inera.certificate.proxy.filter.ProxyFilter.java

private void doInit() {
    if (!isInitiated) {
        connectionManager = new PoolingClientConnectionManager(SchemeRegistryFactory.createDefault());
        connectionManager.setMaxTotal(maxConnections);
        connectionManager.setDefaultMaxPerRoute(maxDefaultPerRoute);

        // TODO: Hardcoded for now... (PW)
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_MS);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_SO_TIMEOUT_MS);
        params.setParameter(CoreConnectionPNames.SO_LINGER, DEFAULT_SO_LINGER_S);

        httpClient = new HttpProxyClient(connectionManager, params);

        isInitiated = true;/*from w w w . ja v  a 2  s . c  o  m*/
    }
}

From source file:com.jrodeo.queue.messageset.provider.TestHttpClient4.java

public TestHttpClient4() {
    super();/*from  ww  w .j  a va  2s  . c o  m*/
    HttpParams params = new SyncBasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024);
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 15000);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    this.mgr = new PoolingClientConnectionManager(schemeRegistry);
    this.httpclient = new DefaultHttpClient(this.mgr, params);
    this.httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {

        public boolean retryRequest(final IOException exception, int executionCount,
                final HttpContext context) {
            return false;
        }

    });
}

From source file:uk.ac.ebi.intact.task.mitab.index.OntologyEnricherItemProcessor.java

private HttpClient createHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);

    HttpClient httpClient = new DefaultHttpClient(cm);

    return httpClient;
}

From source file:simple.crawler.http.HttpClientFactory.java

public static DefaultHttpClient createNewDefaultHttpClient() {
    ////from   ww  w  . j  ava 2 s .  com
    HttpParams params = new BasicHttpParams();

    //Determines the connection timeout
    HttpConnectionParams.setConnectionTimeout(params, 1 * 60 * 1000);

    //Determines the socket timeout
    HttpConnectionParams.setSoTimeout(params, 1 * 60 * 1000);

    //Determines whether stale connection check is to be used
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    //The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. 
    //When application wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY)
    //Data will be sent earlier, at the cost of an increase in bandwidth consumption
    HttpConnectionParams.setTcpNoDelay(params, true);

    //
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params,
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");

    //Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    PoolingClientConnectionManager pm = new PoolingClientConnectionManager(schemeRegistry);

    //
    DefaultHttpClient httpclient = new DefaultHttpClient(pm, params);
    //ConnManagerParams.setMaxTotalConnections(params, MAX_HTTP_CONNECTION);
    //ConnManagerParams.setMaxConnectionsPerRoute(params, defaultConnPerRoute);
    //ConnManagerParams.setTimeout(params, 1 * 60 * 1000);
    httpclient.getParams().setParameter("http.conn-manager.max-total", MAX_HTTP_CONNECTION);
    ConnPerRoute defaultConnPerRoute = new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 4;
        }
    };
    httpclient.getParams().setParameter("http.conn-manager.max-per-route", defaultConnPerRoute);
    httpclient.getParams().setParameter("http.conn-manager.timeout", 1 * 60 * 1000L);
    httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    //
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 2) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    httpclient.setHttpRequestRetryHandler(retryHandler);

    HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    };

    HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header header = entity.getContentEncoding();
            if (header != null) {
                HeaderElement[] codecs = header.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    String codecName = codecs[i].getName();
                    if ("gzip".equalsIgnoreCase(codecName)) {
                        response.setEntity(new GzipDecompressingEntity(entity));
                        return;
                    } else if ("deflate".equalsIgnoreCase(codecName)) {
                        response.setEntity(new DeflateDecompressingEntity(entity));
                        return;
                    }
                }
            }
        }
    };

    httpclient.addRequestInterceptor(requestInterceptor);
    httpclient.addResponseInterceptor(responseInterceptor);
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy());

    return httpclient;
}

From source file:org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor.java

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

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

    this.httpClient = new DefaultHttpClient(connectionManager);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}

From source file:bear.plugins.java.JenkinsCache.java

public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {//  w  w  w . j a v a 2s  .  c o m
        Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion);

        if (!optional.isPresent()) {
            throw new RuntimeException("could not find: " + jdkVersion);
        }

        String uri = optional.get().filepath;

        //                agent.get()

        //                agent.get()

        SSLContext sslContext = SSLContext.getInstance("TLSv1");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);

        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);

        DefaultHttpClient httpClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry));

        MechanizeAgent agent = new MechanizeAgent();
        Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com");
        cookie2.getHttpCookie().setPath("/");
        cookie2.getHttpCookie().setSecure(false);

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("gpw_e24", ".");
        cookie.setDomain("oracle.com");
        cookie.setPath("/");
        cookie.setSecure(true);

        cookieStore.addCookie(cookie);

        httpClient.setCookieStore(cookieStore);

        HttpPost httppost = new HttpPost("https://login.oracle.com");

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        HttpResponse response = httpClient.execute(httppost);

        int code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("unable to auth: " + code);
        }

        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

        response = httpClient.execute(httppost);

        code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("to download: " + uri);
        }

        File file = new File(tempDestDir, optional.get().name);
        HttpEntity entity = response.getEntity();

        final long length = entity.getContentLength();

        final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file));

        System.out.printf("Downloading %s to %s...%n", uri, file);

        Thread progressThread = new Thread(new Runnable() {
            double lastProgress;

            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    long copied = os.getCount();

                    double progress = copied * 100D / length;

                    if (progress != lastProgress) {
                        System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1));
                    }

                    lastProgress = progress;

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "progressThread");

        progressThread.start();

        ByteStreams.copy(entity.getContent(), os);

        progressThread.interrupt();

        System.out.println("Download complete.");

        return file;
    } catch (Exception e) {
        throw Exceptions.runtime(e);
    }
}

From source file:com.impetus.kundera.ycsb.utils.CouchDBOperationUtils.java

public HttpClient initiateClient(String host, int port) {
    if (httpClient == null || httpHost == null) {
        SchemeSocketFactory ssf = null;//from ww  w  .j  ava2 s.  co  m
        ssf = PlainSocketFactory.getSocketFactory();
        SchemeRegistry schemeRegistry = new SchemeRegistry();

        schemeRegistry.register(new Scheme("http", port, ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);

        ccm.setMaxTotal(100);
        //            ccm.setDefaultMaxPerRoute(50);

        httpClient = new DefaultHttpClient(ccm);
        httpHost = new HttpHost(host, port);

        try {
            // Http params
            httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

            // request interceptor
            ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor() {
                public void process(final HttpRequest request, final HttpContext context) throws IOException {

                }
            });
            // response interceptor
            ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor() {
                public void process(final HttpResponse response, final HttpContext context) throws IOException {

                }
            });
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return httpClient;
}