Search in sources :

Example 1 with HttpClientWrapper

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

Example 2 with HttpClientWrapper

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

the class HttpPostMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Poll the specified address for service availability.
 *
 * During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
 * the exec on request is successful, the banner line generated by the
 * interface is parsed and if the banner text indicates that we are talking
 * to Provided that the interface's response is valid we set the service
 * status to SERVICE_AVAILABLE and return.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Process parameters
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    // URI
    String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);
    // Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
    // Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
    // BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    // Scheme
    String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);
    // Payload
    String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);
    // Mimetype
    String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);
    // Charset
    String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);
    // SSLFilter
    boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);
    // Get the address instance.
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        HttpClientWrapper clientWrapper = null;
        try {
            tracker.startAttempt();
            clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout()).setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);
            if (boolSSLFilter) {
                clientWrapper.trustSelfSigned(strScheme);
            }
            HttpEntity postReq;
            if (strUser != null && strPasswd != null) {
                clientWrapper.addBasicCredentials(strUser, strPasswd);
            }
            try {
                postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
            } catch (final UnsupportedCharsetException e) {
                serviceStatus = PollStatus.unavailable("Unsupported encoding encountered while constructing POST body " + e);
                break;
            }
            URIBuilder ub = new URIBuilder();
            ub.setScheme(strScheme);
            ub.setHost(hostAddress);
            ub.setPort(port);
            ub.setPath(strURI);
            LOG.debug("HttpPostMonitor: Constructed URL is {}", ub);
            HttpPost post = new HttpPost(ub.build());
            post.setEntity(postReq);
            CloseableHttpResponse response = clientWrapper.execute(post);
            LOG.debug("HttpPostMonitor: Status Line is {}", response.getStatusLine());
            if (response.getStatusLine().getStatusCode() > 399) {
                LOG.info("HttpPostMonitor: Got response status code {}", response.getStatusLine().getStatusCode());
                LOG.debug("HttpPostMonitor: Received server response: {}", response.getStatusLine());
                LOG.debug("HttpPostMonitor: Failing on bad status code");
                serviceStatus = PollStatus.unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
                break;
            }
            LOG.debug("HttpPostMonitor: Response code is valid");
            double responseTime = tracker.elapsedTimeInMillis();
            HttpEntity entity = response.getEntity();
            InputStream responseStream = entity.getContent();
            String Strresponse = IOUtils.toString(responseStream);
            if (Strresponse == null)
                continue;
            LOG.debug("HttpPostMonitor: banner = {}", Strresponse);
            LOG.debug("HttpPostMonitor: responseTime= {}ms", responseTime);
            // Could it be a regex?
            if (!Strings.isNullOrEmpty(strBannerMatch) && strBannerMatch.startsWith("~")) {
                if (!Strresponse.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                    break;
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (Strresponse.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
                    break;
                }
            }
        } catch (final URISyntaxException e) {
            final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (final Exception e) {
            final String reason = "Exception: " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }
    // return the status of the service
    return serviceStatus;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) PollStatus(org.opennms.netmgt.poller.PollStatus) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InetAddress(java.net.InetAddress)

Example 3 with HttpClientWrapper

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

the class WebMonitor method poll.

