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:com.impetus.client.couchdb.CouchDBSchemaManager.java

/**
 * Instantiate http client.// w w  w.j ava 2 s.  c  om
 * 
 * @return true, if successful
 */
@Override
protected boolean initiateClient() {
    try {
        SchemeSocketFactory ssf = null;
        ssf = PlainSocketFactory.getSocketFactory();
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", Integer.parseInt(port), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpClient = new DefaultHttpClient(ccm);
        httpHost = new HttpHost(hosts[0], Integer.parseInt(port), "http");
        // Http params
        httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

        // basic authentication
        if (userName != null && password != null) {
            ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(hosts[0], Integer.parseInt(port)),
                    new UsernamePasswordCredentials(userName, password));
        }
        // request interceptor
        ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (logger.isInfoEnabled()) {
                    RequestLine requestLine = request.getRequestLine();
                    logger.info(
                            ">> " + requestLine.getMethod() + " " + URI.create(requestLine.getUri()).getPath());
                }
            }
        });
        // response interceptor
        ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                if (logger.isInfoEnabled())
                    logger.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        logger.error("Error Creating HTTP client {}. ", e);
        throw new IllegalStateException(e);
    }
    return true;

}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }/*from   ww  w.ja v  a2  s . com*/

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}

From source file:zsk.YTDownloadThread.java

boolean downloadone(String sURL) {
    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.iRecursionCount++;

    // stop recursion
    try {/*from www  .j  a v  a 2  s .  co  m*/
        if (sURL.equals(""))
            return (false);
    } catch (NullPointerException npe) {
        return (false);
    }
    if (JFCMainClient.getbQuitrequested())
        return (false); // try to get information about application shutdown

    debugoutput("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {
        // determine http_proxy environment variable
        if (!this.getProxy().equals("")) {

            String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", "");
            this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""),
                    Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http");

            SchemeRegistry supportedSchemes = new SchemeRegistry();
            supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUseExpectContinue(params, true);

            ClientConnectionManager ccm = new PoolingClientConnectionManager(supportedSchemes);

            // with proxy
            this.httpclient = new DefaultHttpClient(ccm, params);
            this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy);
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        } else {
            // without proxy
            this.httpclient = new DefaultHttpClient();
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        }
        this.httpget = new HttpGet(getURI(sURL));
        if (sURL.toLowerCase().startsWith("https"))
            this.target = new HttpHost(getHost(sURL), 443, "https");
        else
            this.target = new HttpHost(getHost(sURL), 80, "http");
    } catch (Exception e) {
        debugoutput(e.getMessage());
    }

    debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString()));
    debugoutput("uri: ".concat(this.httpget.getURI().toString()));
    debugoutput("host: ".concat(this.target.getHostName()));
    debugoutput("using proxy: ".concat(this.getProxy()));

    // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work)
    /*
    this.localContext = new BasicHttpContext();
    if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context)
    ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient
    */

    // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again?

    try {
        this.response = this.httpclient.execute(this.target, this.httpget, this.localContext);
    } catch (ClientProtocolException cpe) {
        debugoutput(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ")
                .concat(uhe.getMessage()));
        debugoutput(uhe.getMessage());
    } catch (IOException ioe) {
        debugoutput(ioe.getMessage());
    } catch (IllegalStateException ise) {
        debugoutput(ise.getMessage());
    }

    /*
    CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN);
    CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC);
    CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ;
    try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( )));
    } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute
    try {
       debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString()));
       debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString()));
       debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString()));
    } catch (NullPointerException npe) {
    }
    */

    try {
        debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString()));
        //for (int i = 0; i < response.getAllHeaders().length; i++) {
        //   debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue()));
        //}

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID()));
            rc = downloadone(this.vNextVideoURL.get(0).getsURL());
            return (rc);
        }
        if (rc302)
            debugoutput(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.sVideoURL = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)"))
                this.textreader = new BufferedReader(new InputStreamReader(entity.getContent()));
            else
                this.binaryreader = new BufferedInputStream(entity.getContent());
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.sContentType.matches("^text/html(.*)")) {
                rc = savetextdata();
                // test if we got the binary content
            } else if (this.sContentType.matches("video/(.)*")) {
                if (JFCMainClient.getbNODOWNLOAD())
                    reportheaderinfo();
                else
                    savebinarydata();
            } else { // content-type is not video/
                rc = false;
                this.sVideoURL = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpclient.getConnectionManager().shutdown();

    debugoutput("done: ".concat(sURL));
    if (this.sVideoURL == null)
        this.sVideoURL = ""; // to prevent NPE

    if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) {
        // no more recursion - html source hase been read
        // test !rc than video could not downloaded because of some error (like wrong protocol or restriction)
        if (!rc) {
            debugoutput("cannot download video - URL does not seem to be valid or could not be found: "
                    .concat(this.sURL));
            output(JFCMainClient.isgerman()
                    ? "es gab ein Problem die Video URL zu finden! evt. wegen Landesinschrnkung?!"
                    : "there was a problem getting the video URL! perhaps not allowed in your country?!");
            output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!"
                    : "consider reporting the URL to author! - ").concat(this.sURL));
            this.sVideoURL = null;
        }
    } else {
        // enter recursion - download video resource
        debugoutput("try to download video from URL: ".concat(this.sVideoURL));
        rc = downloadone(this.sVideoURL);
    }
    this.sVideoURL = null;

    return (rc);

}

