Example usage for org.apache.http.client.utils URIBuilder setParameters

List of usage examples for org.apache.http.client.utils URIBuilder setParameters

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder setParameters.

Prototype

public URIBuilder setParameters(final NameValuePair... nvps) 

Source Link

Document

Sets URI query parameters.

Usage

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse caseGetFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {

    URIBuilder getBuilder = new URIBuilder(url);
    if (queryParameters != null) {
        getBuilder.setParameters(queryParameters);
    }/*ww  w . j a v a2s.c o m*/
    HttpGet get = new HttpGet(getBuilder.build());
    get.addHeader("Content-Type", "application/json");
    get.addHeader("Accept", "application/json");
    get.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        return client.execute(get);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse casePatchFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {
    URIBuilder putBuilder = new URIBuilder(url);
    if (queryParameters != null) {
        putBuilder.setParameters(queryParameters);
    }/*from  www .j a va2s. c o  m*/
    HttpPatch patch = new HttpPatch(putBuilder.build());
    patch.setEntity(input);
    patch.addHeader("Content-Type", "application/json");
    patch.addHeader("Accept", "application/json");
    patch.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        return client.execute(patch);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse casePostFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(url);
    if (queryParameters != null) {
        builder.setParameters(queryParameters);
    }//  w  w w . ja v  a  2 s.  c o m

    //ContentType content = ContentType.valueOf(contentType);      
    HttpPost post = new HttpPost(builder.build());
    post.setEntity(input);
    post.addHeader("Content-Type", contentType.getType());
    post.addHeader("Accept", "application/json");
    if (isQuickstart == false)
        post.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();

        return client.execute(post);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}

From source file:com.ibm.iotf.client.api.APIClient.java

private HttpResponse caseDeleteFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {

    URIBuilder deleteBuilder = new URIBuilder(url);
    if (queryParameters != null) {
        deleteBuilder.setParameters(queryParameters);
    }/*from   ww  w .  ja  v a  2s . c om*/

    HttpDelete delete = new HttpDelete(deleteBuilder.build());
    delete.addHeader("Content-Type", "application/json");
    delete.addHeader("Accept", "application/json");
    delete.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        return client.execute(delete);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static HttpGet buildGetMethod(final URI uri, final HttpCollectionSet collectionSet) {
    URI uriWithQueryString = null;
    List<NameValuePair> queryParams = buildRequestParameters(collectionSet);
    try {//from  w  w w .  ja  v a  2 s.co  m
        StringBuffer query = new StringBuffer();
        query.append(URLEncodedUtils.format(queryParams, "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(),
                    Charset.forName("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);
    }
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static URI buildUri(final HttpCollectionSet collectionSet) throws URISyntaxException {
    HashMap<String, String> substitutions = new HashMap<String, String>();
    substitutions.put("ipaddr", InetAddressUtils.str(collectionSet.getAgent().getAddress()));
    substitutions.put("nodeid", Integer.toString(collectionSet.getAgent().getNodeId()));

    final URIBuilder ub = new URIBuilder();
    ub.setScheme(collectionSet.getUriDef().getUrl().getScheme());
    ub.setHost(substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getHost(), "getHost"));
    ub.setPort(collectionSet.getPort());
    ub.setPath(substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getPath(), "getURL"));

    final String query = substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getQuery(),
            "getQuery");
    final List<NameValuePair> params = URLEncodedUtils.parse(query, Charset.forName("UTF-8"));
    ub.setParameters(params);

    ub.setFragment(/*  ww  w  .  jav a2  s .c om*/
            substituteKeywords(substitutions, collectionSet.getUriDef().getUrl().getFragment(), "getFragment"));
    return ub.build();
}

From source file:org.opennms.netmgt.poller.monitors.WebMonitor.java

/** {@inheritDoc} */
@Override/* ww w.  j  a v a2  s.  c  o m*/
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, Charset.forName("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;
}

From source file:org.opennms.netmgt.provision.detector.web.client.WebClient.java

@Override
public void connect(InetAddress address, int port, int timeout) throws IOException, Exception {
    final URIBuilder ub = new URIBuilder();
    ub.setScheme(m_schema);/*w w  w  .  ja va2s  . c o m*/
    ub.setHost(InetAddressUtils.str(address));
    ub.setPort(port);
    ub.setPath(m_path);
    if (m_queryString != null && m_queryString.trim().length() > 0) {
        final List<NameValuePair> params = URLEncodedUtils.parse(m_queryString, Charset.forName("UTF-8"));
        if (!params.isEmpty()) {
            ub.setParameters(params);
        }
    }

    m_httpMethod = new HttpGet(ub.build());
    m_httpMethod.setProtocolVersion(m_version);

    m_httpClientWrapper = HttpClientWrapper.create();
    if (m_overrideSSL) {
        try {
            m_httpClientWrapper.trustSelfSigned("https");
        } catch (final Exception e) {
            LOG.warn("Failed to create relaxed SSL client.", e);
        }
    }
    if (m_userAgent != null && !m_userAgent.trim().isEmpty()) {
        m_httpClientWrapper.setUserAgent(m_userAgent);
    }
    if (timeout > 0) {
        m_httpClientWrapper.setConnectionTimeout(timeout);
        m_httpClientWrapper.setSocketTimeout(timeout);
    }
    if (m_virtualHost != null && !m_virtualHost.trim().isEmpty()) {
        m_httpClientWrapper.setVirtualHost(m_virtualHost);
    }
    if (m_userName != null && !m_userName.trim().isEmpty()) {
        m_httpClientWrapper.addBasicCredentials(m_userName, m_password);
    }
    if (m_authPreemptive) {
        m_httpClientWrapper.usePreemptiveAuth();
    }
}