WebhookCallback implements AlarmCallback { @Override public void doAlarm(List<AlarmMessage> alarmMessage) { if (alarmRulesWatcher.getWebHooks().isEmpty()) { return; } CloseableHttpClient httpClient = HttpClients.custom().build(); try { alarmRulesWatcher.getWebHooks().forEach(url -> { HttpPost post = new HttpPost(url); post.setConfig(requestConfig); post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString()); StringEntity entity; try { entity = new StringEntity(gson.toJson(alarmMessage), StandardCharsets.UTF_8); post.setEntity(entity); CloseableHttpResponse httpResponse = httpClient.execute(post); StatusLine statusLine = httpResponse.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) { log.error("send alarm to " + url + " failure. Response code: " + statusLine.getStatusCode()); } } catch (UnsupportedEncodingException e) { log.error("Alarm to JSON error, " + e.getMessage(), e); } catch (IOException e) { log.error("send alarm to " + url + " failure.", e); } }); } finally { try { httpClient.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } WebhookCallback(AlarmRulesWatcher alarmRulesWatcher); @Override void doAlarm(List<AlarmMessage> alarmMessage);  }
@Test public void testWebhook() { List<String> remoteEndpoints = new ArrayList<>(); remoteEndpoints.add("http: Rules rules = new Rules(); rules.setWebhooks(remoteEndpoints); AlarmRulesWatcher alarmRulesWatcher = new AlarmRulesWatcher(rules, null); WebhookCallback webhookCallback = new WebhookCallback(alarmRulesWatcher); List<AlarmMessage> alarmMessages = new ArrayList<>(2); AlarmMessage alarmMessage = new AlarmMessage(); alarmMessage.setScopeId(DefaultScopeDefine.ALL); alarmMessage.setRuleName("service_resp_time_rule"); alarmMessage.setAlarmMessage("alarmMessage with [DefaultScopeDefine.All]"); alarmMessages.add(alarmMessage); AlarmMessage anotherAlarmMessage = new AlarmMessage(); anotherAlarmMessage.setRuleName("service_resp_time_rule_2"); anotherAlarmMessage.setScopeId(DefaultScopeDefine.ENDPOINT); anotherAlarmMessage.setAlarmMessage("anotherAlarmMessage with [DefaultScopeDefine.Endpoint]"); alarmMessages.add(anotherAlarmMessage); webhookCallback.doAlarm(alarmMessages); Assert.assertTrue(isSuccess); }