use of org.apache.http.client.utils.URIBuilder 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;
}
use of org.apache.http.client.utils.URIBuilder 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);
}
}
use of org.apache.http.client.utils.URIBuilder in project intellij-community by JetBrains.
the class EduAdaptiveStepicConnector method getAttempts.
private static List<StepicWrappers.AdaptiveAttemptWrapper.Attempt> getAttempts(@NotNull StepicUser user, int id) throws URISyntaxException, IOException {
final URI attemptUrl = new URIBuilder(EduStepicNames.ATTEMPTS).addParameter("step", String.valueOf(id)).addParameter("user", String.valueOf(user.getId())).build();
final StepicWrappers.AdaptiveAttemptContainer attempt = EduStepicAuthorizedClient.getFromStepic(attemptUrl.toString(), StepicWrappers.AdaptiveAttemptContainer.class, user);
return attempt.attempts;
}
use of org.apache.http.client.utils.URIBuilder in project intellij-community by JetBrains.
the class EduAdaptiveStepicConnector method getEnrolledCoursesIds.
@NotNull
public static List<Integer> getEnrolledCoursesIds(@NotNull StepicUser stepicUser) {
try {
final URI enrolledCoursesUri = new URIBuilder(EduStepicNames.COURSES).addParameter("enrolled", "true").build();
final List<CourseInfo> courses = EduStepicAuthorizedClient.getFromStepic(enrolledCoursesUri.toString(), StepicWrappers.CoursesContainer.class, stepicUser).courses;
final ArrayList<Integer> ids = new ArrayList<>();
for (CourseInfo course : courses) {
ids.add(course.getId());
}
return ids;
} catch (IOException | URISyntaxException e) {
LOG.warn(e.getMessage());
}
return Collections.emptyList();
}
use of org.apache.http.client.utils.URIBuilder in project graylog2-server by Graylog2.
the class IntegrationTestsConfig method getGlServerURL.
public static URI getGlServerURL() throws MalformedURLException, URISyntaxException {
URIBuilder result = new URIBuilder(GL_BASE_URI);
if (GL_PORT != null) {
result.setPort(Integer.parseInt(GL_PORT));
}
final String username;
final String password;
if (result.getUserInfo() == null) {
username = GL_ADMIN_USER;
password = GL_ADMIN_PASSWORD;
} else {
final String[] userInfo = result.getUserInfo().split(":");
username = (GL_ADMIN_USER != null ? GL_ADMIN_USER : userInfo[0]);
password = (GL_ADMIN_PASSWORD != null ? GL_ADMIN_PASSWORD : userInfo[1]);
}
result.setUserInfo(firstNonNull(username, "admin"), firstNonNull(password, "admin"));
return result.build();
}
Aggregations