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.dataset.test.GetDatasetsTestCase.java

/**
 * Test retrieving all the available value-sets of a dataset.
 * @throws MLHttpClientException /*  w  w w .ja va2s  . com*/
 * @throws IOException 
 */
@Test(description = "Get dataset version with a non-existing ID")
public void testGetVersionSetWithInvalidId() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/datasets/versions/" + 999);
    assertEquals("Unexpected response received", Response.Status.NOT_FOUND.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.apache.solr.prometheus.exporter.SolrExporterTest.java

@Test
public void testExecute() throws Exception {
    // solr client
    CloudSolrClient cloudSolrClient = cluster.getSolrClient();

    int port;//  www .  ja v a 2s  .  c om
    ServerSocket socket = null;
    try {
        socket = new ServerSocket(0);
        port = socket.getLocalPort();
    } finally {
        socket.close();
    }

    // index sample docs
    File exampleDocsDir = new File(getFile("exampledocs").getAbsolutePath());
    List<File> xmlFiles = Arrays.asList(exampleDocsDir.listFiles((dir, name) -> name.endsWith(".xml")));
    for (File xml : xmlFiles) {
        ContentStreamUpdateRequest req = new ContentStreamUpdateRequest("/update");
        req.addFile(xml, "application/xml");
        cloudSolrClient.request(req, "collection1");
    }
    cloudSolrClient.commit("collection1");

    // start exporter
    SolrExporter solrExporter = new SolrExporter(port, cloudSolrClient,
            getFile("conf/solr-exporter-config.xml").toPath(), 1);
    try {
        solrExporter.start();

        URI uri = new URI("http://localhost:" + String.valueOf(port) + "/metrics");

        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            HttpGet request = new HttpGet(uri);
            response = httpclient.execute(request);

            int expectedHTTPStatusCode = HttpStatus.SC_OK;
            int actualHTTPStatusCode = response.getStatusLine().getStatusCode();
            assertEquals(expectedHTTPStatusCode, actualHTTPStatusCode);
        } finally {
            response.close();
            httpclient.close();
        }
    } finally {
        solrExporter.stop();
    }
}

From source file:net.fischboeck.discogs.BaseOperations.java

CloseableHttpResponse doHttpRequest(HttpUriRequest request) throws EntityNotFoundException, ClientException {

    CloseableHttpResponse response = null;
    request = this.authorizationStrategy.authorize(request);

    try {//from   w w w . j  a  v  a2 s.  c  o m
        response = this.httpClient.execute(request);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            response.close();
            throw new EntityNotFoundException("API returned 404 on request GET " + request.getURI());
        }

        return response;
    } catch (EntityNotFoundException enfEx) {
        throw enfEx;
    } catch (Exception ex) {
        throw new ClientException(ex.getMessage());
    }
}

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

/**
 * Test creating a project with a duplicate project name.
 * // w  w  w .ja va  2 s. co  m
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(priority = 2, description = "Create a project with duplicate Name")
public void testCreateProjectWithDuplicateName() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createProject(
            MLIntegrationTestConstants.PROJECT_NAME_DIABETES, MLIntegrationTestConstants.DATASET_NAME_DIABETES);
    assertEquals("Unexpected response received", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.ambraproject.wombat.service.remote.AbstractRemoteService.java

/**
 * Get a response and open the response entity.
 *
 * @param target the request to send/*from   ww  w. j  a va  2  s  . c o m*/
 * @return the response entity
 * @throws IOException      on making the request
 * @throws RuntimeException if a response is received but it has no response entity object
 * @see org.apache.http.HttpResponse#getEntity()
 */
private HttpEntity requestEntity(HttpUriRequest target) throws IOException {
    Preconditions.checkNotNull(target);

    // We must leave the response open if we return a valid stream, but must close it otherwise.
    boolean returningResponse = false;
    CloseableHttpResponse response = null;
    try {
        response = getResponse(target);
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new RuntimeException("No response");
        }
        returningResponse = true;
        return entity;
    } finally {
        if (!returningResponse && response != null) {
            response.close();
        }
    }
}

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

