Example usage for org.apache.http.client.utils HttpClientUtils closeQuietly

List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.http.client.utils HttpClientUtils closeQuietly.

Prototype

public static void closeQuietly(final HttpClient httpClient) 

Source Link

Document

Unconditionally close a httpClient.

Usage

From source file:com.jive.myco.seyren.core.service.notification.HttpNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;//from   ww w. ja v  a 2  s .  c  o  m
    }
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("preview", getPreviewImage(check));

    HttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost(subscription.getTarget());
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.async.AsyncServletTestCase.java

private static void assertValue(HttpClient client, URI uri, int value) throws IOException {
    HttpResponse response = client.execute(new HttpGet(uri));
    try {//from ww w  .  j a va2s.co  m
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(value,
                Integer.parseInt(response.getFirstHeader(SimpleServlet.VALUE_HEADER).getValue()));
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

@Override
public void close() {
    try {//from   ww  w .  j  ava2  s . c o  m
        HttpClientUtils.closeQuietly(client);
        onClose.close();
    } catch (IOException t) {
        LOG.error("Failed to close client", t);
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.passivation.SessionPassivationTestCase.java

@Test
@InSequence(1)/*  w ww  .ja v  a2s.  co  m*/
public void test(
        @ArquillianResource(SessionOperationServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1)
        throws IOException, URISyntaxException {
    DefaultHttpClient client1 = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();
    DefaultHttpClient client2 = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();
    String session1 = null;
    String session2 = null;
    try {
        // This should not trigger any passivation/activation events
        HttpResponse response = client1
                .execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "1")));
        try {
            Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
            Assert.assertFalse(response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS));
            session1 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        long now = System.currentTimeMillis();
        long start = now;
        boolean passivated = false;

        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            // This will trigger passivation of session1
            response = client2.execute(new HttpGet(SessionOperationServlet.createSetURI(baseURL1, "a", "2")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.SESSION_ID);
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
                session2 = response.getFirstHeader(SessionOperationServlet.SESSION_ID).getValue();
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session1,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());

        now = System.currentTimeMillis();
        start = now;
        passivated = false;

        // This should trigger activation of session1 and passivation of session2
        response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
        try {
            checkResponseForHeader(response, SessionOperationServlet.RESULT);
            Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
            checkResponseForHeader(response, SessionOperationServlet.ACTIVATED_SESSIONS);
            passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            Assert.assertEquals(session1,
                    response.getFirstHeader(SessionOperationServlet.ACTIVATED_SESSIONS).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Verify session2 was passivated
        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            response = client1.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.RESULT);
                Assert.assertEquals("1", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session2,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());

        now = System.currentTimeMillis();
        start = now;
        passivated = false;

        // This should trigger activation of session2 and passivation of session1
        response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
        try {
            checkResponseForHeader(response, SessionOperationServlet.RESULT);
            Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
            checkResponseForHeader(response, SessionOperationServlet.ACTIVATED_SESSIONS);
            passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            Assert.assertEquals(session2,
                    response.getFirstHeader(SessionOperationServlet.ACTIVATED_SESSIONS).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Verify session1 was passivated
        while (!passivated && ((now - start) < MAX_PASSIVATION_WAIT)) {
            response = client2.execute(new HttpGet(SessionOperationServlet.createGetURI(baseURL1, "a")));
            try {
                checkResponseForHeader(response, SessionOperationServlet.RESULT);
                Assert.assertEquals("2", response.getFirstHeader(SessionOperationServlet.RESULT).getValue());
                Assert.assertFalse(response.containsHeader(SessionOperationServlet.ACTIVATED_SESSIONS));
                passivated = response.containsHeader(SessionOperationServlet.PASSIVATED_SESSIONS);
            } finally {
                HttpClientUtils.closeQuietly(response);
            }
            Thread.yield();
            now = System.currentTimeMillis();
        }

        Assert.assertTrue(passivated);
        Assert.assertEquals(session1,
                response.getFirstHeader(SessionOperationServlet.PASSIVATED_SESSIONS).getValue());
    } finally {
        HttpClientUtils.closeQuietly(client1);
        HttpClientUtils.closeQuietly(client2);
    }
}

From source file:com.seyren.core.service.notification.HttpNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;/*from  w ww . j av a 2  s  . c  o  m*/
    }
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("preview", getPreviewImage(check));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post;

    if (StringUtils.isNotBlank(seyrenConfig.getHttpNotificationUrl())) {
        post = new HttpPost(seyrenConfig.getHttpNotificationUrl());
    } else {
        post = new HttpPost(subscription.getTarget());
    }

    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.seyren.core.service.notification.PushoverNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String pushoverAppApiToken = StringUtils.trimToNull(seyrenConfig.getPushoverAppApiToken());
    String pushoverUserKey = StringUtils.trimToNull(subscription.getTarget());
    String pushoverMsgTitle = formatMsgTitle(check);
    String pushoverMsgBody = "Check details : " + seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId();
    String pushoverMsgPriority = getMsgPriority(check);

    if (pushoverAppApiToken == null) {
        LOGGER.warn("Pushover App API Token must be provided");
        return;//from w w  w  .j av  a 2  s. c  om
    }

    if (pushoverUserKey == null || pushoverUserKey.length() != 30) {
        LOGGER.warn("Invalid or missing Pushover user key");
        return;
    }

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    HttpPost post = new HttpPost("https://api.pushover.net/1/messages.json");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("token", pushoverAppApiToken));
        nameValuePairs.add(new BasicNameValuePair("user", pushoverUserKey));
        nameValuePairs.add(new BasicNameValuePair("title", pushoverMsgTitle));
        nameValuePairs.add(new BasicNameValuePair("message", pushoverMsgBody));
        nameValuePairs.add(new BasicNameValuePair("priority", pushoverMsgPriority));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Pushover failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.quickstarts.wfk.travelagent.flight.FlightService.java

JSONObject findById(Long id) {

    try {/*from   ww  w.ja va 2  s.c om*/
        URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
                .setPath("/rest/flights/id/" + id.toString())
                //.setParameter("id", id.toString())
                .build();
        HttpGet req = new HttpGet(uri);
        CloseableHttpResponse response = httpClient.execute(req);
        String responseBody = EntityUtils.toString(response.getEntity());
        JSONObject responseJson = new JSONObject(responseBody);

        HttpClientUtils.closeQuietly(response);
        return responseJson;
    } catch (Exception e) {
        log.info(e.toString());
        return null;
    }

}

From source file:com.jive.myco.seyren.core.service.notification.PushoverNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String pushoverAppApiToken = StringUtils.trimToNull(seyrenConfig.getPushoverAppApiToken());
    String pushoverUserKey = StringUtils.trimToNull(subscription.getTarget());
    String pushoverMsgTitle = formatMsgTitle(check);
    String pushoverMsgBody = "Check details : " + seyrenConfig.getBaseUrl() + "/#/checks/" + check.getId();
    String pushoverMsgPriority = getMsgPriority(check);

    if (pushoverAppApiToken == null) {
        LOGGER.warn("Pushover App API Token must be provided");
        return;/*  w w w.  jav a2  s.c o m*/
    }

    if (pushoverUserKey == null || pushoverUserKey.length() != 30) {
        LOGGER.warn("Invalid or missing Pushover user key");
        return;
    }

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("https://api.pushover.net/1/messages.json");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("token", pushoverAppApiToken));
        nameValuePairs.add(new BasicNameValuePair("user", pushoverUserKey));
        nameValuePairs.add(new BasicNameValuePair("title", pushoverMsgTitle));
        nameValuePairs.add(new BasicNameValuePair("message", pushoverMsgBody));
        nameValuePairs.add(new BasicNameValuePair("priority", pushoverMsgPriority));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Pushover failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebFailoverAbstractCase.java

/**
 * Test simple graceful shutdown failover:
 * <p/>/*  www  .j av a  2s  .  c o m*/
 * 1/ Start 2 containers and deploy <distributable/> webapp.
 * 2/ Query first container creating a web session.
 * 3/ Shutdown first container.
 * 4/ Query second container verifying sessions got replicated.
 * 5/ Bring up the first container.
 * 6/ Query first container verifying that updated sessions replicated back.
 *
 * @throws IOException
 * @throws InterruptedException
 * @throws URISyntaxException
 */
@Test
public void testGracefulSimpleFailover(
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "simple";
    String url2 = baseURL2.toString() + "simple";

    try {
        HttpResponse response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Gracefully shutdown the 1st container.
        stop(CONTAINER_1);

        // Now check on the 2nd server

        // Note that this DOES rely on the fact that both servers are running on the "same" domain,
        // which is '127.0.0.0'. Otherwise you will have to spoof cookies. @Rado

        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was shutdown.", 3,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do one more check.
        response = client.execute(new HttpGet(url2));
        try {
            log.info("Requested " + url2 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        start(CONTAINER_1);

        // Lets wait for the cluster to update membership and tranfer state.

        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals("Session failed to replicate after container 1 was brough up.", 5,
                    Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Let's do this twice to have more debug info if failover is slow.
        response = client.execute(new HttpGet(url1));
        try {
            log.info("Requested " + url1 + ", got " + response.getFirstHeader("value").getValue() + ".");
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(6, Integer.parseInt(response.getFirstHeader("value").getValue()));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}