Search in sources :

Example 11 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project gocd by gocd.

the class MingleConfig method urlFor.

public String urlFor(String path) throws MalformedURLException, URISyntaxException {
    URIBuilder baseUri = new URIBuilder(baseUrl);
    String originalPath = baseUri.getPath();
    if (originalPath == null) {
        originalPath = "";
    }
    if (originalPath.endsWith(DELIMITER) && path.startsWith(DELIMITER)) {
        path = path.replaceFirst(DELIMITER, "");
    }
    return baseUri.setPath(originalPath + path).toString();
}
Also used : URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 12 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project infoarchive-sip-sdk by Enterprise-Content-Management.

the class InfoArchiveRestClient method fetchContent.

@Override
public ContentResult fetchContent(String contentId) throws IOException {
    try {
        String contentResource = resourceCache.getCiResourceUri();
        URIBuilder builder = new URIBuilder(contentResource);
        builder.setParameter("cid", contentId);
        URI uri = builder.build();
        return restClient.get(uri.toString(), contentResultFactory);
    } catch (URISyntaxException e) {
        throw new IllegalStateException("Failed to create content resource uri.", e);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 13 with URIBuilder

use of org.apache.http.client.utils.URIBuilder 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 {
        StringBuffer query = new StringBuffer();
        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 14 with URIBuilder

use of org.apache.http.client.utils.URIBuilder in project opennms by OpenNMS.

the class GrafanaDashletConfigurationWindow method getGrafanaDashboards.

private Map<String, String> getGrafanaDashboards() throws GrafanaDashletException {
    /**
         * Loading the required properties...
         */
    final String grafanaApiKey = System.getProperty("org.opennms.grafanaBox.apiKey", "");
    final String grafanaProtocol = System.getProperty("org.opennms.grafanaBox.protocol", "http");
    final String grafanaHostname = System.getProperty("org.opennms.grafanaBox.hostname", "localhost");
    final int grafanaPort = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.port", "3000"));
    final int grafanaConnectionTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.connectionTimeout", "500"));
    final int grafanaSoTimeout = Integer.parseInt(System.getProperty("org.opennms.grafanaBox.soTimeout", "500"));
    if (!"".equals(grafanaApiKey) && !"".equals(grafanaHostname) && !"".equals(grafanaProtocol) && ("http".equals(grafanaProtocol) || "https".equals(grafanaProtocol))) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(grafanaConnectionTimeout).setSocketTimeout(grafanaSoTimeout).build();
            final URI uri = new URIBuilder().setScheme(grafanaProtocol).setHost(grafanaHostname).setPort(grafanaPort).setPath("/api/search/").build();
            final HttpGet httpGet = new HttpGet(uri);
            httpGet.setConfig(requestConfig);
            /**
                 * Adding the API key...
                 */
            httpGet.setHeader("Authorization", "Bearer " + grafanaApiKey);
            final Map<String, String> resultSet = new TreeMap<>();
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    /**
                         * Fill the result set...
                         */
                    final String responseString = IOUtils.toString(httpEntity.getContent(), StandardCharsets.UTF_8.name());
                    if (!Strings.isNullOrEmpty(responseString)) {
                        try {
                            final JSONArray arr = new JSONObject("{dashboards:" + responseString + "}").getJSONArray("dashboards");
                            for (int i = 0; i < arr.length(); i++) {
                                resultSet.put(arr.getJSONObject(i).getString("title"), arr.getJSONObject(i).getString("uri"));
                            }
                        } catch (JSONException e) {
                            throw new GrafanaDashletException(e.getMessage());
                        }
                    }
                }
            }
            return resultSet;
        } catch (Exception e) {
            throw new GrafanaDashletException(e.getMessage());
        }
    } else {
        throw new GrafanaDashletException("Invalid configuration");
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) TreeMap(java.util.TreeMap) URI(java.net.URI) JSONException(org.json.JSONException) URIBuilder(org.apache.http.client.utils.URIBuilder) JSONObject(org.json.JSONObject) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 15 with URIBuilder

use of org.apache.http.client.utils.URIBuilder 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)

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