Search in sources :

Example 16 with URIBuilder

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;
}
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 17 with URIBuilder

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);
    }
}
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)

Example 18 with URIBuilder

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;
}
Also used : URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 19 with URIBuilder

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();
}
Also used : IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) NotNull(org.jetbrains.annotations.NotNull)

Example 20 with URIBuilder

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();
}
Also used : URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

URIBuilder (org.apache.http.client.utils.URIBuilder)95 URISyntaxException (java.net.URISyntaxException)36 URI (java.net.URI)35 HttpGet (org.apache.http.client.methods.HttpGet)21 IOException (java.io.IOException)19 NameValuePair (org.apache.http.NameValuePair)12 HttpEntity (org.apache.http.HttpEntity)9 NotNull (org.jetbrains.annotations.NotNull)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)7 HttpResponse (org.apache.http.HttpResponse)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 HttpClient (org.apache.http.client.HttpClient)5 Gson (com.google.gson.Gson)4 URL (java.net.URL)4 HttpPost (org.apache.http.client.methods.HttpPost)4 StringEntity (org.apache.http.entity.StringEntity)4 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)4