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:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testDSlackAlertRules() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient client = null;/* w w  w .java 2s  . com*/
    wireMockRule.addStubMapping(stubFor(post(urlEqualTo("/services")).willReturn(
            aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("na"))));
    client = Utils.buildClient("http://localhost:8080/commands/templates", 2000, 2000);
    HttpPut templateUpload = new HttpPut("http://localhost:8080/commands/templates");
    String template = AlertTemplateSerializer.serialize(new AlertTemplate((short) 7, "test_template",
            "http://localhost:54322/services@#general", "slack", "test", "test", 30, 1), false);
    templateUpload.addHeader("content-type", "application/json");
    templateUpload.setEntity(new StringEntity(new Gson().toJson(new TemplateCommand("all", false, template))));
    CloseableHttpResponse response = client.execute(templateUpload);
    response.close();
    assertTrue(
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);

    client = Utils.buildClient("http://localhost:8080/commands/rules", 2000, 2000);
    HttpPut ruleUpload = new HttpPut("http://localhost:8080/commands/rules");
    String rule = RuleSerializer.serializeRuleToJSONString(new SimpleRule((short) 9, "SimpleRule", true,
            new EqualsCondition("value", 4.0), new Action[] { new TemplatedAlertAction((short) 0, (short) 7) }),
            false);
    ruleUpload.addHeader("content-type", "application/json");
    ruleUpload.setEntity(new StringEntity(
            new Gson().toJson(new RuleCommand(StatelessRulesEngine.ALL_RULEGROUP, false, rule))));
    response = client.execute(ruleUpload);
    response.close();
    assertTrue(
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);

    client = Utils.buildClient("http://localhost:8080/events", 2000, 2000);
    Map<String, Object> eventHeaders = new HashMap<>();
    eventHeaders.put("value", 4);
    eventHeaders.put("@timestamp", "2014-04-23T13:40:29.000Z");
    eventHeaders.put(Constants.FIELD_EVENT_ID, 1103);

    HttpPost eventUpload = new HttpPost("http://localhost:8080/events");
    eventUpload.addHeader("content-type", "application/json");
    eventUpload.setEntity(new StringEntity(new Gson().toJson(eventHeaders)));
    response = client.execute(eventUpload);
    response.close();
    assertTrue(response.getStatusLine().getReasonPhrase(),
            response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300);
    Thread.sleep(1000);
    verify(1, postRequestedFor(urlEqualTo("/services")));
}

From source file:webrequester.CouchDBWebRequest.java

public String requestWithPut(String content) {
    String s = "";
    try {/*from   w  w  w.ja  v a 2s  .  com*/

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(buildURI().toString());

        StringEntity se = new StringEntity(content);
        httpput.setEntity(se);

        CloseableHttpResponse response = httpclient.execute(httpput);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                s = EntityUtils.toString(entity, "UTF-8");
            }
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        return null;
    }
    return s;
}

From source file:com.github.getmapgen.model.SenderRequest.java

/**
 * Send getmap request/*from w  ww. j  ava  2 s.  co m*/
 *
 * @param url string representation of URL
 * @return message about successful \ unsuccessful request
 */
public String send(final String url) {
    HttpGet request = null;
    CloseableHttpResponse response = null;
    String msg = null;
    try {
        request = new HttpGet(url);
        response = client.execute(request);
        msg = String.format("REQUEST %1s IS SEND. RESPONSE: %2s.", url, response.getStatusLine().toString());
        response.close();
    } catch (IOException e) {
        msg = String.format("REQUEST %1s FAILED", url);
        log.error(msg, e);
    }
    return msg;
}

From source file:httpServerClient.app.QuickStart.java

public static void getAllMessages(String[] args) throws Exception {
    // arguments to run Quick start:
    // args[0] GET
    // args[1] IPAddress of server
    // args[2] port No.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    JacksonObjectMapperToList myList = new JacksonObjectMapperToList();

    try {// ww  w.ja va 2s .  c  om
        HttpGet httpGet = new HttpGet("http://" + args[1] + ":" + args[2] + "/getAllMessages");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            String result = EntityUtils.toString(entity1);

            /*
             * Vypisanie odpovede do konzoly a discard dat zo serveru.
             */
            //myList.jsonToList(result);
            myList.jacksonToList(result);
            myList.PrintList();
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

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

/**
 * Test retrieving all analyzes from project API.
 * //from   ww w.  j a  v a2  s.c o  m
 * @throws MLHttpClientException
 * @throws IOException
 */
@Test(description = "Get all analyses")
public void testGetAllAnalyzesFromProject() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/projects/analyses");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.wso2.carbon.ml.configs.test.ConfigurationAPITestCase.java

/**
 * Test retrieving configs of all algorithms.
 * /*w  w w . j a va2  s  . com*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Get all algorithms")
public void testGetAllAlgorithmsConfig() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.doHttpGet("/api/configs/algorithms");
    assertEquals("Unexpected response received", Response.Status.OK.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

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

/**
 * Test creating an analysis without a project ID.
 * /*from  w  w  w .j av a2 s  . c o  m*/
 * @throws MLHttpClientException 
 * @throws IOException 
 */
@Test(description = "Create an analysis without a ProjectId")
public void testCreateAnalysisWithoutProjectID() throws MLHttpClientException, IOException {
    CloseableHttpResponse response = mlHttpclient.createAnalysis("TestAnalysisForAnalysis", -1);
    assertEquals("Unexpected response received", Response.Status.BAD_REQUEST.getStatusCode(),
            response.getStatusLine().getStatusCode());
    response.close();
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void notAuthorized() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {// w  w w.  ja va2s . co m
            add(new BasicNameValuePair("username", "userB"));
            add(new BasicNameValuePair("password", "secret"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(200, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }

    // then we can just call the hello servlet
    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {
        assertEquals(403, resp.getStatusLine().getStatusCode());

    } finally {
        resp.close();
    }
}

From source file:org.superbiz.CdiEventRealmTest.java

@Test
public void success() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    // first authenticate with the login servlet
    final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login");
    final List<NameValuePair> data = new ArrayList<NameValuePair>() {
        {//from   www  .  j a v a2 s.  c  o m
            add(new BasicNameValuePair("username", "userA"));
            add(new BasicNameValuePair("password", "secret"));
        }
    };
    httpPost.setEntity(new UrlEncodedFormEntity(data));
    final CloseableHttpResponse respLogin = client.execute(httpPost);
    try {
        assertEquals(200, respLogin.getStatusLine().getStatusCode());

    } finally {
        respLogin.close();
    }

    // then we can just call the hello servlet
    final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello");
    final CloseableHttpResponse resp = client.execute(httpGet);
    try {
        assertEquals(200, resp.getStatusLine().getStatusCode());
        System.out.println(EntityUtils.toString(resp.getEntity()));

    } finally {
        resp.close();
    }
}