Example usage for org.apache.http.client.methods CloseableHttpResponse close

List of usage examples for org.apache.http.client.methods CloseableHttpResponse close

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse 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:fr.treeptik.cloudunit.service.impl.MonitoringServiceImpl.java

@Override
public String getJsonFromCAdvisor(String containerId) {
    String result = "";
    try {//from   www.j  a v a2s.c  o m
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.0/containers/docker/" + containerId);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            result = EntityUtils.toString(response.getEntity());
            if (logger.isDebugEnabled()) {
                logger.debug(result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error(containerId, e);
    }
    return result;
}

From source file:fr.treeptik.cloudunit.service.impl.MonitoringServiceImpl.java

@Override
public String getJsonMachineFromCAdvisor() {
    String result = "";
    try {/* w w w .j  a  va2s  .c o  m*/
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(cAdvisorURL + "/api/v1.0/machine");
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            result = EntityUtils.toString(response.getEntity());
            if (logger.isDebugEnabled()) {
                logger.debug(result);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("" + e);
    }
    return result;
}

From source file:com.sampleapp.db.CloudantDAOFactory.java

@Override
public List<Influencer> getAll() {
    List<Influencer> influencers = new ArrayList<Influencer>();

    try {/*from ww w  .  java  2s. c o  m*/
        // Get id of all docs and then lookup each doc to get the details
        HttpGet get = new HttpGet(url + "/" + database + "/_all_docs");

        CloseableHttpResponse response = httpClient.execute(get);

        String result = EntityUtils.toString(response.getEntity());
        response.close();
        System.out.println(result);
        JSONObject obj = new JSONObject(result);

        JSONArray arr = obj.getJSONArray("rows");
        for (int i = 0; i < arr.length(); i++) {
            Influencer influencer = new Influencer();
            JSONObject record = new JSONObject(getRecordAsJson(arr.getJSONObject(i).getString("id")));
            influencer.setTwitterHandle(record.getString("_id"));
            influencer.setFcount(record.getInt("fcount"));
            influencer.setMcount(record.getInt("mcount"));
            influencer.setFscore(record.getInt("fscore"));
            influencer.setRtcount(record.getInt("rtcount"));
            influencer.setTotalscore(record.getInt("totalscore"));
            influencers.add(influencer);
        }

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

    return influencers;
}

From source file:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java

/**
 * Test deleting a project.// w  w w  . j  ava  2s.com
 * 
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 7, description = "Delete an exsisting project")
public void testDeleteProject() throws MLHttpClientException, IOException {
    int projectId = mlHttpclient.getProjectId(MLIntegrationTestConstants.PROJECT_NAME_DIABETES);
    CloseableHttpResponse response = mlHttpclient.doHttpDelete("/api/projects/" + projectId);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wuspba.ctams.ws.ITBandContestController.java

protected static void add() throws Exception {
    ITVenueController.add();//from  w  w  w. j  av  a 2s  .  c om
    ITJudgeController.add();
    ITHiredJudgeController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getBandContests().add(TestFixture.INSTANCE.bandContest);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITVenueController.PATH)
            .build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandContest.setId(doc.getBandContests().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITJudgeController.PATH)
            .build();

    httpPost = new HttpPost(uri);

    xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    httpPost = new HttpPost(uri);

    xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandContest.setId(doc.getBandContests().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:org.wso2.carbon.ml.analysis.test.FeatureProcessingTestCase.java

/**
 * /*from ww  w . j a  v a 2  s .  c  o  m*/
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 3, description = "Get all filtered features")
public void testGetFilteredFeatures() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/analyses/" + analysisId + "/filteredFeatures?featureType=CATEGORICAL");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:net.di2e.ddf.argo.probe.responder.ProbeHandler.java

/**
 * Sends the response using an HTTP POST
 *
 * @param endpoint//from   www . j  a  va2 s.  com
 *            URI of the service to send the POST to
 * @param responseStr
 *            Content for the response message
 * @param payloadType
 *            Encoding type of the response, should be either XML or JSON.
 */
private void sendResponse(String endpoint, String responseStr, String payloadType) {
    ContentType contentType = ContentType.TEXT_XML;
    if (Probe.JSON.equalsIgnoreCase(payloadType)) {
        contentType = ContentType.APPLICATION_JSON;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setEntity(new ByteArrayEntity(responseStr.getBytes(), contentType));

    try {
        CloseableHttpResponse response = httpClient.execute(httpPost);
        LOGGER.debug("Response sent.");
        response.close();
    } catch (Exception e) {
        LOGGER.warn("Could not send message to server at " + endpoint.toString(), e);
    }
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

/**
 * Get all pages from the server and construct a map in order to compare content
 * to detect changes or not.//from w  ww.j  a v  a2 s .c  om
 *
 */
private static void getPageMap(String host) {

    Map<String, Object> inputMap = new HashMap<String, Object>();
    inputMap.put("category", "page");
    inputMap.put("name", "getPageMap");
    inputMap.put("readOnly", true);

    CloseableHttpResponse response = null;
    try {
        HttpPost httpPost = new HttpPost(host + "/api/rs");
        httpPost.addHeader("Authorization", "Bearer " + jwt);
        StringEntity input = new StringEntity(
                ServiceLocator.getInstance().getMapper().writeValueAsString(inputMap));
        input.setContentType("application/json");
        httpPost.setEntity(input);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String json = "";
        String line = "";
        while ((line = rd.readLine()) != null) {
            json = json + line;
        }
        EntityUtils.consume(entity);
        System.out.println("Got page map from server");
        if (json != null && json.trim().length() > 0) {
            pageMap = ServiceLocator.getInstance().getMapper().readValue(json,
                    new TypeReference<HashMap<String, String>>() {
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.aurora.scheduler.events.WebhookTest.java

@Test
public void testTaskChangedWithOldState() throws Exception {
    CloseableHttpResponse httpResponse = createMock(CloseableHttpResponse.class);
    HttpEntity entity = createMock(HttpEntity.class);

    Capture<HttpPost> httpPostCapture = createCapture();
    expect(entity.isStreaming()).andReturn(false);
    expect(httpResponse.getEntity()).andReturn(entity);
    httpResponse.close();
    expectLastCall().once();//from   w w w  .  j  a  v a2s.  co  m
    expect(httpClient.execute(capture(httpPostCapture))).andReturn(httpResponse);

    control.replay();

    webhook.taskChangedState(changeWithOldState);

    assertTrue(httpPostCapture.hasCaptured());
    assertEquals(httpPostCapture.getValue().getURI(), new URI("http://localhost:5000/"));
    assertEquals(EntityUtils.toString(httpPostCapture.getValue().getEntity()), changeJson);
    Header[] producerTypeHeader = httpPostCapture.getValue().getHeaders("Producer-Type");
    assertEquals(producerTypeHeader.length, 1);
    assertEquals(producerTypeHeader[0].getName(), "Producer-Type");
    assertEquals(producerTypeHeader[0].getValue(), "reliable");
    Header[] contentTypeHeader = httpPostCapture.getValue().getHeaders("Content-Type");
    assertEquals(contentTypeHeader.length, 1);
    assertEquals(contentTypeHeader[0].getName(), "Content-Type");
    assertEquals(contentTypeHeader[0].getValue(), "application/vnd.kafka.json.v1+json");
    assertNotNull(httpPostCapture.getValue().getHeaders("Timestamp"));
}

From source file:cn.org.once.cstack.maven.plugin.utils.RestUtils.java

/**
 * sendGetCommand/*  w ww .  j av a 2 s .c  o  m*/
 * 
 * @param url
 * @param log
 * @return
 * @throws MojoExecutionException
 * @throws CheckException
 */
public Map<String, String> sendGetCommand(String url, Log log) throws CheckException {
    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);
    try {
        CloseableHttpResponse httpResponse = httpclient.execute(httpget, localContext);
        ResponseHandler<String> handler = new ResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put("body", body);
        httpResponse.close();

    } catch (Exception e) {
        log.warn("GET request failed!");

        throw new CheckException("Send GET to server failed!", e);
    }

    return response;
}