Search in sources :

Example 71 with NameValuePair

use of org.apache.http.NameValuePair in project sling by apache.

the class SlingParameter method toNameValuePairs.

public List<NameValuePair> toNameValuePairs() {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    if (multiple) {
        for (String value : values) {
            parameters.add(new BasicNameValuePair(parameterName, value));
        }
    } else if (values != null && values.length == 1) {
        parameters.add(new BasicNameValuePair(parameterName, values[0]));
    } else if (values != null && values.length > 1) {
        // TODO not sure about the proper format of the values in this case?
        // For now, only take the first one.
        parameters.add(new BasicNameValuePair(parameterName, values[0]));
    } else {
        parameters.add(new BasicNameValuePair(parameterName, null));
    }
    // add @TypeHint suffix
    if (typeHint != null) {
        String parameter = parameterName + "@TypeHint";
        parameters.add(new BasicNameValuePair(parameter, typeHint));
    }
    // add @Delete suffix
    if (delete) {
        String parameter = parameterName + "@Delete";
        parameters.add(new BasicNameValuePair(parameter, "true"));
    }
    return parameters;
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList)

Example 72 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class HttpCollector method buildPostMethod.

private static HttpPost buildPostMethod(final URI uri, final HttpCollectorAgent collectorAgent) {
    HttpPost method = new HttpPost(uri);
    List<NameValuePair> postParams = buildRequestParameters(collectorAgent);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8);
    method.setEntity(entity);
    return method;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 73 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class HttpCollector method buildGetMethod.

private static HttpGet buildGetMethod(final URI uri, final HttpCollectorAgent collectorAgent) {
    URI uriWithQueryString = null;
    List<NameValuePair> queryParams = buildRequestParameters(collectorAgent);
    try {
        final StringBuilder query = new StringBuilder();
        query.append(URLEncodedUtils.format(queryParams, StandardCharsets.UTF_8));
        if (uri.getQuery() != null && !uri.getQuery().trim().isEmpty()) {
            if (query.length() > 0) {
                query.append("&");
            }
            query.append(uri.getQuery());
        }
        final URIBuilder ub = new URIBuilder(uri);
        if (query.length() > 0) {
            final List<NameValuePair> params = URLEncodedUtils.parse(query.toString(), StandardCharsets.UTF_8);
            if (!params.isEmpty()) {
                ub.setParameters(params);
            }
        }
        uriWithQueryString = ub.build();
        return new HttpGet(uriWithQueryString);
    } catch (URISyntaxException e) {
        LOG.warn(e.getMessage(), e);
        return new HttpGet(uri);
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpGet(org.apache.http.client.methods.HttpGet) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 74 with NameValuePair

use of org.apache.http.NameValuePair 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 75 with NameValuePair

use of org.apache.http.NameValuePair in project opennms by OpenNMS.

the class RequestTracker method getClientWrapper.

public synchronized HttpClientWrapper getClientWrapper() {
    if (m_clientWrapper == null) {
        m_clientWrapper = HttpClientWrapper.create().setSocketTimeout(m_timeout).setConnectionTimeout(m_timeout).setRetries(m_retries).useBrowserCompatibleCookies().dontReuseConnections();
        final HttpPost post = new HttpPost(m_baseURL + "/REST/1.0/user/" + m_user);
        final List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("user", m_user));
        params.add(new BasicNameValuePair("pass", m_password));
        CloseableHttpResponse response = null;
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
            post.setEntity(entity);
            response = m_clientWrapper.execute(post);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode != HttpStatus.SC_OK) {
                throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode);
            } else {
                if (response.getEntity() != null) {
                    EntityUtils.consume(response.getEntity());
                }
                LOG.warn("got user session for username: {}", m_user);
            }
        } catch (final Exception e) {
            LOG.warn("Unable to get session (by requesting user details)", e);
        } finally {
            m_clientWrapper.close(response);
        }
    }
    return m_clientWrapper;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException)

Aggregations

NameValuePair (org.apache.http.NameValuePair)713 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)592 ArrayList (java.util.ArrayList)478 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)256 HttpPost (org.apache.http.client.methods.HttpPost)218 HttpResponse (org.apache.http.HttpResponse)150 IOException (java.io.IOException)125 HttpEntity (org.apache.http.HttpEntity)108 Test (org.junit.Test)85 URI (java.net.URI)79 Map (java.util.Map)72 HashMap (java.util.HashMap)68 HttpGet (org.apache.http.client.methods.HttpGet)66 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)59 UnsupportedEncodingException (java.io.UnsupportedEncodingException)58 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)55 URISyntaxException (java.net.URISyntaxException)52 Document (org.jsoup.nodes.Document)51 URIBuilder (org.apache.http.client.utils.URIBuilder)50 HttpClient (org.apache.http.client.HttpClient)46