Search in sources :

Example 6 with HttpClientWrapper

use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.

the class ErrorResponseIT method verifyErrorResponseV1.

@Test
public void verifyErrorResponseV1() throws IOException {
    try (HttpClientWrapper client = createClientWrapper()) {
        // "INVALID-XML" is not a valid graphml definition, therefore unmarshalling will fail.
        HttpPost httpPost = new HttpPost(getBaseUrl() + "opennms/rest/graphml/test-graph");
        httpPost.setHeader("Accept", "application/xml");
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new StringEntity("INVALID-XML"));
        CloseableHttpResponse response = client.execute(httpPost);
        verify(response);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Test(org.junit.Test)

Example 7 with HttpClientWrapper

use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.

the class ErrorResponseIT method verifyErrorResponseV2.

@Test
public void verifyErrorResponseV2() throws IOException {
    try (HttpClientWrapper client = createClientWrapper()) {
        // The FIQL parser expects == and cannot handle =.
        HttpGet httpGet = new HttpGet(getBaseUrl() + "opennms/api/v2/nodes?_s=label=*");
        httpGet.setHeader("Accept", "application/json");
        CloseableHttpResponse response = client.execute(httpGet);
        verify(response);
    }
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Test(org.junit.Test)

Example 8 with HttpClientWrapper

use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.

the class ErrorResponseIT method createClientWrapper.

private static HttpClientWrapper createClientWrapper() {
    HttpClientWrapper wrapper = HttpClientWrapper.create();
    wrapper.addBasicCredentials(BASIC_AUTH_USERNAME, BASIC_AUTH_PASSWORD);
    return wrapper;
}
Also used : HttpClientWrapper(org.opennms.core.web.HttpClientWrapper)

Example 9 with HttpClientWrapper

use of org.opennms.core.web.HttpClientWrapper 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 10 with HttpClientWrapper

use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.

the class HttpCollector method doCollection.

/**
 * Performs HTTP collection.
 *
 * Couple of notes to make the implementation of this client library
 * less obtuse:
 *
 *   - HostConfiguration class is not created here because the library
 *     builds it when a URI is defined.
 *
 * @param collectorAgent
 * @throws HttpCollectorException
 */
private static void doCollection(final HttpCollectorAgent collectorAgent, final CollectionSetBuilder collectionSetBuilder) throws HttpCollectorException {
    HttpRequestBase method = null;
    HttpClientWrapper clientWrapper = null;
    try {
        final HttpVersion httpVersion = computeVersion(collectorAgent.getUriDef());
        clientWrapper = HttpClientWrapper.create().setConnectionTimeout(ParameterMap.getKeyedInteger(collectorAgent.getParameters(), ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT)).setSocketTimeout(ParameterMap.getKeyedInteger(collectorAgent.getParameters(), ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT)).useBrowserCompatibleCookies();
        if ("https".equals(collectorAgent.getUriDef().getUrl().getScheme())) {
            clientWrapper.useRelaxedSSL("https");
        }
        String key = ParameterName.RETRY.toString();
        if (collectorAgent.getParameters().containsKey(ParameterName.RETRIES.toString())) {
            key = ParameterName.RETRIES.toString();
        }
        Integer retryCount = ParameterMap.getKeyedInteger(collectorAgent.getParameters(), key, DEFAULT_RETRY_COUNT);
        clientWrapper.setRetries(retryCount);
        method = buildHttpMethod(collectorAgent);
        method.setProtocolVersion(httpVersion);
        final String userAgent = determineUserAgent(collectorAgent);
        if (userAgent != null && !userAgent.trim().isEmpty()) {
            clientWrapper.setUserAgent(userAgent);
        }
        final HttpClientWrapper wrapper = clientWrapper;
        if (collectorAgent.getUriDef().getUrl().getUserInfo().isPresent()) {
            final String userInfo = collectorAgent.getUriDef().getUrl().getUserInfo().get();
            final String[] streetCred = userInfo.split(":", 2);
            if (streetCred.length == 2) {
                wrapper.addBasicCredentials(streetCred[0], streetCred[1]);
            } else {
                LOG.warn("Illegal value found for username/password HTTP credentials: {}", userInfo);
            }
        }
        LOG.info("doCollection: collecting using method: {}", method);
        final CloseableHttpResponse response = clientWrapper.execute(method);
        // Not really a persist as such; it just stores data in collectionSet for later retrieval
        persistResponse(collectorAgent, collectionSetBuilder, response);
    } catch (URISyntaxException e) {
        throw new HttpCollectorException("Error building HttpClient URI", e);
    } catch (IOException e) {
        throw new HttpCollectorException("IO Error retrieving page", e);
    } catch (PatternSyntaxException e) {
        throw new HttpCollectorException("Invalid regex specified in HTTP collection configuration", e);
    } catch (Throwable e) {
        throw new HttpCollectorException("Unexpected exception caught during HTTP collection", e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpVersion(org.apache.http.HttpVersion) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

HttpClientWrapper (org.opennms.core.web.HttpClientWrapper)18 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HttpGet (org.apache.http.client.methods.HttpGet)7 HttpPost (org.apache.http.client.methods.HttpPost)7 IOException (java.io.IOException)6 StringEntity (org.apache.http.entity.StringEntity)6 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 HttpEntity (org.apache.http.HttpEntity)3 HttpVersion (org.apache.http.HttpVersion)3 NameValuePair (org.apache.http.NameValuePair)3 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)3 Test (org.junit.Test)3 PollStatus (org.opennms.netmgt.poller.PollStatus)3 ArrayList (java.util.ArrayList)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)2 URIBuilder (org.apache.http.client.utils.URIBuilder)2 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)2