Skip to content

Commit 44d82aa

Browse files
Refactored sending POST to AlertManager into specific class
Signed-off-by: Decker, Stefan <[email protected]>
1 parent 9d0bec2 commit 44d82aa

File tree

3 files changed

+96
-69
lines changed

3 files changed

+96
-69
lines changed

src/main/java/de/gdata/mobilelab/alertmanagercallback/AlertManagerAlarmCallback.java

Lines changed: 3 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package de.gdata.mobilelab.alertmanagercallback;
22

3-
import com.fasterxml.jackson.databind.ObjectMapper;
4-
53
import org.graylog2.plugin.alarms.AlertCondition;
64
import org.graylog2.plugin.alarms.callbacks.AlarmCallback;
75
import org.graylog2.plugin.alarms.callbacks.AlarmCallbackConfigurationException;
@@ -14,28 +12,19 @@
1412
import org.graylog2.plugin.configuration.fields.TextField;
1513
import org.graylog2.plugin.streams.Stream;
1614

17-
import java.io.BufferedReader;
18-
import java.io.IOException;
19-
import java.io.InputStreamReader;
20-
import java.io.OutputStream;
21-
import java.net.HttpURLConnection;
2215
import java.net.URI;
2316
import java.net.URISyntaxException;
24-
import java.net.URL;
25-
import java.nio.charset.StandardCharsets;
2617
import java.util.Map;
2718

2819
public class AlertManagerAlarmCallback implements AlarmCallback {
2920

3021
private Configuration configuration;
31-
private ObjectMapper objectMapper;
22+
private AlertManagerPostRequestSender alertManagerPostRequestSender;
3223

3324
@Override
3425
public void initialize(Configuration config) throws AlarmCallbackConfigurationException {
3526
configuration = config;
36-
if (objectMapper == null) {
37-
objectMapper = new ObjectMapper();
38-
}
27+
alertManagerPostRequestSender = new AlertManagerPostRequestSender(config.getString("alertmanager_api_url"));
3928
}
4029

4130
@Override
@@ -46,60 +35,7 @@ public void call(Stream stream, AlertCondition.CheckResult result) throws AlarmC
4635
.withStream(stream)
4736
.build();
4837

49-
Object[] wrapper = new Object[1];
50-
wrapper[0] = alertManagerPayload;
51-
52-
final String alertManagerApiUrl = configuration.getString("alertmanager_api_url");
53-
try {
54-
String responseAsString = postForResponseAsString(alertManagerApiUrl, objectMapper.writeValueAsString(wrapper));
55-
AlertManagerResponse alertManagerResponse = objectMapper.readValue(responseAsString, AlertManagerResponse.class);
56-
if (!AlertManagerResponse.STATUS_SUCCESS.equals(alertManagerResponse.getStatus())) {
57-
throw new AlarmCallbackException("Response from AlertManager for Alert failed. Response-Status: '"
58-
+ alertManagerResponse.getStatus() + "'.");
59-
}
60-
} catch (Exception e) {
61-
throw new AlarmCallbackException("Could not send Alert to AlertManager (" + alertManagerApiUrl + ").", e);
62-
}
63-
}
64-
65-
/**
66-
* Sends the POST-request to the given targetUrl with given payload as body.
67-
*
68-
* @param targetUrl the target url of POST-request
69-
* @param payload the payload (JSON body)
70-
* @return the response
71-
* @throws IOException if request fails
72-
*/
73-
private String postForResponseAsString(String targetUrl, String payload) throws IOException {
74-
URL apiUrl = new URL(targetUrl);
75-
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
76-
connection.setDoInput(true);
77-
connection.setDoOutput(true);
78-
79-
connection.setRequestProperty("Content-Type", "application/json;");
80-
connection.setRequestProperty("Accept", "application/json,text/plain");
81-
connection.setRequestProperty("Method", "POST");
82-
OutputStream os = connection.getOutputStream();
83-
os.write(payload.getBytes(StandardCharsets.UTF_8));
84-
os.close();
85-
86-
StringBuilder sb = new StringBuilder();
87-
int HttpResult = connection.getResponseCode();
88-
if (HttpResult == HttpURLConnection.HTTP_OK) {
89-
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
90-
91-
String line;
92-
while ((line = br.readLine()) != null) {
93-
sb.append(line).append("\n");
94-
}
95-
br.close();
96-
connection.disconnect();
97-
return sb.toString();
98-
} else {
99-
throw new IOException("Could not get a valid response for POST-request to '" + targetUrl
100-
+ "'. ResponseCode: " + connection.getResponseCode()
101-
+ " ResponseMessage: '" + connection.getResponseMessage() + "'.");
102-
}
38+
alertManagerPostRequestSender.sendPostRequestToAlertManager(alertManagerPayload);
10339
}
10440