From source file:org.graphity.core.util.jena.HttpOp.java

/** Create an HttpClient that performs connection pooling.  This can be used
 * with {@link #setDefaultHttpClient} or provided in the HttpOp calls.
 *//*from  w  w  w.j  av a 2  s.c  o  m*/
public static HttpClient createCachingHttpClient() {
    return new SystemDefaultHttpClient() {
        /** See SystemDefaultHttpClient (4.2).  This version always sets the connection cache */
        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            PoolingClientConnectionManager connmgr = new PoolingClientConnectionManager(
                    SchemeRegistryFactory.createSystemDefault());
            String s = System.getProperty("http.maxConnections", "5");
            int max = Integer.parseInt(s);
            connmgr.setDefaultMaxPerRoute(max);
            connmgr.setMaxTotal(2 * max);
            return connmgr;
        }
    };
}

From source file:com.dumiduh.das.AnalyticsAPIInvoker.java

private String invoke(String url, String username, String pwd, String type) {
    TrustStrategyExt strategy = new TrustStrategyExt();

    String jsonString = "";
    try {//from   ww  w.ja v a 2  s  .c o m
        SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", Integer.parseInt(port), sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        DefaultHttpClient client = new DefaultHttpClient(ccm);
        HttpGet get = new HttpGet(url);
        String header = "Basic " + getBase64EncodedToken(username, pwd);
        get.setHeader("Authorization", header);

        HttpResponse resp = client.execute(get);
        if (type.equals("body")) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonString = result.toString();
        } else if (type.equals("header")) {
            StringBuffer result = new StringBuffer();
            Header[] headers = resp.getAllHeaders();
            for (Header h : headers) {

                result.append(h.getName() + " : " + h.getValue());
            }
            result.append("status code : " + resp.getStatusLine().getStatusCode());
            jsonString = result.toString();
        }

        client.close();

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return jsonString;
}

From source file:com.unboundid.scim.sdk.examples.ClientExample.java

/**
 * Create an SSL-enabled Wink client config from the provided information.
 * The returned client config may be used to create a SCIM service object.
 * IMPORTANT: This should not be used in production because no validation
 * is performed on the server certificate returned by the SCIM service.
 *
 * @param userName    The HTTP Basic Auth user name.
 * @param password    The HTTP Basic Auth password.
 *
 * @return  An Apache Wink client config.
 *//*from w  ww .  j a  v a 2s  .  com*/
public static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {
    SSLSocketFactory sslSocketFactory;
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLS");

        // Do not use these settings in production.
        sslContext.init(null, new TrustManager[] { new BlindTrustManager() }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getLocalizedMessage());
    }

    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()));
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);
    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:com.wso2telco.dep.verificationhandler.verifier.ACRHandler.java

/**
 * Gets the msisdn./*from   www .j a  v a  2s  . c o m*/
 *
 * @param Url the url
 * @param Requeststr the requeststr
 * @return the msisdn
 * @throws UnsupportedEncodingException the unsupported encoding exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private String getMSISDN(String Url, String Requeststr)
        throws UnsupportedEncodingException, IOException, JSONException {

    String Authtoken = "con123";
    String retStr = "";

    log.info("RequestString =" + Requeststr);

    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());

    HttpClient client = new DefaultHttpClient(connManager);
    //DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(Url);
    postRequest.addHeader("accept", "application/json");
    postRequest.addHeader("authorization", "ServiceKey " + Authtoken);

    StringEntity input = new StringEntity(Requeststr);
    input.setContentType("application/json");
    postRequest.setEntity(input);

    HttpResponse response = client.execute(postRequest);

    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

    String output;
    while ((output = br.readLine()) != null) {
        retStr += output;
    }

    log.info("ACR Response " + retStr);
    client.getConnectionManager().shutdown();

    org.json.JSONObject jsonBody = null;
    jsonBody = new org.json.JSONObject(retStr.toString());

    String msisdn = jsonBody.getJSONObject("decodeAcrResponse").getString("msisdn");

    return msisdn;
}

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

public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {/*w  w  w .  j  a  v  a2 s .  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;

        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();

        Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(httpScheme);

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

        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);
        }

        // closes the single connection
        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

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

        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:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java

/**
 * Creates PoolingClientConnectionManager
 *
 * @param url/*from   w ww  .  j a  v  a2  s.co  m*/
 * @param port
 *
 * @return {@link ClientConnectionManager}
 */
private ClientConnectionManager createPoolingClientConnectionManager(String url, int port) {
    SchemeRegistry schemeRegistry = createSchemeRegistry(url, port);

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(MAX_CONNECTIONS);
    cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    cm.setMaxPerRoute(new HttpRoute(new HttpHost(getHost(url), getPort(url, port))), MAX_CONNECTIONS_PER_HOST);

    return cm;
}