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:org.wso2.carbon.ml.project.test.MLProjectsTestCase.java

/**
 * Test retrieving a project.//w w w .j  a  v  a  2s .c o  m
 * 
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 6, description = "Retrieve a project")
public void testGetProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/projects/" + MLIntegrationTestConstants.PROJECT_NAME_DIABETES);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.incode.module.commchannel.dom.api.GeocodingService.java

@Programmatic
public GeocodedAddress lookup(final String address) {

    if (demo) {//from w  w w.  java 2 s  . c o m
        return demoResponse();
    }

    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout * 1000)
            .setConnectTimeout(timeout * 1000).build();

    final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .useSystemProperties().build();

    try {
        final String uri = buildUri(address);
        final HttpGet httpGet = new HttpGet(uri);
        final CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            HttpEntity entity = response.getEntity();
            final String json = EntityUtils.toString(entity, "UTF-8");

            return asGeocodedAddress(json);
        } finally {
            response.close();
        }
    } catch (Exception ex) {
        return null;
    }
}

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

protected static void add() throws Exception {
    ITVenueController.add();//from  w w  w . j  a  v  a2  s.  co  m
    ITHiredJudgeController.add();
    ITJudgeController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getPeople().add(TestFixture.INSTANCE.andy);
    doc.getPeople().add(TestFixture.INSTANCE.jamie);
    doc.getPeople().add(TestFixture.INSTANCE.bob);
    doc.getPeople().add(TestFixture.INSTANCE.eoin);
    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.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin);
    doc.getSoloContests().add(TestFixture.INSTANCE.soloContest);

    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.soloContest.setId(doc.getSoloContests().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.soloContest.setId(doc.getSoloContests().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:com.redhat.red.build.koji.HttpClientUtilsTest.java

/**
 * The test mocks available CloseableHttpResponse, and verfiy InputStream close() method will never be met when
 * CloseableHttpResponse close() method called.
 */// w  w  w .j  a va2s  .c o  m
@Test
public void testResponseClose() throws Exception {
    final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class);
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    final InputStream inputStream = Mockito.mock(InputStream.class);

    Mockito.when(response.getEntity()).thenReturn(entity);
    Mockito.when(entity.isStreaming()).thenReturn(Boolean.TRUE);
    Mockito.when(entity.getContent()).thenReturn(inputStream);

    response.close();
    Mockito.verify(inputStream, never()).close();
    Mockito.verify(response).close();
}

From source file:fi.vm.kapa.identification.proxy.metadata.MetadataClient.java

List<MetadataDTO> getMetadataDTOs(CloseableHttpClient httpClient, HttpGet getMethod) throws IOException {
    List<MetadataDTO> serviceProviders = new ArrayList<>();
    CloseableHttpResponse response = httpClient.execute(getMethod);

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        Gson gson = new Gson();
        serviceProviders = gson.fromJson(EntityUtils.toString(response.getEntity()),
                new TypeToken<List<MetadataDTO>>() {
                }.getType());//w  w  w.j  ava  2  s.co m
        response.close();
    } else {
        logger.warn("Metadata server responded with HTTP {}", statusCode);
        response.close();
    }
    return serviceProviders;
}

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

/**
 * @throws MLHttpClientException/*from  w  ww  . ja  v  a  2s. c o m*/
 * @throws IOException
 */
@Test(priority = 2, description = "Get response variable of the analyses")
public void testGetResponseVariable() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/analyses/" + analysisId + "/responseVariables");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

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

/**
 * @throws MLHttpClientException//  ww w .j av a 2  s . c  o m
 * @throws IOException
 */
@Test(priority = 2, description = "Get train data fraction of the analyses")
public void testGetTrainDataFractionType() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient
            .doHttpGet("/api/analyses/" + analysisId + "/trainDataFraction");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.dataset.test.CreateDatasetTestCase.java

/**
 * Test creating a dataset from a valid DAS table.
 * // w  ww. j  a  va2 s.  c  o m
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Create a dataset from a DAS table", dependsOnMethods = "testCreateDatasetFromFile")
public void testCreateDatasetFromDAS() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.uploadDatasetFromDAS(
            MLIntegrationTestConstants.DATASET_NAME_DAS, "1.0", MLIntegrationTestConstants.DAS_DATASET_SAMPLE);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

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

/**
 * Test setting customized hyper-parameters of an analysis.
 * //w ww .j  av  a2s  .  c  om
 * @throws IOException
 * @throws MLHttpClientException
 */
@Test(priority = 3, description = "Set customized hyperparameters", dependsOnMethods = "testSetDefaultHyperparameters")
public void testSetCustomizedHyperParameters() throws IOException, MLHttpClientException {
    String payload = "[{\"key\" :\"Learning_Rate\",\"value\" : \"0.1\"},{\"key\":\"Iterations\",\"value\":\"100\"}]";
    CloseableHttpResponse response = mlHttpclient.doHttpPost("/api/analyses/" + analysisId + "/hyperParams",
            payload);
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:com.oltpbenchmark.util.ResultUploader.java

public void uploadResult(List<TransactionType> activeTXTypes) throws ParseException {
    try {// w  ww  .jav  a 2s .co m
        File expConfigFile = File.createTempFile("expconfig", ".tmp");
        File samplesFile = File.createTempFile("samples", ".tmp");
        File summaryFile = File.createTempFile("summary", ".tmp");
        File paramsFile = File.createTempFile("params", ".tmp");
        File metricsFile = File.createTempFile("metrics", ".tmp");
        File csvDataFile = File.createTempFile("csv", ".gz");

        PrintStream confOut = new PrintStream(new FileOutputStream(expConfigFile));
        writeBenchmarkConf(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(paramsFile));
        writeDBParameters(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(metricsFile));
        writeDBMetrics(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(samplesFile));
        results.writeCSV2(confOut);
        confOut.close();

        confOut = new PrintStream(new FileOutputStream(summaryFile));
        writeSummary(confOut);
        confOut.close();

        confOut = new PrintStream(new GZIPOutputStream(new FileOutputStream(csvDataFile)));
        results.writeAllCSVAbsoluteTiming(activeTXTypes, confOut);
        confOut.close();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(uploadUrl);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addTextBody("upload_code", uploadCode)
                .addPart("sample_data", new FileBody(samplesFile))
                .addPart("raw_data", new FileBody(csvDataFile))
                .addPart("db_parameters_data", new FileBody(paramsFile))
                .addPart("db_metrics_data", new FileBody(metricsFile))
                .addPart("benchmark_conf_data", new FileBody(expConfigFile))
                .addPart("summary_data", new FileBody(summaryFile)).build();

        httppost.setEntity(reqEntity);

        LOG.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity resEntity = response.getEntity();
            LOG.info(IOUtils.toString(resEntity.getContent()));
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (ConfigurationException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}