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:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * Updates the page with the given identifier.
 * /*from w  ww  .j  a va2  s. co  m*/
 * @param serverUrl
 *          the server url
 * @param id
 *          the page identifier
 * @throws Exception
 *           if updating the page fails
 */
private void update(String serverUrl, String id) throws Exception {
    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/pages");

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

    // Publish it
    HttpPut publishPageRequest = new HttpPut(UrlUtils.concat(requestUrl, id, "publish"));
    httpClient = new DefaultHttpClient();
    String[][] params = new String[][] { { "modified", "true" } };
    logger.info("Publishing the page at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, publishPageRequest, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Unlock the page
    HttpDelete unlockRequest = new HttpDelete(UrlUtils.concat(requestUrl, id, "lock"));
    httpClient = new DefaultHttpClient();
    logger.info("Unlocking the page at {}", requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, unlockRequest, null);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:uk.bcu.services.MusicDetailsService.java

public void run() {
    String api_key = "f06e41f0aad377a1aebfe76927318181";
    String url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + api_key + "&mbid="
            + movieId + "&format=json";

    Log.i("URL", url);

    boolean error = false;
    HttpClient httpclient = null;
    try {//from  w w w .  jav a  2  s .  c o m
        httpclient = new DefaultHttpClient();
        HttpResponse data = httpclient.execute(new HttpGet(url));
        HttpEntity entity = data.getEntity();
        String result = EntityUtils.toString(entity, "UTF8");

        JSONresult = new JSONObject(result);

        //if (Integer.valueOf(json.getJSONObject("track").getString("opensearch)) > 0) {
        //  results = json.getJSONObject("results").getJSONObject("trackmatches").getJSONArray("track");
    } catch (Exception e) {
        System.out.println(e.toString());
        movie = null;
        error = true;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    super.serviceComplete(error);
}

From source file:net.sourceforge.subsonic.service.AudioScrobblerService.java

private String[] executeRequest(HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

    try {/*w ww. ja  va  2  s  .  c  o  m*/
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(request, responseHandler);
        return response.split("\\n");

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

From source file:com.impetus.ankush.agent.action.impl.UploadHandler.java

/**
 * A generic method to execute any type of Http Request and constructs a
 * response object.// w w  w.  j  a va 2  s.  c o m
 * 
 * @param requestBase
 *            the request that needs to be exeuted
 * @return server response as <code>String</code>
 */
private static String executeRequest(HttpRequestBase requestBase) {
    String responseString = "";

    InputStream responseStream = null;
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(requestBase);
        if (response != null) {
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                responseStream = responseEntity.getContent();
                if (responseStream != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                    String responseLine = br.readLine();
                    String tempResponseString = "";
                    while (responseLine != null) {
                        tempResponseString = tempResponseString + responseLine
                                + System.getProperty("line.separator");
                        responseLine = br.readLine();
                    }
                    br.close();
                    if (tempResponseString.length() > 0) {
                        responseString = tempResponseString;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    }
    client.getConnectionManager().shutdown();

    return responseString;
}

From source file:hobbyshare.testclient.RestService_TestClient.java

public void test_GetUserProfile() {
    HttpClient httpClient = HttpClientBuilder.create().build();

    try {/*from  w w  w .  j  a  v  a 2s. c o m*/
        HttpGet request = new HttpGet("http://localhost:8095/get_User?userID=1");
        HttpResponse response = httpClient.execute(request);

        System.out.println("---Testing getUserProfile----");
        System.out.println(response.toString());
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
        System.out.println("---End of getUserProfile test----");

    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:net.sourceforge.subsonic.service.VersionService.java

/**
 * Resolves the latest available Subsonic version by screen-scraping a web page.
 *
 * @throws IOException If an I/O error occurs.
 *///from  w  w w .  j a  v a 2 s.com
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 + "?v=" + getLocalVersion());
    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("SUBSONIC_FULL_VERSION_BEGIN(.*)SUBSONIC_FULL_VERSION_END");
    Pattern betaPattern = Pattern.compile("SUBSONIC_BETA_VERSION_BEGIN(.*)SUBSONIC_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 Subsonic final version to: " + latestFinalVersion);
            }
            Matcher betaMatcher = betaPattern.matcher(line);
            if (betaMatcher.find()) {
                latestBetaVersion = new Version(betaMatcher.group(1));
                LOG.info("Resolved latest Subsonic beta version to: " + latestBetaVersion);
            }
            line = reader.readLine();
        }

    } finally {
        reader.close();
    }
}

From source file:servlet.SecurityServlet.java

private String getFacebookAccessToken(String faceCode) {
    String token = null;//from   w  w w . ja  v  a  2  s  . c  o m
    if (faceCode != null && !"".equals(faceCode)) {
        String appId = "303525776508598";
        String redirectUrl = "http://localhost:8080/Facebook_Login/index.sec";
        String faceAppSecret = "9a11d42ee3086b9e62affd4005e9e85d";
        String newUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&redirect_uri="
                + redirectUrl + "&client_secret=" + faceAppSecret + "&code=" + faceCode;
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet(newUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httpget, responseHandler);
            token = StringUtils.removeEnd(StringUtils.removeStart(responseBody, "access_token="),
                    "&expires=5180795");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return token;
}

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

/**
 * Performs a search request for existing content.
 * /*from   w ww  . j a  v a 2 s  .  c  om*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void searchExisting(String serverUrl) throws Exception {
    logger.info("Preparing test of search rest api");

    String requestUrl = UrlUtils.concat(serverUrl, "system/weblounge/search");

    // Prepare the request
    logger.info("Searching for a page");
    HttpGet searchRequest = new HttpGet(requestUrl);

    // Send the request. The response should be a 400 (bad request)
    logger.debug("Sending empty get request to {}", searchRequest.getURI());
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusLine().getStatusCode());
        assertEquals(0, response.getEntity().getContentLength());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that don't yield a result
    String searchTerms = "xyz";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, searchTerms));
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("0", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for search terms that should yield a result
    searchTerms = "Friedrich Nietzsche Suchresultat";
    httpClient = new DefaultHttpClient();
    searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
    String[][] params = new String[][] { { "limit", "5" } };
    logger.info("Sending search request for '{}' to {}", searchTerms, requestUrl);
    try {
        HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Document xml = TestUtils.parseXMLResponse(response);
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@documents"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@hits"));
        assertEquals("0", XPathHelper.valueOf(xml, "/searchresult/@offset"));
        assertEquals("1", XPathHelper.valueOf(xml, "/searchresult/@page"));
        assertEquals("5", XPathHelper.valueOf(xml, "/searchresult/@pagesize"));
        assertEquals("5", XPathHelper.valueOf(xml, "count(/searchresult/result)"));
        assertEquals("4bb19980-8f98-4873-a813-000000000006",
                XPathHelper.valueOf(xml, "/searchresult/result/id"));
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    // Check for exact matches on subjects
    String[] exactMatches = { "Search Topic A", "Search Topic B" };
    for (String searchTerm : exactMatches) {

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for exact match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount == 5);
            Assert.assertTrue(hitCount == 5);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

    }

    // Check for partial matches in fields that should be supporting partial
    // matches
    String[] partialSearchTerms = { "Kurzer Seitentitel", // German title
            "Il titre de la page", // French title
            "Lange Beschreibung", // German description
            "Dscription longue", // French description
            "Hans Muster", // creator, publisher
            "Amlie Poulard", // modifier
            "Friedrich Nietzsche Suchresultat", // element text
            "Ein amsanter Titel", // German element text
            "Un titre joyeux" // French element text
    };

    for (String searchTerm : partialSearchTerms) {
        int fullMatchDocumentCount = 0;
        int fullMatchHitCount = 0;

        // Full match
        httpClient = new DefaultHttpClient();
        searchRequest = new HttpGet(UrlUtils.concat(requestUrl, URLEncoder.encode(searchTerms, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for full match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            fullMatchDocumentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            fullMatchHitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(fullMatchDocumentCount >= 1);
            Assert.assertTrue(fullMatchHitCount >= fullMatchDocumentCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Full match lowercase
        httpClient = new DefaultHttpClient();
        String lowerCaseSearchTerm = searchTerm.toLowerCase();
        searchRequest = new HttpGet(
                UrlUtils.concat(requestUrl, URLEncoder.encode(lowerCaseSearchTerm, "utf-8")));
        params = new String[][] { { "limit", "5" } };
        logger.info("Sending search request for lowercase match of '{}' to {}", searchTerm, requestUrl);
        try {
            HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Document xml = TestUtils.parseXMLResponse(response);
            int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
            int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
            Assert.assertTrue(documentCount >= fullMatchDocumentCount);
            Assert.assertTrue(hitCount >= fullMatchHitCount);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }

        // Partial match
        for (String partialSearchTerm : StringUtils.split(searchTerm)) {
            httpClient = new DefaultHttpClient();
            searchRequest = new HttpGet(
                    UrlUtils.concat(requestUrl, URLEncoder.encode(partialSearchTerm, "utf-8")));
            params = new String[][] { { "limit", "5" } };
            logger.info("Sending search request for partial match of '{}' to {}", searchTerm, requestUrl);
            try {
                HttpResponse response = TestUtils.request(httpClient, searchRequest, params);
                Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
                Document xml = TestUtils.parseXMLResponse(response);
                int documentCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@documents"));
                int hitCount = Integer.parseInt(XPathHelper.valueOf(xml, "/searchresult/@hits"));
                Assert.assertTrue(documentCount > 0);
                Assert.assertTrue(hitCount > 0);
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

}

From source file:org.apache.juddi.v3.tck.UDDI_160_RESTIntergrationTest.java

@Test
public void InquiryREST_GET_Binding() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());

    BindingTemplate bt = getFirstBindingTemplate();
    Assume.assumeTrue(bt != null);/*  w ww .j  av  a 2  s .c  o m*/

    String url = manager.getClientConfig().getHomeNode().getInquiry_REST_Url();

    Assume.assumeNotNull(url);
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url + "?bindingKey=" + bt.getBindingKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    BindingTemplate unmarshal = JAXB.unmarshal(response.getEntity().getContent(), BindingTemplate.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getServiceKey(), bt.getServiceKey());
    Assert.assertEquals(unmarshal.getBindingKey(), bt.getBindingKey());

}

From source file:com.ibm.commerce.worklight.android.search.SearchSuggestionsProvider.java

/**
 * Retrieves the search suggestion JSON array and constructs the search suggestions list
 * For example, the JSON array would follow a similar structure, using a search on the 
 * term 'dress'://from  w w  w.  ja  v  a 2 s  .c o  m
 * 
 * {'terms':
 *     [
 *      {'dress':'766'},
 *      {'dress empire':'62'},
 *      {'dress empire waist':'62'},
 *      {'dress layered':'57'},
 *      ...
 *     ]
 * }
 * 
 * @param string The query term input into the search dialog
 * @return The list of search term suggestions
 */
private List<String> getSearchTermSuggestions(String query) {
    final String METHOD_NAME = CLASS_NAME + ".getSearchTermSuggestions";
    boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG);
    if (loggingEnabled) {
        Log.d(METHOD_NAME, "ENTRY");
    }

    List<String> suggestionList = null;
    if (query == null || query.equals("")) {
        return suggestionList;
    }

    WCHybridApplication wcHybridApp = WCHybridApplication.getInstance();
    String requestUrl = wcHybridApp.getSearchSuggestionUrl(query).toString();
    String suggestionJsonString = null;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIME_OUT);
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    try {
        suggestionJsonString = httpClient.execute(new HttpGet(requestUrl), new BasicResponseHandler());
    } catch (ClientProtocolException e) {
        Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage());
    } catch (IOException e) {
        Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    if (suggestionJsonString != null && !suggestionJsonString.equals("")) {
        try {
            if (loggingEnabled) {
                Log.d(METHOD_NAME, "Suggestion JSON string: " + suggestionJsonString);
            }
            JSONObject json = new JSONObject(suggestionJsonString);
            JSONArray suggestions = json.getJSONArray("terms");
            if (suggestions != null) {
                suggestionList = new ArrayList<String>(suggestions.length());
                for (int i = 0; i < suggestions.length(); i++) {
                    suggestionList.add(suggestions.getJSONObject(i).names().getString(0));
                }
            }
        } catch (JSONException e) {
            Log.d(METHOD_NAME, "Error parsing search suggestion JSON: " + e.getLocalizedMessage());
        }
    }

    if (loggingEnabled) {
        Log.d(METHOD_NAME, "EXIT");
    }
    return suggestionList;
}