Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:it.tai.solr.http.HttpInvoker.java

public SolrResponse getSolrReport(REPORT_ACTION action) throws IOException, UnsupportedActionException {

    String url;/*w  w w . j ava  2 s.c  o  m*/

    switch (action) {
    case SUMMARY:
        url = solrURL + "action=" + REPORT_ACTION.SUMMARY.getCode() + "&wt=json";
        break;
    case REPORT:
        url = solrURL + "action=" + REPORT_ACTION.REPORT.getCode() + "&wt=json";
        break;
    default:
        throw new UnsupportedActionException("Unsupported report action");
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        HttpGet httpget = new HttpGet(url);
        logger.info("Excuting SOLR report request: " + httpget.getRequestLine());
        long currTime = System.currentTimeMillis();

        CloseableHttpResponse response = httpclient.execute(httpget);
        responseTime("SOLR report ", currTime);

        checkResponse(response);

        String data = EntityUtils.toString(response.getEntity());

        if (logger.isDebugEnabled()) {
            logger.debug("Response data \n" + data);
        }

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);

        JsonNode root = mapper.readTree(data).path("Summary").path("alfresco").path("Searcher");

        SolrResponse toReturn = mapper.readValue(root.traverse(), SolrResponse.class);
        toReturn.setRawResponse(data);
        toReturn.setUrl(httpget.getRequestLine().getUri());

        return toReturn;

    } finally {
        httpclient.close();
    }
}

From source file:com.aws.image.flickr.FlickrAPI.java

