Search in sources :

Example 96 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse 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 97 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse 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 98 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.

the class OnmsRestEventsClient method getEventCount.

/**
	 * Returns event count or null if failed to retrieve data
	 * @return
	 */
public Integer getEventCount() {
    Integer eventCount = null;
    CloseableHttpClient httpclient = getNewClient();
    try {
        HttpGet getRequest = new HttpGet(onmsUrl + EVENT_COUNT_URI);
        getRequest.addHeader("accept", "text/plain");
        LOG.debug("Executing request " + getRequest.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        String responseStr = null;
        try {
            LOG.debug("response status:" + response.getStatusLine().toString());
            responseStr = EntityUtils.toString(response.getEntity());
            LOG.debug("response string:" + responseStr);
            eventCount = Integer.parseInt(responseStr);
        } finally {
            response.close();
        }
    } catch (Exception e) {
        throw new RuntimeException("exception when getting event count", e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
        }
    }
    return eventCount;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 99 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.

the class MetadataUtils method fetchGeodata.

public static Map<String, String> fetchGeodata() {
    final Map<String, String> ret = new HashMap<>();
    final String url = "http://freegeoip.net/xml/";
    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpGet get = new HttpGet(url);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(get);
        final HttpEntity entity = response.getEntity();
        final String xml = EntityUtils.toString(entity);
        System.err.println("xml = " + xml);
        final GeodataResponse geoResponse = JaxbUtils.unmarshal(GeodataResponse.class, xml);
        ret.put("external-ip-address", InetAddressUtils.str(geoResponse.getIp()));
        ret.put("country-code", geoResponse.getCountryCode());
        ret.put("region-code", geoResponse.getRegionCode());
        ret.put("city", geoResponse.getCity());
        ret.put("zip-code", geoResponse.getZipCode());
        ret.put("time-zone", geoResponse.getTimeZone());
        ret.put("latitude", geoResponse.getLatitude() == null ? null : geoResponse.getLatitude().toString());
        ret.put("longitude", geoResponse.getLongitude() == null ? null : geoResponse.getLongitude().toString());
        EntityUtils.consumeQuietly(entity);
    } catch (final Exception e) {
        LOG.debug("Failed to get GeoIP data from " + url, e);
    } finally {
        IOUtils.closeQuietly(response);
    }
    return ret;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GeodataResponse(org.opennms.netmgt.poller.remote.support.GeodataResponse) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 100 with CloseableHttpResponse

use of org.apache.http.client.methods.CloseableHttpResponse in project opennms by OpenNMS.

the class HttpUrlConnection method getInputStream.

/* (non-Javadoc)
     * @see java.net.URLConnection#getInputStream()
     */
@Override
public InputStream getInputStream() throws IOException {
    try {
        if (m_clientWrapper == null) {
            connect();
        }
        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(), StandardCharsets.UTF_8);
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }
        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }
        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }
        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException("Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e);
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) ContentType(org.apache.http.entity.ContentType) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) Header(org.opennms.protocols.xml.config.Header) Content(org.opennms.protocols.xml.config.Content) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

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