/**
 * Test Creating a new version of an existing dataset
 * //from   www  . j a v  a 2  s.  c  o  m
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Create a duplicate version of an existing dataset", dependsOnMethods = "testCreateNewDatasetVersion")
public void testCreateDuplicateDatasetVersion() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.uploadDatasetFromCSV(
            MLIntegrationTestConstants.DATASET_NAME_DIABETES, "2.0",
            MLIntegrationTestConstants.DIABETES_DATASET_SAMPLE);
    assertEquals("Unexpected response received", Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:cn.org.once.cstack.cli.rest.RestUtils.java

/**
 * sendGetCommand/* w ww  .j a  v  a2  s. c o m*/
 *
 * @param url
 * @param parameters
 * @return
 */
public Map<String, String> sendGetCommand(String url, Map<String, Object> parameters)
        throws ManagerResponseException {
    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 CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put(BODY, body);
        httpResponse.close();

    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:cn.org.once.cstack.cli.rest.RestUtils.java

/**
 * sendPostCommand/*www  . j  a  v a  2 s  .c o  m*/
 *
 * @param url
 * @param credentials
 * @param entity
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPostCommand(String url, Map<String, Object> credentials, String entity)
        throws ManagerResponseException {
    Map<String, Object> response = new HashMap<String, Object>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(entity);
        httpPost.setEntity(stringEntity);
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put(BODY, body);
        httpResponse.close();
    } catch (Exception e) {
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}

From source file:uk.org.openeyes.oink.itest.adapters.ITFacadeToHl7v2.java

@Test
public void testPatientQueryIsPossibleUsingMockedHl7Server() throws Exception {

    Thread.sleep(45000);/*  ww w.j a  v  a 2  s.  c o m*/

    // Mock an HL7 Server
    Hl7Server hl7Server = new Hl7Server(Integer.parseInt(hl7Props.getProperty("remote.port")), false);

    final Message searchResults = Hl7Helper.loadHl7Message("/example-messages/hl7v2/ADR-A19-mod.txt");
    hl7Server.setMessageHandler("QRY", "A19", new ReceivingApplication() {

        @Override
        public Message processMessage(Message in, Map<String, Object> metadata)
                throws ReceivingApplicationException, HL7Exception {
            // Always return search results
            log.debug("Returning search results");
            return searchResults;
        }

        @Override
        public boolean canProcess(Message message) {
            return true;
        }
    });

    hl7Server.start();

    // Make a Patient Query
    URIBuilder builder = new URIBuilder(facadeProps.getProperty("facade.uri") + "/Patient");
    builder.addParameter("identifier", "NHS|123456");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(builder.build());
    httpGet.addHeader("Accept", "application/json+fhir; charset=UTF-8");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);

    // Check results
    assertEquals(200, response1.getStatusLine().getStatusCode());
    String json = null;
    try {
        HttpEntity entity1 = response1.getEntity();
        json = EntityUtils.toString(entity1);
    } finally {
        response1.close();
        hl7Server.stop();
    }

    assertNotNull(json);

    BundleParser conv = new BundleParser();
    AtomFeed response = conv.fromJsonOrXml(json);

    assertNotEquals(0, response.getEntryList().size());
}

From source file:cn.org.once.cstack.cli.rest.RestUtils.java

public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

    Map<String, String> response = new HashMap<String, String>();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
    nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
    localContext = HttpClientContext.create();
    localContext.setCookieStore(new BasicCookieStore());
    HttpPost httpPost = new HttpPost(url);
    try {//from w w  w  . j av  a2 s .c o m
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
        ResponseHandler<String> handler = new CustomResponseErrorHandler();
        String body = handler.handleResponse(httpResponse);
        response.put(BODY, body);
        httpResponse.close();
    } catch (Exception e) {
        authentificationUtils.getMap().clear();
        throw new ManagerResponseException(e.getMessage(), e);
    }

    return response;
}