List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly
public static void closeQuietly(final HttpClient httpClient)
From source file:com.seyren.core.service.notification.VictorOpsNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String victorOpsRestEndpoint = seyrenConfig.getVictorOpsRestEndpoint(); String victorOpsRoutingKey = StringUtils.defaultIfEmpty(subscription.getTarget(), "default"); if (victorOpsRestEndpoint == null) { LOGGER.warn("VictorOps REST API endpoint needs to be set before sending notifications"); return;/* w ww .j a v a 2 s . c o m*/ } URI victorOpsUri = null; try { victorOpsUri = new URI(victorOpsRestEndpoint).resolve(new URI(victorOpsRoutingKey)); } catch (URISyntaxException use) { LOGGER.warn("Invalid endpoint is given."); return; } HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost post = new HttpPost(victorOpsUri); try { HttpEntity entity = new StringEntity(getDescription(check, alerts), 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 VictorOps", e); } finally { post.releaseConnection(); HttpClientUtils.closeQuietly(client); } }
From source file:com.seyren.core.service.notification.FlowdockNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String token = subscription.getTarget(); String externalUsername = seyrenConfig.getFlowdockExternalUsername(); List<String> tags = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getFlowdockTags())); List<String> emojis = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getFlowdockEmojis())); String url = String.format("%s/v1/messages/chat/%s", baseUrl, token); HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost post = new HttpPost(url); post.addHeader("Content-Type", "application/json"); post.addHeader("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> dataToSend = new HashMap<String, Object>(); dataToSend.put("content", formatContent(emojis, check, subscription, alerts)); dataToSend.put("external_user_name", externalUsername); dataToSend.put("tags", formatTags(tags, check, subscription, alerts)); try {/*from w w w. j av a 2 s . co m*/ String data = StringEscapeUtils.unescapeJava(mapper.writeValueAsString(dataToSend)); post.setEntity(new StringEntity(data, APPLICATION_JSON)); client.execute(post); } catch (Exception e) { LOGGER.warn("Error posting to Flowdock", e); } finally { post.releaseConnection(); HttpClientUtils.closeQuietly(client); } }
From source file:org.jboss.as.test.clustering.cluster.web.ReplicationForNegotiationAuthenticatorTestCase.java
@Test public void testOneRequestSimpleFailover( @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException { DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient(); String url1 = baseURL1.toString() + "simple"; String url2 = baseURL2.toString() + "simple"; try {//w w w. j ava 2 s. com 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); } // Now check on the 2nd server 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.", 2, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } //and back on the 1st server 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.", 3, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } } finally { HttpClientUtils.closeQuietly(client); } }
From source file:com.jive.myco.seyren.core.service.notification.FlowdockNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String token = subscription.getTarget(); String externalUsername = seyrenConfig.getFlowdockExternalUsername(); List<String> tags = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getFlowdockTags())); List<String> emojis = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getFlowdockEmojis())); String url = String.format("%s/v1/messages/chat/%s", baseUrl, token); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.addHeader("Content-Type", "application/json"); post.addHeader("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); Map<String, Object> dataToSend = new HashMap<String, Object>(); dataToSend.put("content", formatContent(emojis, check, subscription, alerts)); dataToSend.put("external_user_name", externalUsername); dataToSend.put("tags", formatTags(tags, check, subscription, alerts)); try {/*from www . j a v a 2s . co m*/ String data = StringEscapeUtils.unescapeJava(mapper.writeValueAsString(dataToSend)); post.setEntity(new StringEntity(data, APPLICATION_JSON)); client.execute(post); } catch (Exception e) { LOGGER.warn("Error posting to Flowdock", e); } finally { post.releaseConnection(); HttpClientUtils.closeQuietly(client); } }
From source file:com.jive.myco.seyren.core.service.notification.SlackNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String token = seyrenConfig.getSlackToken(); String channel = subscription.getTarget(); String username = seyrenConfig.getSlackUsername(); String iconUrl = seyrenConfig.getSlackIconUrl(); List<String> emojis = Lists.newArrayList( Splitter.on(',').omitEmptyStrings().trimResults().split(seyrenConfig.getSlackEmojis())); String url = String.format("%s/api/chat.postMessage", baseUrl); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.addHeader("accept", "application/json"); List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("token", token)); parameters.add(new BasicNameValuePair("channel", channel)); parameters.add(new BasicNameValuePair("text", formatContent(emojis, check, subscription, alerts))); parameters.add(new BasicNameValuePair("username", username)); parameters.add(new BasicNameValuePair("icon_url", iconUrl)); try {// w w w . j ava2 s . co m post.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response = client.execute(post); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Status: {}, Body: {}", response.getStatusLine(), new BasicResponseHandler().handleResponse(response)); } } catch (Exception e) { LOGGER.warn("Error posting to Slack", e); } finally { post.releaseConnection(); HttpClientUtils.closeQuietly(client); } }
From source file:org.jboss.as.test.clustering.cluster.web.async.AsyncServletTestCase.java
@Test public void test(@ArquillianResource(AsyncServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(AsyncServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { URI uri1 = AsyncServlet.createURI(baseURL1); URI uri2 = AsyncServlet.createURI(baseURL2); HttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient(); try {/*from w w w. ja va 2s .c om*/ assertValue(client, uri1, 1); assertValue(client, uri1, 2); assertValue(client, uri2, 3); assertValue(client, uri2, 4); assertValue(client, uri1, 5); assertValue(client, uri1, 6); } finally { HttpClientUtils.closeQuietly(client); } }
From source file:com.google.gct.stats.GoogleUsageTracker.java
private static void sendPing(@NotNull final List<? extends NameValuePair> postData) { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(ANALYTICS_URL); try { request.setEntity(new UrlEncodedFormEntity(postData)); CloseableHttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300) { LOG.debug("Non 200 status code : " + status.getStatusCode() + " - " + status.getReasonPhrase()); }/* w w w . j av a 2 s . c o m*/ } catch (IOException ex) { LOG.debug("IOException during Analytics Ping", new Object[] { ex.getMessage() }); } finally { HttpClientUtils.closeQuietly(client); } } }); }
From source file:org.jboss.additional.testsuite.jdkall.present.clustering.cluster.web.ExternalizerTestCase.java
private static void assertValue(HttpClient client, URI uri, int value) throws IOException { HttpResponse response = client.execute(new HttpGet(uri)); try {/*from w w w . j av a 2s . c o m*/ Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(value, Integer.parseInt(response.getFirstHeader(CounterServlet.COUNT_HEADER).getValue())); } finally { HttpClientUtils.closeQuietly(response); } }
From source file:com.seyren.core.service.notification.TwilioNotificationService.java
@Override public void sendNotification(Check check, Subscription subscription, List<Alert> alerts) throws NotificationFailedException { String twilioUrl = StringUtils.trimToNull(seyrenConfig.getTwilioUrl()); if (twilioUrl == null) { LOGGER.warn("Twilio URL needs to be set before sending notifications to Twilio"); return;/*from w w w. ja v a 2 s . co m*/ } String body; if (check.getState() == AlertType.ERROR) { body = "ERROR Check " + check.getName() + " has exceeded its threshold."; } else if (check.getState() == AlertType.OK) { body = "OK Check " + check.getName() + " has been resolved."; } else if (check.getState() == AlertType.WARN) { body = "WARN Check " + check.getName() + " has exceeded its threshold."; } else { LOGGER.warn("Did not send notification to Twilio for check in state: {}", check.getState()); body = null; } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("To", subscription.getTarget())); params.add(new BasicNameValuePair("From", seyrenConfig.getTwilioPhoneNumber())); params.add(new BasicNameValuePair("Body", body)); HttpClient client = HttpClientBuilder.create().useSystemProperties().build(); HttpPost post = new HttpPost(twilioUrl + "/" + seyrenConfig.getTwilioAccountSid() + "/Messages"); try { String credentials = seyrenConfig.getTwilioAccountSid() + ":" + seyrenConfig.getTwilioAuthToken(); post.setHeader(new BasicHeader("Authorization", "Basic " + Base64.encodeBase64String(credentials.getBytes("UTF-8")))); HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(entity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() / 100 != 2) throw new IOException("API request failed: " + response.getStatusLine()); } catch (IOException e) { throw new NotificationFailedException("Sending notification to Twilio at " + twilioUrl + " failed.", e); } finally { HttpClientUtils.closeQuietly(client); } }