public String callFlickrAPIForEachKeyword(String query, String synsetCode, String safeSearch,
        int urlsPerKeyword) throws IOException, JSONException {
    String apiKey = "5dfc9f4453ed8205f230164a5ff484b1";
    String apiSecret = "71693b1aea42a504";

    int total = 500;
    int perPage = 500;

    int rankCounter = 0;
    int counter = 0;

    System.out.println("\n\t\t KEYWORD::" + query);
    System.out.println("\t No. of urls required::" + urlsPerKeyword);
    int totalPages;

    if (query == null || "".equals(query.trim())) {
        return null;
    }//  ww  w . java  2 s  .  c  o m

    if (urlsPerKeyword % perPage != 0)
        totalPages = (urlsPerKeyword / perPage) + 1;
    else
        totalPages = urlsPerKeyword / perPage;

    System.out.println("\n\n\t total pages ::" + totalPages);

    int currentCount = 0;

    int eachPage;
    List<Document> documentsInBatch = new ArrayList<>();

    for (int i = 1; i <= totalPages && currentCount <= total; i++, currentCount = currentCount + perPage) {
        documentsInBatch = new ArrayList<>();

        eachPage = urlsPerKeyword < perPage ? urlsPerKeyword : perPage;

        StringBuffer sb = new StringBuffer(512);
        sb.append("https://api.flickr.com/services/rest/?method=flickr.photos.search&text=")
                .append(URLEncoder.encode(query, "UTF-8")).append("&safe_search=").append(safeSearch)
                .append("&extras=url_c,url_m,url_n,license,owner_name&per_page=").append(eachPage)
                .append("&page=").append(i).append("&format=json&api_key=").append(apiKey)
                .append("&api_secret=").append(apiSecret).append("&license=4,5,6,7,8");

        String url = sb.toString();

        System.out.println("URL FORMED --> " + url);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        String responseString = response.toString();

        responseString = responseString.replace("jsonFlickrApi(", "");

        int length = responseString.length();

        responseString = responseString.substring(0, length - 1);

        // print result
        httpClient.close();

        JSONObject json = null;
        try {
            json = new JSONObject(responseString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //System.out.println("Converted JSON String " + json);

        JSONObject photosObj = json.has("photos") ? json.getJSONObject("photos") : null;
        total = photosObj.has("total") ? (Integer.parseInt(photosObj.getString("total"))) : 0;
        perPage = photosObj.has("perpage") ? (Integer.parseInt(photosObj.getString("perpage"))) : 0;

        //System.out.println(" perPage --> " + perPage + " total --> " + total);

        JSONArray photoArr = photosObj.getJSONArray("photo");
        //System.out.println("Length of Array --> " + photoArr.length());
        String scrapedImageURL = "";

        for (int itr = 0; itr < photoArr.length(); itr++) {
            JSONObject tempObject = photoArr.getJSONObject(itr);
            scrapedImageURL = tempObject.has("url_c") ? tempObject.getString("url_c")
                    : tempObject.has("url_m") ? tempObject.getString("url_m")
                            : tempObject.has("url_n") ? tempObject.getString("url_n") : null;

            if (scrapedImageURL == null) {
                continue;
            }
            String contributor = tempObject.getString("ownername");
            String license = tempObject.getString("license");

            //System.out.println("Scraped Image URL, need to insert this to Mongo DB --> " + scrapedImageURL);

            documentsInBatch.add(getDocumentPerCall(scrapedImageURL, contributor, license, synsetCode, query,
                    ++rankCounter));

            counter++;
        }

        insertData(documentsInBatch);
    }

    System.out.println("F L I C K R      C O U N T E R -> " + counter);
    //insertData(documentsInBatch);

    countDownLatchForImageURLs.countDown();
    return null;
}

From source file:org.keycloak.testsuite.oauth.OAuthRedirectUriTest.java

@Test
public void testWithCustomScheme() throws IOException {
    oauth.clientId("custom-scheme");

    oauth.redirectUri(//from  w w  w.  jav  a2 s.  co m
            "android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
    oauth.openLoginForm();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    String loginUrl = driver.getCurrentUrl();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore).build();

    try {
        String loginPage = SimpleHttp.doGet(loginUrl, client).asString();

        String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&amp;", "&");
        SimpleHttp.Response response = SimpleHttp.doPost(formAction, client)
                .param("username", "test-user@localhost").param("password", "password").asResponse();

        response.getStatus();
        assertThat(response.getFirstHeader("Location"), Matchers.startsWith(
                "android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
    } finally {
        client.close();
    }
}

From source file:org.skfiy.typhon.rnsd.service.impl.RechargingServiceImpl.java

@Transactional
@Override/*from  www.  ja  v  a2 s .c o  m*/
public void giveZucks(JSONObject json) throws TradeValidatedException {
    Zucks zucks = new Zucks();
    zucks.setOs(OS.valueOf(json.getString("os")));
    zucks.setZid(json.getString("id"));
    zucks.setPoint(json.getIntValue("point"));
    zucks.setUid(json.getString("userId"));

    // validate
    String sha1 = DigestUtils
            .sha1Hex(zucksKeys.get(zucks.getOs()) + zucks.getUid() + zucks.getPoint() + zucks.getZid());
    if (!json.getString("verify").equals(sha1)) {
        throw new TradeValidatedException(sha1, "verify failed");
    }

    rechargingRepository.save(zucks);

    Region region = regionService.loadAll().get(0);

    CloseableHttpClient hc = HC_BUILDER.build();
    HttpHost httpHost = new HttpHost(region.getIp(), region.getJmxPort());

    StringBuilder query = new StringBuilder();
    query.append(
            "/InvokeAction//org.skfiy.typhon.spi%3Aname%3DGMConsoleProvider%2Ctype%3Dorg.skfiy.typhon.spi.GMConsoleProvider/action=pushItem?action=pushItem");
    query.append("&uid%2Bjava.lang.String=").append(zucks.getUid());
    query.append("&iid%2Bjava.lang.String=").append("w036");
    query.append("&count%2Bjava.lang.String=").append(zucks.getPoint());

    HttpGet httpGet = new HttpGet(query.toString());
    httpGet.addHeader("Authorization", basicAuth);

    CloseableHttpResponse response = null;
    try {
        response = hc.execute(httpHost, httpGet);
    } catch (IOException ex) {
        LOG.error("host:port -> {}:{}", region.getIp(), region.getJmxPort(), ex);
        throw new RechargingException("send to game server error error", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }

    if (response == null || response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) {
        LOG.error("recharging failed. {}", response);
        throw new RechargingException("recharging failed");
    }
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected HttpResponse executeRequest(HttpUriRequest uriRequest, Header... header) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from w w w. ja v a 2  s  . c  o  m*/

        httpClient = getHttpClient();

        if (header != null && header.length > 0) {
            for (int i = 0; i < header.length; i++) {
                Header h = header[i];
                uriRequest.addHeader(h);
            }
        }

        HttpResponse res = new HttpResponse(httpClient.execute(uriRequest));
        log.trace(res.getBody());
        return res;
    } finally {

        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.sicongtang.http.httpcomponents.httpclient.basic.ClientWithResponseHandler.java

public void execute(int count, String url) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  www . jav  a2 s .c  o  m*/
        HttpGet httpget = new HttpGet(url);

        System.out.println(count + " Executing request " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.print("----------------------------------------");
        System.out.println(responseBody);
    } finally {
        httpclient.close();
    }
}

From source file:kr.co.koscom.openapitest.ExecuteQuery2.java

public ResultSet ExecuteQuery() throws UnsupportedEncodingException, IOException {
    String accessTokenCached;/*w  w w.  j a v a  2 s . co m*/
    accessTokenCached = ovc.getAccessToken();
    System.out.println("AccessToken2 = [" + accessTokenCached + "]");
    // Request feed data with access token
    String requestUrl;
    String JSON_STRING;
    switch (querytype) {
    case "account":
        requestUrl = HttpConstants.API_GW_ENDPOINT + company + HttpConstants.API_ACCOUNT_BALANCE_TAIL;
        JSON_STRING = "{" + "  \"accInfo\": {" + "    \"vtAccNo\": \"" + accountNo + "\"" + "  },"
                + "  \"balanceRequestBody\": {" + "    \"queryType\": {" + "      \"assetType\": \"" + assettype
                + "\"," + "      \"count\": 0," + "      \"page\": \"" + pageno + "\"" + "    }" + "  },"
                + "  \"commonHeader\": {" + "    \"ci\": \"" + ci + "\"," + "    \"reqIdConsumer\": \"string\""
                + "  }," + "  \"devInfo\": {" + "    \"ipAddr\": \"IP\"," + "    \"macAddr\": \"string\""
                + "  }," + "  \"partner\": {" + "    \"comId\": \"F0000\"," + "    \"srvId\": \"Mock\"" + "  }"
                + "}";
        break;
    case "portfolio":
        requestUrl = HttpConstants.API_GW_ENDPOINT + company + HttpConstants.API_ACCOUNT_PORTFOLIO_TAIL;
        JSON_STRING = "{\"accInfo\":{\"vtAccNo\":\"" + accountNo + "\"},\"commonHeader\":{\"ci\":\"" + ci
                + "\",\"reqIdConsumer\":\"string\"},\"devInfo\":{\"ipAddr\":\"string\",\"macAddr\":\"string\"},\"partner\":{\"comId\":\"string\",\"srvId\":\"string\"},\"portfolioRequestBody\":{\"queryType\":{\"assetType\":\""
                + assettype + "\",\"count\":0,\"page\":\"" + pageno + "\",\"rspType\":\"" + rsptype + "\"}}}";
        break;
    case "transaction":
        requestUrl = HttpConstants.API_GW_ENDPOINT + company + HttpConstants.API_ACCOUNT_TRANSACTION_TAIL;
        JSON_STRING = "{\"accInfo\":{\"vtAccNo\":\"" + accountNo + "\"},\"commonHeader\":{\"ci\":\"" + ci
                + "\",\"reqIdConsumer\":\"string\"},\"devInfo\":{\"ipAddr\":\"string\",\"macAddr\":\"string\"},\"partner\":{\"comId\":\"string\",\"srvId\":\"string\"},\"transactionHistoryRequestBody\":{\"queryParams\":{\"conunt\":0,\"fromDate\":\"20160301\",\"isinCode\":\"\",\"page\":\""
                + pageno + "\",\"side\":\"ALL\",\"toDate\":\"20160330\"}}}";
        break;
    case "interest":
        requestUrl = HttpConstants.API_GW_ENDPOINT + company + HttpConstants.API_ACCOUNT_INTEREST_TAIL;
        JSON_STRING = "{\"accInfo\":{\"vtAccNo\":\"" + accountNo + "\"},\"commonHeader\":{\"ci\":\"" + ci
                + "\",\"reqIdConsumer\":\"string\"},\"devInfo\":{\"ipAddr\":\"string\",\"macAddr\":\"string\"},\"partner\":{\"comId\":\"string\",\"srvId\":\"string\"}}";
        break;
    default:
        requestUrl = HttpConstants.API_GW_ENDPOINT + company + HttpConstants.API_ACCOUNT_BALANCE_TAIL;
        JSON_STRING = "{" + "  \"accInfo\": {" + "    \"vtAccNo\": \"" + accountNo + "\"" + "  },"
                + "  \"balanceRequestBody\": {" + "    \"queryType\": {" + "      \"assetType\": \"" + assettype
                + "\"," + "      \"count\": 0," + "      \"page\": \"" + pageno + "\"" + "    }" + "  },"
                + "  \"commonHeader\": {" + "    \"ci\": \"" + ci + "\"," + "    \"reqIdConsumer\": \"string\""
                + "  }," + "  \"devInfo\": {" + "    \"ipAddr\": \"IP\"," + "    \"macAddr\": \"string\""
                + "  }," + "  \"partner\": {" + "    \"comId\": \"F0000\"," + "    \"srvId\": \"Mock\"" + "  }"
                + "}";
        break;
    }

    HttpResponse httpResponse;
    StringBuffer responseBody;
    CloseableHttpClient httpClient;

    httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setHeader("Authorization", "Bearer " + accessTokenCached);
    httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
    httpPost.addHeader("apikey", HttpConstants.THIS_APP_CLIENT_ID);
    StringEntity requestEntity = new StringEntity(JSON_STRING);
    System.out.println("[QueryString       ] - [" + JSON_STRING + "]");
    httpPost.setEntity(requestEntity);
    httpResponse = httpClient.execute(httpPost);
    // do streamed by response body

    responseBody = new StringBuffer();
    try (BufferedReader br = new BufferedReader(
            new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"))) {
        String lineBuffer = null;
        while ((lineBuffer = br.readLine()) != null) {
            responseBody.append(lineBuffer);
            responseBody.append("\n");
        }
    }
    httpClient.close();

    int respCode = httpResponse.getStatusLine().getStatusCode();
    if (respCode != HttpConstants.HTTP_OK) {
        resultSet.setMessage(responseBody.toString());
        resultSet.setStatusCode(respCode);
        resultSet.setStatus(httpResponse.getStatusLine().toString());

        return resultSet;
    }
    resultSet.setStatusCode(respCode);
    resultSet.setMessage(httpResponse.getStatusLine().getReasonPhrase());
    String resultMsg;
    System.out.println("Body - [" + responseBody + "]");
    resultMsg = getResultMsg(responseBody);
    resultSet.setMessage(resultMsg);
    return resultSet;
}

From source file:com.bluetag.api.search.service.SearchService.java

public String searchUsers(String queryString) {

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet queryInfoGet = new HttpGet(cloudantURI + searchPath + queryString);
    queryInfoGet.addHeader(authHeaderKey, authHeaderValue);
    queryInfoGet.addHeader(acceptHeaderKey, acceptHeaderValue);
    queryInfoGet.addHeader(contentHeaderKey, contentHeaderValue);
    System.out.println("searchUsers queryString: " + searchPath + queryString);
    try {//from   www  .java2  s .co m
        HttpResponse queryInfoResp = httpclient.execute(queryInfoGet);

        Gson gson = new Gson();
        SearchResultsModel gsonSearchResults = gson.fromJson(EntityUtils.toString(queryInfoResp.getEntity()),
                SearchResultsModel.class);
        searchList.clear();
        for (SearchResultsRowModel row : gsonSearchResults.getRows()) {
            searchList.add(row.getId());
            System.out.println(searchList);
        }

        gsonSearchList.setProcessedResults(searchList);

        System.out.println("Entity info: " + gson.toJson(gsonSearchResults));
        System.out.println("Processed search results: " + gson.toJson(searchList));
        httpclient.close();
        return gson.toJson(gsonSearchList);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            httpclient.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return failJson;
    }
}

From source file:org.hawkular.apm.tests.agent.opentracing.client.http.ApacheHttpClientITest.java

protected void testHttpClientWithoutResponseHandler(HttpUriRequest request, boolean fault, boolean respexpected)
        throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w  w  w .ja va  2 s  .c  o  m
        request.addHeader("test-header", "test-value");
        if (fault) {
            request.addHeader("test-fault", "true");
        }
        if (!respexpected) {
            request.addHeader("test-no-data", "true");
        }

        HttpResponse response = httpclient.execute(request);

        int status = response.getStatusLine().getStatusCode();

        if (!fault) {
            assertEquals("Unexpected response code", 200, status);

            if (respexpected) {
                HttpEntity entity = response.getEntity();

                assertNotNull(entity);

                assertEquals(HELLO_WORLD, EntityUtils.toString(entity));
            }
        } else {
            assertEquals("Unexpected fault response code", 401, status);
        }

    } catch (ConnectException ce) {
        assertEquals(BAD_URL, request.getURI().toString());
    } finally {
        httpclient.close();
    }

    Wait.until(() -> getTracer().finishedSpans().size() == 1);

    List<MockSpan> spans = getTracer().finishedSpans();
    assertEquals(1, spans.size());
    assertEquals(Tags.SPAN_KIND_CLIENT, spans.get(0).tags().get(Tags.SPAN_KIND.getKey()));
    assertEquals(request.getMethod(), spans.get(0).operationName());
    assertEquals(request.getURI().toString(), spans.get(0).tags().get(Tags.HTTP_URL.getKey()));
    if (fault) {
        assertEquals("401", spans.get(0).tags().get(Tags.HTTP_STATUS.getKey()));
    }
}