Example usage for org.apache.http.client HttpClient getConnectionManager

List of usage examples for org.apache.http.client HttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getConnectionManager.

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:tap.Tap.java

private static void testMethod() {
    try {//  w  w  w .j a  va2  s .com

        String testdata = new Scanner(new File("testdata.txt")).useDelimiter("\\A").next();

        System.out.println("Uploading Ballots to the server!");

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost("http://localhost:9000/3FF968A3B47CT34C");

        List<BasicNameValuePair> bnvp = new ArrayList();

        bnvp.add(new BasicNameValuePair("record", testdata));
        bnvp.add(new BasicNameValuePair("precinctID", Integer.toString((new Random()).nextInt())));

        /* Set entities for each of the url encoded forms of the NVP */
        post.setEntity(new UrlEncodedFormEntity(bnvp));

        System.out.println("Executing post..." + post.getEntity());

        /* Execute the post */
        client.execute(post);

        System.out.println("Upload complete!");

        /* Shutdown the connection when done */
        client.getConnectionManager().shutdown();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.codegist.crest.io.http.HttpClientFactory.java

public static HttpClient create(CRestConfig crestConfig, Class<?> source) {
    HttpClient httpClient = crestConfig.get(source.getName() + HTTP_CLIENT);
    if (httpClient != null) {
        return httpClient;
    }//from   w w  w. j a  v  a  2  s. co  m

    int concurrencyLevel = crestConfig.getConcurrencyLevel();
    if (concurrencyLevel > 1) {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(concurrencyLevel));
        ConnManagerParams.setMaxTotalConnections(params, concurrencyLevel);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), HTTPS_PORT));

        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);
    } else {
        httpClient = new DefaultHttpClient();
    }
    ((DefaultHttpClient) httpClient).setRoutePlanner(new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    return httpClient;
}

From source file:test.java.ecplugins.weblogic.TestUtils.java

/**
 * Wrapper around a HTTP GET to a REST service
 * //from   w  w  w  .j  av a 2 s.  co m
 * @param url
 * @return JSONObject
 */
static JSONObject performHTTPGet(String url) throws Exception, JSONException {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    String encoding = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils
                    .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":"
                            + props.getProperty(StringConstants.COMMANDER_PASSWORD))));
    try {
        HttpGet httpGetRequest = new HttpGet(url);
        httpGetRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpGetRequest);
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException("HTTP GET failed with " + httpResponse.getStatusLine().getStatusCode()
                    + "-" + httpResponse.getStatusLine().getReasonPhrase());
        }
        return new JSONObject(EntityUtils.toString(httpResponse.getEntity()));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolServiceImpl.java