10541
@Override
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package de.gdata.mobilelab.alertmanagercallback;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
5+
import org.graylog2.plugin.alarms.callbacks.AlarmCallbackException;
6+
7+
import java.io.BufferedReader;
8+
import java.io.IOException;
9+
import java.io.InputStreamReader;
10+
import java.io.OutputStream;
11+
import java.net.HttpURLConnection;
12+
import java.net.URL;
13+
import java.nio.charset.StandardCharsets;
14+
15+
class AlertManagerPostRequestSender {
16+
17+
private ObjectMapper objectMapper;
18+
private final String alertManagerApiUrl;
19+
20+
/**
21+
* Initialized a new POST request sender for the AlertManager callback with given AlertManager API URL.
22+
*
23+
* @param alertManagerApiUrl the AlertManager API URL to use
24+
*/
25+
AlertManagerPostRequestSender(String alertManagerApiUrl) {
26+
this.alertManagerApiUrl = alertManagerApiUrl;
27+
objectMapper = new ObjectMapper();
28+
}
29+
30+
/**
31+
* Sends the HTTP-POST request to the AlertManager with given payload.
32+
*
33+
* @param alertManagerPayload the payload to send
34+
* @throws AlarmCallbackException if sending POST fails
35+
*/
36+
void sendPostRequestToAlertManager(AlertManagerPayload alertManagerPayload) throws AlarmCallbackException {
37+
Object[] wrapper = new Object[1];
38+
wrapper[0] = alertManagerPayload;
39+
try {
40+
String responseAsString = postForResponseAsString(alertManagerApiUrl, objectMapper.writeValueAsString(wrapper));
41+
AlertManagerResponse alertManagerResponse = objectMapper.readValue(responseAsString, AlertManagerResponse.class);
42+
if (!AlertManagerResponse.STATUS_SUCCESS.equals(alertManagerResponse.getStatus())) {
43+
throw new AlarmCallbackException("Response from AlertManager for Alert failed. Response-Status: '"
44+
+ alertManagerResponse.getStatus() + "'.");
45+
}
46+
} catch (Exception e) {
47+
throw new AlarmCallbackException("Could not send Alert to AlertManager (" + alertManagerApiUrl + ").", e);
48+
}
49+
}
50+
51+
/**
52+
* Sends the POST-request to the given targetUrl with given payload as body.
53+
*
54+
* @param targetUrl the target url of POST-request
55+
* @param payload the payload (JSON body)
56+
* @return the response
57+
* @throws IOException if request fails
58+
*/
59+
private String postForResponseAsString(String targetUrl, String payload) throws IOException {
60+
URL apiUrl = new URL(targetUrl);
61+
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
62+
connection.setDoInput(true);
63+
connection.setDoOutput(true);
64+
65+
connection.setRequestProperty("Content-Type", "application/json;");
66+
connection.setRequestProperty("Accept", "application/json,text/plain");
67+
connection.setRequestProperty("Method", "POST");
68+
OutputStream os = connection.getOutputStream();
69+
os.write(payload.getBytes(StandardCharsets.UTF_8));
70+
os.close();
71+
72+
StringBuilder sb = new StringBuilder();
73+
int HttpResult = connection.getResponseCode();
74+
if (HttpResult == HttpURLConnection.HTTP_OK) {
75+
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
76+
77+
String line;
78+
while ((line = br.readLine()) != null) {
79+
sb.append(line).append("\n");
80+
}
81+
br.close();
82+
connection.disconnect();
83+
return sb.toString();
84+
} else {
85+
throw new IOException("Could not get a valid response for POST-request to '" + targetUrl
86+
+ "'. ResponseCode: " + connection.getResponseCode()
87+
+ " ResponseMessage: '" + connection.getResponseMessage() + "'.");
88+
}
89+
}
90+
91+
}

src/test/java/de/gdata/mobilelab/alertmanagercallback/AlertManagerAlarmCallbackTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ public void initialize() throws AlarmCallbackConfigurationException, NoSuchField
3131
alertManagerAlarmCallback.initialize(configuration);
3232

3333
// then: alertManagerAlarmCallback should have been correctly initialized
34-
// Check that ObjectMapper is not null
35-
Field field = AlertManagerAlarmCallback.class.getDeclaredField("objectMapper");
34+
// Check that alertManagerPostRequestSender is not null
35+
Field field = AlertManagerAlarmCallback.class.getDeclaredField("alertManagerPostRequestSender");
3636
field.setAccessible(true);
3737
assertNotNull(field.get(alertManagerAlarmCallback));
3838

0 commit comments

Comments
 (0)