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:com.rukman.emde.smsgroups.client.NetworkUtilities.java

private static String executeHttpRequest(HttpUriRequest request)
        throws ClientProtocolException, IOException, JSONException {
    final HttpClient client = getHttpClient();
    StringBuilder sb = new StringBuilder();
    String output = null;/*  w w  w  .  ja  va2  s.  c  o  m*/
    int responseCode;
    try {
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream istream = entity.getContent();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
                int value = reader.read();
                while (value != -1) {
                    sb.append((char) value);
                    value = reader.read();
                }
            } finally {
                if (istream != null) {
                    istream.close();
                }
            }
        }
        responseCode = response.getStatusLine().getStatusCode();
        if (responseCode == HttpStatus.SC_OK) {
            output = sb.toString();
            Log.v(TAG, String.format("Response is: %1$s", output));
        } else {
            setErrorString(new JSONObject(sb.toString()).getString(JSONKeys.KEY_MESSAGE));
            Log.v(TAG, String.format("Error is: %1$s",
                    new JSONObject(sb.toString()).getString(JSONKeys.KEY_MESSAGE)));
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
    return output;
}

From source file:org.apache.camel.component.restlet.RestletSetBodyTest.java

@Test
public void testSetBodyRepresentation() throws Exception {
    HttpGet get = new HttpGet("http://0.0.0.0:" + portNum + "/images/123");
    HttpClient httpclient = new DefaultHttpClient();
    InputStream is = null;/*from   w w w  . j a v a2  s.  com*/
    try {
        HttpResponse response = httpclient.execute(get);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("image/png", response.getEntity().getContentType().getValue());
        is = response.getEntity().getContent();
        assertEquals("Get wrong available size", 10, is.available());
        byte[] buffer = new byte[10];
        is.read(buffer);
        for (int i = 0; i < 10; i++) {
            assertEquals(i + 1, buffer[i]);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
        if (is != null) {
            is.close();
        }
    }
}

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

@Override
public void run() {
    while (!this.done) {
        synchronized (listLock) {

            LOG.trace("Iterating through decommissioned clients...");

            List<HttpClient> clientsToRemove = new ArrayList<HttpClient>();

            for (HttpClient client : clientList) {

                String clientId = client.getParams().getParameter(HttpConnectionPoolProvider.CLIENT_INSTANCE_ID)
                        .toString();//from w w  w . j a  v a2 s . co  m

                if (userManager.hasUsers(clientId)) {
                    LOG.warn("Failed to shutdown connection pool client {} due to a connection still in "
                            + "use after last reconfiguration of Repose.", clientId);
                    break;
                }

                PoolingClientConnectionManager connMan = (PoolingClientConnectionManager) client
                        .getConnectionManager();
                PoolStats stats = connMan.getTotalStats();

                if (stats.getLeased() == 0) { // if no active connections we will shutdown this client
                    LOG.debug("Shutting down client {}", clientId);
                    connMan.shutdown();
                    clientsToRemove.add(client);
                }
            }
            for (HttpClient client : clientsToRemove) {
                clientList.remove(client);
                LOG.info("HTTP connection pool {} has been destroyed.",
                        client.getParams().getParameter(HttpConnectionPoolProvider.CLIENT_INSTANCE_ID));
            }
        }

        try {
            Thread.sleep(DEFAULT_INTERVAL);
        } catch (InterruptedException ex) {
            LOG.info("Interrupted", ex);
            break;
        }

    }

    LOG.info("Shutting down HTTP Client Service Decommissioner");
    Thread.currentThread().interrupt();
}

From source file:ch.entwine.weblounge.test.harness.content.PageContentTest.java

/**
 * Tests for a non-existing page and makes sure that a 404 is returned.
 * //from ww  w  . j  av a 2  s. co m
 * @param serverUrl
 *          the server url
 */
private void testNonExistingPage(String serverUrl) throws Exception {
    logger.info("Preparing test of non-existing page content");

    String requestUrl = UrlUtils.concat(serverUrl, requestPath, "does-not-exist", "index.html");

    logger.info("Sending request to {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);

    // Send and the request and examine the response
    logger.debug("Sending request to {}", request.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, null);
        assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
        TestUtils.parseTextResponse(response);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:at.co.blogspot.javaskeleton.WebClientDevWrapper.java

public static HttpClient wrapClient(final HttpClient base, final int port) {
    try {/*from w  w  w .  ja v a  2 s .co m*/
        final SSLContext ctx = SSLContext.getInstance("TLS");
        final X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(final X509Certificate[] xcs, final String string)
                    throws CertificateException {
            }

            public void checkServerTrusted(final X509Certificate[] xcs, final String string)
                    throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        final X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(final String string, final SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(final String string, final X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(final String string, final String[] strings, final String[] strings1)
                    throws SSLException {
            }

            @Override
            public boolean verify(final String string, final SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        final SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        final ClientConnectionManager ccm = base.getConnectionManager();
        final SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, port));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (final Exception ex) {
        LOG.error("Error enabling https-connections", ex);
        return null;
    }
}

From source file:com.google.appengine.tck.blobstore.support.FileUploader.java

private String getUploadUrl(URL url, Method method, Map<String, String> params)
        throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(url.toURI());
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.addParameter(entry.getKey(), entry.getValue());
    }/*  w  w w.  jav a 2s  . c o  m*/
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpUriRequest request;
        switch (method) {
        case GET:
            request = new HttpGet(builder.build());
            break;
        case POST:
            request = new HttpPost(builder.build());
            break;
        default:
            throw new IllegalArgumentException(String.format("No such method: %s", method));
        }
        HttpResponse response = httpClient.execute(request);
        return EntityUtils.toString(response.getEntity()).trim();
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.solr.client.solrj.impl.CloudSolrServerTest.java

public void customHttpClientTest() {
    CloudSolrServer server = null;//from   w ww  .ja  va2s  .  c  o m
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(HttpClientUtil.PROP_SO_TIMEOUT, 1000);
    HttpClient client = null;

    try {
        client = HttpClientUtil.createClient(params);
        server = new CloudSolrServer(zkServer.getZkAddress(), client);
        assertTrue(server.getLbServer().getHttpClient() == client);
    } finally {
        server.shutdown();
        client.getConnectionManager().shutdown();
    }
}

From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java

@Test
public void testPostConsumer() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT1 + "/customerservice/customers");
    post.addHeader("Accept", "text/xml");
    StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);/*ww w  . j  av  a  2s  .c  om*/
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(200, response.getStatusLine().getStatusCode());
        String id = getCustomerId("Jack");
        assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>" + id
                + "</id><name>Jack</name></Customer>", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.madsonic.service.VersionService.java

/**
 * Resolves the latest available Subsonic version by screen-scraping a web page.
 *
 * @throws IOException If an I/O error occurs.
 *//*  w w w  .j  a v  a2s . co m*/
private void readLatestVersion() throws IOException {

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
    HttpGet method = new HttpGet(VERSION_URL);
    String content;
    try {

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        content = client.execute(method, responseHandler);

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

    BufferedReader reader = new BufferedReader(new StringReader(content));
    Pattern finalPattern = Pattern.compile("MADSONIC_FULL_VERSION_BEGIN_(.*)_MADSONIC_FULL_VERSION_END");
    Pattern betaPattern = Pattern.compile("MADSONIC_BETA_VERSION_BEGIN_(.*)_MADSONIC_BETA_VERSION_END");

    try {
        String line = reader.readLine();
        while (line != null) {
            Matcher finalMatcher = finalPattern.matcher(line);
            if (finalMatcher.find()) {
                latestFinalVersion = new Version(finalMatcher.group(1));
                LOG.info("Resolved latest Madsonic final version to: " + latestFinalVersion);
            }
            Matcher betaMatcher = betaPattern.matcher(line);
            if (betaMatcher.find()) {
                latestBetaVersion = new Version(betaMatcher.group(1));
                LOG.info("Resolved latest Madsonic beta version to: " + latestBetaVersion);
            }
            line = reader.readLine();
        }

    } finally {
        reader.close();
    }
}

From source file:org.apache.camel.component.cxf.cxfbean.CxfBeanTest.java

@Test
public void testPostConsumerUniqueResponseCode() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + PORT1 + "/customerservice/customersUniqueResponseCode");
    post.addHeader("Accept", "text/xml");
    StringEntity entity = new StringEntity(POST2_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);/*from ww w  . jav a  2  s .co m*/
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(201, response.getStatusLine().getStatusCode());
        String id = getCustomerId("James");
        assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>" + id
                + "</id><name>James</name></Customer>", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}