/**
 * {@inheritDoc}
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    PollStatus pollStatus = PollStatus.unresponsive();
    HttpClientWrapper clientWrapper = HttpClientWrapper.create();
    try {
        final String hostAddress = InetAddressUtils.str(svc.getAddress());
        URIBuilder ub = new URIBuilder();
        ub.setScheme(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
        ub.setHost(hostAddress);
        ub.setPort(ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT));
        ub.setPath(ParameterMap.getKeyedString(map, "path", DEFAULT_PATH));
        String queryString = ParameterMap.getKeyedString(map, "queryString", null);
        if (queryString != null && !queryString.trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
            if (!params.isEmpty()) {
                ub.setParameters(params);
            }
        }
        final HttpGet getMethod = new HttpGet(ub.build());
        clientWrapper.setConnectionTimeout(ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT)).setSocketTimeout(ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));
        final String userAgent = ParameterMap.getKeyedString(map, "user-agent", DEFAULT_USER_AGENT);
        if (userAgent != null && !userAgent.trim().isEmpty()) {
            clientWrapper.setUserAgent(userAgent);
        }
        final String virtualHost = ParameterMap.getKeyedString(map, "virtual-host", hostAddress);
        if (virtualHost != null && !virtualHost.trim().isEmpty()) {
            clientWrapper.setVirtualHost(virtualHost);
        }
        if (ParameterMap.getKeyedBoolean(map, "http-1.0", false)) {
            clientWrapper.setVersion(HttpVersion.HTTP_1_0);
        }
        for (final Object okey : map.keySet()) {
            final String key = okey.toString();
            if (key.matches("header_[0-9]+$")) {
                final String headerName = ParameterMap.getKeyedString(map, key, null);
                final String headerValue = ParameterMap.getKeyedString(map, key + "_value", null);
                getMethod.setHeader(headerName, headerValue);
            }
        }
        if (ParameterMap.getKeyedBoolean(map, "use-ssl-filter", false)) {
            clientWrapper.trustSelfSigned(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
        }
        if (ParameterMap.getKeyedBoolean(map, "auth-enabled", false)) {
            clientWrapper.addBasicCredentials(ParameterMap.getKeyedString(map, "auth-user", DEFAULT_USER), ParameterMap.getKeyedString(map, "auth-password", DEFAULT_PASSWORD));
            if (ParameterMap.getKeyedBoolean(map, "auth-preemptive", true)) {
                clientWrapper.usePreemptiveAuth();
            }
        }
        LOG.debug("getMethod parameters: {}", getMethod);
        CloseableHttpResponse response = clientWrapper.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().getReasonPhrase();
        String expectedText = ParameterMap.getKeyedString(map, "response-text", null);
        LOG.debug("returned results are:");
        if (!inRange(ParameterMap.getKeyedString(map, "response-range", DEFAULT_HTTP_STATUS_RANGE), statusCode)) {
            pollStatus = PollStatus.unavailable(statusText);
        } else {
            pollStatus = PollStatus.available();
        }
        if (expectedText != null) {
            String responseText = EntityUtils.toString(response.getEntity());
            if (expectedText.charAt(0) == '~') {
                if (!responseText.matches(expectedText.substring(1))) {
                    pollStatus = PollStatus.unavailable("Regex Failed");
                } else
                    pollStatus = PollStatus.available();
            } else {
                if (expectedText.equals(responseText))
                    pollStatus = PollStatus.available();
                else
                    pollStatus = PollStatus.unavailable("Did not find expected Text");
            }
        }
    } catch (IOException e) {
        LOG.info(e.getMessage());
        pollStatus = PollStatus.unavailable(e.getMessage());
    } catch (URISyntaxException e) {
        LOG.info(e.getMessage());
        pollStatus = PollStatus.unavailable(e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error("Unable to set SSL trust to allow self-signed certificates", e);
        pollStatus = PollStatus.unavailable("Unable to set SSL trust to allow self-signed certificates");
    } catch (Throwable e) {
        LOG.error("Unexpected exception while running " + getClass().getName(), e);
        pollStatus = PollStatus.unavailable("Unexpected exception: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
    return pollStatus;
}
Also used : NameValuePair(org.apache.http.NameValuePair) PollStatus(org.opennms.netmgt.poller.PollStatus) HttpGet(org.apache.http.client.methods.HttpGet) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 4 with HttpClientWrapper

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

the class HttpNorthbounder method forwardAlarms.

/* (non-Javadoc)
     * @see org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder#forwardAlarms(java.util.List)
     */
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
    LOG.info("Forwarding {} alarms", alarms.size());
    // Need a configuration bean for these
    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = Integer.valueOf(3);
    URI uri = m_config.getURI();
    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(connectionTimeout).setSocketTimeout(socketTimeout).setRetries(retryCount).useBrowserCompatibleCookies();
    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        clientWrapper.setVirtualHost(m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        clientWrapper.setUserAgent(m_config.getUserAgent());
    }
    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure HTTP northbounder for relaxed SSL.", e);
        }
    }
    HttpUriRequest method = null;
    if (HttpMethod.POST == (m_config.getMethod())) {
        HttpPost postMethod = new HttpPost(uri);
        // TODO: need to configure these
        List<NameValuePair> postParms = new ArrayList<>();
        // FIXME:do this for now
        NameValuePair p = new BasicNameValuePair("foo", "bar");
        postParms.add(p);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParms, StandardCharsets.UTF_8);
        postMethod.setEntity(formEntity);
        HttpEntity entity = null;
        try {
            // I have no idea what I'm doing here ;)
            entity = new StringEntity("XML HERE");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        postMethod.setEntity(entity);
        method = postMethod;
    } else if (HttpMethod.GET == m_config.getMethod()) {
        // TODO: need to configure these
        // List<NameValuePair> getParms = null;
        method = new HttpGet(uri);
    }
    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
    clientWrapper.setVersion(httpVersion);
    HttpResponse response = null;
    try {
        response = clientWrapper.execute(method);
        int code = response.getStatusLine().getStatusCode();
        HttpResponseRange range = new HttpResponseRange("200-399");
        if (!range.contains(code)) {
            LOG.debug("response code out of range for uri:{}.  Expected {} but received {}", uri, range, code);
            throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected " + range + " but received " + code);
        }
        LOG.debug("HTTP Northbounder received response: {}", response.getStatusLine().getReasonPhrase());
    } catch (final ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (final IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseRange(org.opennms.core.utils.HttpResponseRange) StringEntity(org.apache.http.entity.StringEntity) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) HttpVersion(org.apache.http.HttpVersion)

Example 5 with HttpClientWrapper

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

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