@Override
public void shutdown() {
    LOG.info("Shutting down HTTP connection pools");
    for (HttpClient client : poolMap.values()) {
        client.getConnectionManager().shutdown();
    }/*from   w  w w  .  jav  a2  s .  c  o m*/
    decommissionManager.stopThread();
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {/*from w w w. j  av a  2  s.  c o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.apache.airavata.client.secure.client.OAuthTokenRetrievalClient.java

/**
 * Retrieve the OAuth Access token via the specified grant type.
 * @param consumerId/* w w  w .j ava2  s . c  o  m*/
 * @param consumerSecret
 * @param userName
 * @param password
 * @param grantType
 * @return
 * @throws SecurityException
 */
public String retrieveAccessToken(String consumerId, String consumerSecret, String userName, String password,
        int grantType) throws AiravataSecurityException {

    HttpPost postMethod = null;
    try {
        //initialize trust store to handle SSL handshake with WSO2 IS properly.
        TrustStoreManager trustStoreManager = new TrustStoreManager();
        SSLContext sslContext = trustStoreManager.initializeTrustStoreManager(Properties.TRUST_STORE_PATH,
                Properties.TRUST_STORE_PASSWORD);
        //create https scheme with the trust store
        org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(
                sslContext);
        Scheme httpsScheme = new Scheme("https", sf, Properties.authzServerPort);

        HttpClient httpClient = new DefaultHttpClient();
        //set the https scheme in the httpclient
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

        postMethod = new HttpPost(Properties.oauthTokenEndPointURL);
        //build the HTTP request with relevant params for resource owner credential grant type
        String authInfo = consumerId + ":" + consumerSecret;
        String authHeader = new String(Base64.encodeBase64(authInfo.getBytes()));

        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Authorization", "Basic " + authHeader);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();

        if (grantType == 1) {
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("username", userName));
            urlParameters.add(new BasicNameValuePair("password", password));

        } else if (grantType == 2) {
            urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
        }

        postMethod.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = httpClient.execute(postMethod);

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

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(result.toString());
        return (String) jsonObject.get("access_token");
    } catch (ClientProtocolException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}

From source file:com.google.appengine.tck.endpoints.support.EndPointClient.java

public void shutdown() {
    if (client != null) {
        HttpClient tmp = client;
        client = null;/*  w  w w .j  a va  2s  .  com*/
        tmp.getConnectionManager().shutdown();
    }
}

From source file:com.google.resting.rest.client.impl.RESTClient.java

/**
 * Executes REST request for HTTP/*from w  ww  .  j  a v  a2s  .c o m*/
 * 
 * @param Domain of the REST endpoint
 * @param path Path of the URI
 * @param port port number of the REST endpoint
 * @param verb Type of HTTP method(GET/POST/PUT/DELETE)
 * 
 * @return ServiceResponse object containing http status code and entire response as a String
 */

public static ServiceResponse invoke(ServiceContext serviceContext) {
    String targetDomain = serviceContext.getTargetDomain();
    int port = serviceContext.getPort();
    EncodingTypes charset = serviceContext.getCharset();

    HttpResponse response = null;
    ServiceResponse serviceResponse = null;
    String functionName = "invoke";

    HttpHost targetHost = new HttpHost(targetDomain, port, RequestConstants.HTTP);

    HttpRequest request = buildHttpRequest(serviceContext);

    HttpClient httpClient = buildHttpClient(serviceContext);

    try {
        // execute is a blocking call, it's best to call this code in a
        // thread separate from the ui's
        final long startTime = System.currentTimeMillis();
        response = httpClient.execute(targetHost, request);
        final long endTime = System.currentTimeMillis();

        serviceResponse = new ServiceResponse(response, charset);

        final long endTime2 = System.currentTimeMillis();

        //   System.out.println( "The REST response is:\n " + serviceResponse);
        System.out.println("Time taken in REST operation : " + (endTime - startTime) + " ms.");
        System.out.println("Time taken in service response construction : " + (endTime2 - endTime) + " ms.");

    } // try
    catch (ConnectTimeoutException e) {
        System.out.println("[" + functionName + "] Connection timed out. The host may be unreachable.");
        e.printStackTrace();

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {

        httpClient.getConnectionManager().shutdown();

    } //try
    return serviceResponse;
}

From source file:realizer.com.schoolgenieparent.ServerUtilities.java

private static StringBuilder postUnregister(String EmpId, String did, String access) {

    String my = Config.URL + "deregisterStudentDevice/" + EmpId + "/" + did;
    Log.d("GCMDID", my);
    builder = new StringBuilder();
    HttpGet httpGet = new HttpGet(my);
    HttpClient client = new DefaultHttpClient();
    httpGet.setHeader("AccessToken", access);
    try {/*from w ww  .j a  v  a  2 s.  c  o m*/
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();

        int statusCode = statusLine.getStatusCode();
        Log.d("GCMSTATUS", "" + statusCode);
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("Error", "Failed to Login");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        client.getConnectionManager().closeExpiredConnections();
        client.getConnectionManager().shutdown();
    }

    return builder;
}

From source file:com.twitter.hbc.httpclient.RestartableHttpClient.java

public void restart() {
    HttpClient old = underlying.get();
    if (old != null) {
        // this will kill all of the connections and release the resources for our old client
        old.getConnectionManager().shutdown();
    }/*w  ww.  j  a  v a 2s.c o m*/
    setup();
}