Search in sources :

Example 91 with CloseableHttpResponse

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpEntity(org.apache.http.HttpEntity) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException)

Example 92 with CloseableHttpResponse

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;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException)

Example 93 with CloseableHttpResponse

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");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) TreeMap(java.util.TreeMap) URI(java.net.URI) JSONException(org.json.JSONException) URIBuilder(org.apache.http.client.utils.URIBuilder) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 94 with CloseableHttpResponse

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);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) GWTLatLng(org.opennms.features.poller.remote.gwt.client.GWTLatLng) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ElementTree(net.simon04.jelementtree.ElementTree)

Example 95 with CloseableHttpResponse

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);
    }
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) URI(java.net.URI)

Aggregations

CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)536 HttpGet (org.apache.http.client.methods.HttpGet)242 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)171 StringEntity (org.apache.http.entity.StringEntity)127 JsonNode (com.fasterxml.jackson.databind.JsonNode)125 Test (org.junit.Test)125 HttpPost (org.apache.http.client.methods.HttpPost)107 IOException (java.io.IOException)105 HttpEntity (org.apache.http.HttpEntity)103 Deployment (org.activiti.engine.test.Deployment)87 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)67 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)57 InputStream (java.io.InputStream)53 HttpPut (org.apache.http.client.methods.HttpPut)50 Task (org.activiti.engine.task.Task)41 URI (java.net.URI)36 StatusLine (org.apache.http.StatusLine)34 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)34 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 BufferedReader (java.io.BufferedReader)30