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:net.sourceforge.ganttproject.client.RssFeedChecker.java

private Runnable createRssReadCommand() {
    return new Runnable() {
        @Override//from  ww w .  j  a v  a  2  s. c  o m
        public void run() {
            GPLogger.log("Starting RSS check...");
            HttpClient httpClient = new DefaultHttpClient();
            String url = RSS_URL;
            try {
                for (int i = 0; i < MAX_ATTEMPTS; i++) {
                    HttpGet getRssUrl = new HttpGet(url);
                    getRssUrl.addHeader("User-Agent", "GanttProject " + GPVersion.CURRENT);
                    HttpResponse result = httpClient.execute(getRssUrl);

                    switch (result.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_OK:
                        processResponse(result.getEntity().getContent());
                        return;
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
                GPLogger.log("RSS check finished");
            }
        }

        private void processResponse(InputStream responseStream) {
            RssFeed feed = parser.parse(responseStream, myLastCheckOption.getValue());
            List<NotificationItem> items = new ArrayList<NotificationItem>();
            for (RssFeed.Item item : feed.getItems()) {
                items.add(new NotificationItem(item.title, item.body,
                        NotificationManager.DEFAULT_HYPERLINK_LISTENER));
            }
            Collections.reverse(items);
            if (!items.isEmpty()) {
                getNotificationManager().addNotifications(NotificationChannel.RSS, items);
            }
            markLastCheck();
        }
    };
}

From source file:org.caboclo.clients.ApiClient.java

protected void downloadURL(String url, File file, Map<String, String> headers)
        throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    for (String key : headers.keySet()) {
        String value = headers.get(key);

        httpget.setHeader(key, value);//w  ww.  j  a va2  s.  com
    }

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (IllegalStateException ex) {
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:test.Http.java

public static String submit(String url, String requestJson, List<File> upFiles) {
    String result = "";
    System.out.println("json:" + requestJson);
    HttpClient httpclient = new DefaultHttpClient();
    InputStream instream = null;//  w  ww .j a  v  a2 s . c o  m
    try {
        HttpPost httpPost = new HttpPost(url);
        //         MultipartEntity multipartEntity = new MultipartEntity();
        //         multipartEntity.addPart("requestJson", new StringBody(requestJson,
        //               Charset.forName("UTF-8")));
        //         for (File file : upFiles) {
        //            FileBody fileBody = new FileBody(file);
        //            multipartEntity.addPart("file", (ContentBody) fileBody);
        //         }
        //         httpPost.setEntity(multipartEntity);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {

            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                instream = httpEntity.getContent();
                // 
                BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
                String line = null;
                result = "";
                while ((line = reader.readLine()) != null) {
                    result += line;
                }

            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        httpclient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.couchbase.capi.TestCouchbase.java

public void testPools() throws Exception {
    HttpClient client = getClient();

    HttpUriRequest request = new HttpGet(String.format("http://localhost:%d/pools", port));

    HttpResponse response = client.execute(request);

    Assert.assertEquals(200, response.getStatusLine().getStatusCode());

    HttpEntity entity = response.getEntity();

    Map<String, List<Map<String, Object>>> details = null;
    if (entity != null) {
        InputStream input = entity.getContent();
        try {/*from  w ww.j av a  2 s.  c om*/
            details = mapper.readValue(input, Map.class);
        } finally {
            input.close();
        }
    }

    Assert.assertTrue(details.containsKey("pools"));
    Assert.assertEquals(1, details.get("pools").size());
    Assert.assertEquals("default", details.get("pools").get(0).get("name"));
    Assert.assertEquals("/pools/default?uuid=00000000000000000000000000000000",
            details.get("pools").get(0).get("uri"));

    client.getConnectionManager().shutdown();
}

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

/**
 * Creates a new workspace. If the workspace already exists,It continues.
 * /*from  w  w  w  . java  2 s  .  c  o  m*/
 */
static void createCommanderWorkspace(String workspaceName) throws Exception {

    props = getProperties();
    HttpClient httpClient = new DefaultHttpClient();
    JSONObject jo = new JSONObject();

    try {

        String url = "http://" + props.getProperty(StringConstants.COMMANDER_SERVER)
                + ":8000/rest/v1.0/workspaces/";
        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))));

        HttpPost httpPostRequest = new HttpPost(url);
        jo.put("workspaceName", workspaceName);
        jo.put("description", workspaceName);
        jo.put("agentDrivePath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUncPath", "C:/Program Files/Electric Cloud/ElectricCommander");
        jo.put("agentUnixPath", "/opt/electriccloud/electriccommander");
        jo.put("local", true);

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPostRequest.setEntity(input);
        httpPostRequest.setHeader("Authorization", "Basic " + encoding);
        HttpResponse httpResponse = httpClient.execute(httpPostRequest);

        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            System.out.println("Commander workspace already exists.Continuing....");
        } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException(
                    "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-"
                            + httpResponse.getStatusLine().getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

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

/**
 * {@inheritDoc}/* www.j a  v a  2s.c  o  m*/
 * 
 * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String)
 */
@Override
public void execute(String serverUrl) throws Exception {
    logger.info("Preparing test of greeter action");

    String requestUrl = UrlUtils.concat(serverUrl, "greeting/index.xml");

    // Load the test data
    Map<String, String> greetings = TestSiteUtils.loadGreetings();
    Set<String> languages = greetings.keySet();

    // Prepare the request
    logger.info("Testing greeter action's xml output");
    logger.info("Sending requests to {}", requestUrl);

    for (String language : languages) {
        String greeting = greetings.get(language);
        HttpGet request = new HttpGet(requestUrl);
        String[][] params = new String[][] { { "language", language } };

        // 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, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

            // Find the content encoding
            Assert.assertNotNull(response.getFirstHeader("Content-Type"));
            Assert.assertNotNull(
                    response.getFirstHeader("Content-Type").getElements()[0].getParameterByName("charset"));
            String charset = response.getFirstHeader("Content-Type").getElements()[0]
                    .getParameterByName("charset").getValue();

            Document xml = TestUtils.parseXMLResponse(response);
            String xpath = "/greetings/greeting[@language=\"" + language + "\"]/text()";

            String greetingEncoded = new String(greeting.getBytes(charset));
            Assert.assertEquals(greetingEncoded, XPathHelper.valueOf(xml, xpath));
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:ch.entwine.weblounge.test.harness.rest.PagesEndpointTest.java

/**
 * Locks the page./*www  . j a  va2s .  co  m*/
 * 
 * @param serverUrl
 *          the server url
 * @param id
 *          the page identifier
 * @throws Exception
 *           if updating failed
 */
private void testLockPage(String serverUrl, String id) throws Exception {
    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages/", id);

    // Lock the page
    HttpPut lockRequest = new HttpPut(UrlUtils.concat(requestUrl, "lock"));
    HttpClient httpClient = new DefaultHttpClient();
    logger.info("Locking the page at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, lockRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.jigarmjoshi.service.RestService.java

private void executeRequest(HttpUriRequest request, String url) {

    HttpClient client = new DefaultHttpClient();

    // no response within 120 seconds
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120 * 1000);

    // this one causes a timeout if no connection is established within 5min
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300 * 1000);

    HttpResponse httpResponse;// www. j  a v  a 2  s . c om

    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException ex) {
        client.getConnectionManager().shutdown();
        Log.e(RestService.class.getSimpleName(), "Failed to execute rest call ", ex);
    } catch (IOException ex) {
        client.getConnectionManager().shutdown();
        Log.e(RestService.class.getSimpleName(), "Failed to execute rest call ", ex);
    }
}

From source file:org.openintents.openpgp.keyserver.HkpKeyServer.java

@Override
public String get(long keyId) throws QueryException {
    HttpClient client = new DefaultHttpClient();
    try {//from w w w .  jav a2 s  . c o m
        HttpGet get = new HttpGet(
                "http://" + mHost + ":" + mPort + "/pks/lookup?op=get&search=0x" + KeyInfo.hexFromKeyId(keyId));

        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new QueryException("not found");
        }

        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        String data = readAll(is, EntityUtils.getContentCharSet(entity));
        Matcher matcher = PGP_PUBLIC_KEY.matcher(data);
        if (matcher.find()) {
            return matcher.group(1);
        }
    } catch (IOException e) {
        e.printStackTrace();
        // nothing to do, better luck on the next keyserver
    } finally {
        client.getConnectionManager().shutdown();
    }

    return null;
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * executing request from post in execute restclient
 *
 * *//*w w w.  ja  v a  2  s  .  c o m*/
private void executeRequest(HttpUriRequest request, String url) throws Exception {
    HttpClient client = getNewHttpClient();//; new DefaultHttpClient(httpParams);
    HttpResponse httpResponse;
    try {
        httpResponse = client.execute(request);
        responseCode = httpResponse.getStatusLine().getStatusCode();
        message = httpResponse.getStatusLine().getReasonPhrase();
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            response = convertStreamToString(instream);
            instream.close();
        }
    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        Log.d("RestClientExecption", "protocol error at:" + this.url);
        e.printStackTrace();
        throw new Exception();
    } catch (IOException e) {
        Log.d("RestClientExecption", "I/O error at:" + this.url);
        client.getConnectionManager().shutdown();
        e.printStackTrace();
        throw new Exception();
    }
}