use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.
the class AbstractSlackCompatibleNotificationStrategy method send.
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public int send(List<Argument> arguments) {
m_arguments = arguments;
String url = getUrl();
if (url == null) {
LOG.error("send: url must not be null");
return 1;
}
String iconUrl = getIconUrl();
String iconEmoji = getIconEmoji();
String channel = getChannel();
String message = buildMessage(arguments);
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000).setSocketTimeout(3000).useSystemProxySettings();
HttpPost postMethod = new HttpPost(url);
JSONObject jsonData = new JSONObject();
jsonData.put("username", getUsername());
if (iconUrl != null) {
jsonData.put("icon_url", iconUrl);
}
if (iconEmoji != null) {
jsonData.put("icon_emoji", iconEmoji);
}
if (channel != null) {
jsonData.put("channel", channel);
}
jsonData.put("text", message);
if (jsonData.containsKey("icon_url") && jsonData.containsKey("icon_emoji")) {
LOG.warn("Both URL and emoji specified for icon. Sending both; behavior is undefined.");
}
LOG.debug("Prepared JSON POST data for webhook is: {}", jsonData.toJSONString());
final HttpEntity entity = new StringEntity(jsonData.toJSONString(), ContentType.APPLICATION_JSON);
postMethod.setEntity(entity);
// Mattermost 1.1.0 does not like having charset specified alongside Content-Type
postMethod.setHeader("Content-Type", "application/json");
String contents = null;
int statusCode = -1;
try {
CloseableHttpResponse response = clientWrapper.getClient().execute(postMethod);
statusCode = response.getStatusLine().getStatusCode();
contents = EntityUtils.toString(response.getEntity());
LOG.debug("send: Contents is: {}", contents);
} catch (IOException e) {
LOG.error("send: I/O problem with webhook post/response: {}", e);
throw new RuntimeException("Problem with webhook post: " + e.getMessage());
} finally {
IOUtils.closeQuietly(clientWrapper);
}
if ("ok".equals(contents)) {
LOG.debug("Got 'ok' back from webhook, indicating success.");
statusCode = 0;
} else {
LOG.info("Got a non-ok response from webhook, attempting to dissect response.");
LOG.error("Webhook returned non-OK response to notification post: {}", formatWebhookErrorResponse(statusCode, contents));
statusCode = 1;
}
return statusCode;
}
use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.
the class HttpNotificationStrategy method send.
/* (non-Javadoc)
* @see org.opennms.netmgt.notifd.NotificationStrategy#send(java.util.List)
*/
/** {@inheritDoc} */
@Override
public int send(List<Argument> arguments) {
m_arguments = arguments;
String url = getUrl();
if (url == null) {
LOG.warn("send: url argument is null, HttpNotification requires a URL");
return 1;
}
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000).setSocketTimeout(3000).useSystemProxySettings();
HttpUriRequest method = null;
final List<NameValuePair> posts = getPostArguments();
if (posts == null) {
method = new HttpGet(url);
LOG.info("send: No \"post-\" arguments..., continuing with an HTTP GET using URL: {}", url);
} else {
LOG.info("send: Found \"post-\" arguments..., continuing with an HTTP POST using URL: {}", url);
for (final NameValuePair post : posts) {
LOG.debug("send: post argument: {} = {}", post.getName(), post.getValue());
}
method = new HttpPost(url);
final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(posts, StandardCharsets.UTF_8);
((HttpPost) method).setEntity(entity);
}
String contents = null;
int statusCode = -1;
try {
CloseableHttpResponse response = clientWrapper.execute(method);
statusCode = response.getStatusLine().getStatusCode();
contents = EntityUtils.toString(response.getEntity());
LOG.info("send: Contents is: {}", contents);
} catch (IOException e) {
LOG.error("send: IO problem with HTTP post/response: {}", e);
throw new RuntimeException("Problem with HTTP post: " + e.getMessage());
} finally {
IOUtils.closeQuietly(clientWrapper);
}
doSql(contents);
return statusCode;
}
use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.
the class GrafanaDashletConfigurationWindow method getGrafanaDashboards.
private Map<String, String> getGrafanaDashboards() throws GrafanaDashletException {
/**
* Loading the required properties...
*/
final String grafanaApiKey = System.getProperty("org.opennms.grafanaBox.apiKey", "");
final String grafanaProtocol = System.getProperty("org.opennms.grafanaBox.protocol", "http");
final String grafanaHostname = System.getProperty("org.opennms.grafanaBox.hostname", "localhost");
final int grafanaPort = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.port", "3000"));
final int grafanaConnectionTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.connectionTimeout", "500"));
final int grafanaSoTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.soTimeout", "500"));
if (!"".equals(grafanaApiKey) && !"".equals(grafanaHostname) && !"".equals(grafanaProtocol) && ("http".equals(grafanaProtocol) || "https".equals(grafanaProtocol))) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(grafanaConnectionTimeout).setSocketTimeout(grafanaSoTimeout).build();
final URI uri = new URIBuilder().setScheme(grafanaProtocol).setHost(grafanaHostname).setPort(grafanaPort).setPath("/api/search/").build();
final HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);
/**
* Adding the API key...
*/
httpGet.setHeader("Authorization", "Bearer " + grafanaApiKey);
final Map<String, String> resultSet = new TreeMap<>();
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
/**
* Fill the result set...
*/
final String responseString = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8.name());
if (!Strings.isNullOrEmpty(responseString)) {
try {
final JSONArray arr = new JSONObject("{dashboards:" + responseString + "}").getJSONArray("dashboards");
for (int i = 0; i < arr.length(); i++) {
resultSet.put(arr.getJSONObject(i).getString("title"), arr.getJSONObject(i).getString("uri"));
}
} catch (JSONException e) {
throw new GrafanaDashletException(e.getMessage());
}
}
}
}
return resultSet;
} catch (Exception e) {
throw new GrafanaDashletException(e.getMessage());
}
} else {
throw new GrafanaDashletException("Invalid configuration");
}
}
use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.
the class NominatimGeocoder method geocode.
/** {@inheritDoc} */
@Override
public GWTLatLng geocode(final String geolocation) throws GeocoderException {
final HttpUriRequest method = new HttpGet(getUrl(geolocation));
method.addHeader("User-Agent", "OpenNMS-MapquestGeocoder/1.0");
if (m_referer != null) {
method.addHeader("Referer", m_referer);
}
CloseableHttpResponse response = null;
try {
response = m_clientWrapper.execute(method);
InputStream responseStream = response.getEntity().getContent();
final ElementTree tree = ElementTree.fromStream(responseStream);
if (tree == null) {
throw new GeocoderException("an error occurred connecting to the Nominatim geocoding service (no XML tree was found)");
}
final List<ElementTree> places = tree.findAll("//place");
if (places.size() > 1) {
LOG.warn("more than one location returned for query: {}", geolocation);
} else if (places.size() == 0) {
throw new GeocoderException("Nominatim returned an OK status code, but no places");
}
final ElementTree place = places.get(0);
Double latitude = Double.valueOf(place.getAttribute("lat"));
Double longitude = Double.valueOf(place.getAttribute("lon"));
return new GWTLatLng(latitude, longitude);
} catch (GeocoderException e) {
throw e;
} catch (Throwable e) {
throw new GeocoderException("unable to get lat/lng from Nominatim", e);
} finally {
m_clientWrapper.close(response);
}
}
use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.
the class HttpRequisitionProvider method getRequisitionFor.
@Override
public Requisition getRequisitionFor(HttpRequisitionRequest request) {
try (HttpClientWrapper client = HttpClientWrapper.create()) {
final URI uri = new URI(request.getUrl());
HttpGet get = new HttpGet(uri);
if (Boolean.FALSE.equals(request.getStrictSsl())) {
client.trustSelfSigned(uri.getScheme());
}
if (request.getUsername() != null) {
client.addBasicCredentials(request.getPassword(), request.getPassword());
}
try (CloseableHttpResponse response = client.execute(get)) {
String responseString = new BasicResponseHandler().handleResponse(response);
return JaxbUtils.unmarshal(Requisition.class, responseString);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Aggregations