use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.
the class NCSNorthbounder method postAlarms.
private void postAlarms(HttpEntity entity) {
// Need a configuration bean for these
int connectionTimeout = 3000;
int socketTimeout = 3000;
Integer retryCount = 3;
HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
URI uri = m_config.getURI();
System.err.println("uri = " + uri);
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setSocketTimeout(socketTimeout).setConnectionTimeout(connectionTimeout).setRetries(retryCount).useBrowserCompatibleCookies().dontReuseConnections();
if ("https".equals(uri.getScheme())) {
try {
clientWrapper.useRelaxedSSL("https");
} catch (final GeneralSecurityException e) {
throw new NorthbounderException("Failed to configure Relaxed SSL handling.", e);
}
}
final HttpEntityEnclosingRequestBase method = m_config.getMethod().getRequestMethod(uri);
if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
method.setHeader(HTTP.TARGET_HOST, m_config.getVirtualHost());
}
if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
method.setHeader(HTTP.USER_AGENT, m_config.getUserAgent());
}
method.setProtocolVersion(httpVersion);
method.setEntity(entity);
CloseableHttpResponse response = null;
try {
System.err.println("execute: " + method);
response = clientWrapper.execute(method);
} catch (ClientProtocolException e) {
throw new NorthbounderException(e);
} catch (IOException e) {
throw new NorthbounderException(e);
} finally {
IOUtils.closeQuietly(clientWrapper);
}
if (response != null) {
try {
int code = response.getStatusLine().getStatusCode();
final HttpResponseRange range = new HttpResponseRange("200-399");
if (!range.contains(code)) {
LOG.warn("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);
}
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
LOG.debug(response != null ? response.getStatusLine().getReasonPhrase() : "Response was null");
}
use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.
the class PageSequenceMonitor method poll.
/**
* {@inheritDoc}
*/
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameterMap) {
PollStatus serviceStatus = PollStatus.unavailable("Poll not completed yet");
final Map<String, Number> responseTimes = new LinkedHashMap<String, Number>();
SequenceTracker tracker = new SequenceTracker(parameterMap, DEFAULT_SEQUENCE_RETRY, DEFAULT_TIMEOUT);
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
HttpClientWrapper clientWrapper = null;
try {
PageSequenceMonitorParameters parms = PageSequenceMonitorParameters.get(parameterMap);
clientWrapper = parms.createHttpClient();
// TODO: Is it normal for monitors to set 'response-time' to NaN
// before the poll is executed?
responseTimes.put(PollStatus.PROPERTY_RESPONSE_TIME, Double.NaN);
tracker.startAttempt();
parms.getPageSequence().execute(clientWrapper, svc, responseTimes);
double responseTime = tracker.elapsedTimeInMillis();
serviceStatus = PollStatus.available();
// Update response time with the actual execution time
responseTimes.put(PollStatus.PROPERTY_RESPONSE_TIME, responseTime);
} catch (PageSequenceMonitorException e) {
serviceStatus = PollStatus.unavailable(e.getMessage());
} catch (IllegalArgumentException e) {
LOG.error("Invalid parameters to monitor", e);
serviceStatus = PollStatus.unavailable("Invalid parameter to monitor: " + e.getMessage() + ". See log for details.");
} catch (Throwable e) {
LOG.error("Unexpected exception: " + e.getMessage(), e);
serviceStatus = PollStatus.unavailable("Unexpected exception: " + e.getMessage());
} finally {
serviceStatus.setProperties(responseTimes);
IOUtils.closeQuietly(clientWrapper);
}
}
return serviceStatus;
}
use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.
the class HypericAckProcessor method fetchHypericAlerts.
/**
* <p>fetchHypericAlerts</p>
*
* @param hypericUrl a {@link java.lang.String} object.
* @param alertIds a {@link java.util.List} object.
* @return a {@link java.util.List} object.
* @throws org.apache.commons.httpclient.HttpException if any.
* @throws java.io.IOException if any.
* @throws javax.xml.bind.JAXBException if any.
* @throws javax.xml.stream.XMLStreamException if any.
*/
public static List<HypericAlertStatus> fetchHypericAlerts(String hypericUrl, List<String> alertIds) throws IOException, JAXBException, XMLStreamException {
List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();
if (alertIds.size() < 1) {
return retval;
}
for (int i = 0; i < alertIds.size(); i++) {
// Construct the query string for the HTTP operation
final StringBuilder alertIdString = new StringBuilder();
alertIdString.append("?");
for (int j = 0; (j < ALERTS_PER_HTTP_TRANSACTION) && (i < alertIds.size()); j++, i++) {
if (j > 0)
alertIdString.append("&");
// Numeric values, no need to worry about URL encoding
alertIdString.append("id=").append(alertIds.get(i));
}
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000).setSocketTimeout(3000).setUserAgent("OpenNMS-Ackd.HypericAckProcessor");
HttpUriRequest httpMethod = new HttpGet(hypericUrl + alertIdString.toString());
// Parse the URI from the config so that we can deduce the username/password information
String userinfo = null;
try {
URI hypericUri = new URI(hypericUrl);
userinfo = hypericUri.getUserInfo();
} catch (final URISyntaxException e) {
LOG.warn("Could not parse URI to get username/password stanza: {}", hypericUrl, e);
}
if (userinfo != null && !"".equals(userinfo)) {
final String[] credentials = userinfo.split(":");
if (credentials.length == 2) {
clientWrapper.addBasicCredentials(credentials[0], credentials[1]).usePreemptiveAuth();
} else {
LOG.warn("Unable to deduce username/password from '{}'", userinfo);
}
}
try {
CloseableHttpResponse response = clientWrapper.execute(httpMethod);
retval = parseHypericAlerts(new StringReader(EntityUtils.toString(response.getEntity())));
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
return retval;
}
use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.
the class HttpUrlConnectionIT method testServlet.
/**
* Test the Servlet with a simple POST Request based on XML Data.
*
* @throws Exception the exception
*/
@Test
@JUnitHttpServer(port = 10342, https = false, webapps = { @Webapp(context = "/junit", path = "src/test/resources/test-webapp") })
public void testServlet() throws Exception {
String xml = "<person><firstName>Alejandro</firstName></person>";
final HttpClientWrapper clientWrapper = HttpClientWrapper.create();
try {
StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML);
HttpPost method = new HttpPost("http://localhost:10342/junit/test/sample");
method.setEntity(entity);
CloseableHttpResponse response = clientWrapper.execute(method);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
Assert.assertEquals("OK!", EntityUtils.toString(response.getEntity()));
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
use of org.opennms.core.web.HttpClientWrapper in project opennms by OpenNMS.
the class GraphMLTopologyIT method existsGraph.
private boolean existsGraph() throws IOException {
try (HttpClientWrapper client = createClientWrapper()) {
HttpGet httpGet = new HttpGet(URL);
httpGet.addHeader("Accept", "application/xml");
CloseableHttpResponse response = client.execute(httpGet);
return response.getStatusLine().getStatusCode() == 200;
}
}
Aggregations