Java Code Examples for org.apache.brooklyn.util.http.HttpTool#isStatusCodeHealthy()

The following examples show how to use org.apache.brooklyn.util.http.HttpTool#isStatusCodeHealthy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VaultExternalConfigSupplier.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected JsonObject apiGet(String path, ImmutableMap<String, String> headers) {
    try {
        String uri = Urls.mergePaths(endpoint, path);
        LOG.trace("Vault request - GET: {}", uri);
        HttpToolResponse response = HttpTool.httpGet(httpClient, Urls.toUri(uri), headers);
        LOG.trace("Vault response - code: {} {}", response.getResponseCode(), response.getReasonPhrase());
        String responseBody = new String(response.getContent(), CHARSET_NAME);
        if (HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            return gson.fromJson(responseBody, JsonObject.class);
        } else {
            throw new IllegalStateException("HTTP request returned error");
        }
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 2
Source File: VaultExternalConfigSupplier.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected JsonObject apiPost(String path, ImmutableMap<String, String> headers, ImmutableMap<String, String> requestData) {
    try {
        String body = gson.toJson(requestData);
        String uri = Urls.mergePaths(endpoint, path);
        LOG.trace("Vault request - POST: {}", uri);
        HttpToolResponse response = HttpTool.httpPost(httpClient, Urls.toUri(uri), headers, body.getBytes(CHARSET_NAME));
        LOG.trace("Vault response - code: {} {}", response.getResponseCode(), response.getReasonPhrase());
        String responseBody = new String(response.getContent(), CHARSET_NAME);
        if (HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            return gson.fromJson(responseBody, JsonObject.class);
        } else {
            throw new IllegalStateException("HTTP request returned error");
        }
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 3
Source File: SeaCloudsMonitoringInitializationPolicies.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private void postSeaCloudsDcConfiguration(String requestBody) {

            URI apiEndpoint = URI.create(getConfig(SEACLOUDS_DC_ENDPOINT) + RESOURCES);

            Map<String, String> headers = MutableMap.of(
                    HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString(),
                    HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString());

            HttpToolResponse response = HttpTool
                    .httpPost(HttpTool.httpClientBuilder().build(), apiEndpoint, headers, requestBody.getBytes());

            if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
                throw new RuntimeException("Something went wrong during SeaCloudsDc configuration, "
                        + response.getResponseCode() + ":" + response.getContentAsString());
            }
        }
 
Example 4
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private void installMonitoringRules() {
    LOG.info("SeaCloudsInitializerPolicy is installing T4C Monitoring Rules for " + entity.getId());

    HttpToolResponse response = post(getConfig(T4C_ENDPOINT) + "/v1/monitoring-rules", MediaType.APPLICATION_XML_UTF_8.toString(),
            getConfig(T4C_USERNAME), getConfig(T4C_PASSWORD), BaseEncoding.base64().decode(getConfig(T4C_RULES)));

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong while the monitoring rules installation. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    } else {
        List<String> ruleIds = new ArrayList<>();

        for (MonitoringRule rule : monitoringRules.getMonitoringRules()) {
            ruleIds.add(rule.getId());
        }
        entity.sensors().set(T4C_IDS, ruleIds);
    }
}
 
Example 5
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private void installGrafanaDashboards() {
    try {
        HttpToolResponse response = post(getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db",
                MediaType.JSON_UTF_8.toString(), getConfig(GRAFANA_USERNAME),
                getConfig(GRAFANA_PASSWORD), grafanaInitializerPayload.getBytes());

        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            throw new RuntimeException("Something went wrong while installing Grafana Dashboards. " +
                    "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
        }

        // Retrieving unique slug to be able to remove the Dashboard later
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(response.getContent());
        grafanaDashboardSlug = json.get("slug").asText();
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.warn("Error installingGrafanaDashboards, using " + getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db {}", e);
    }
}
 
Example 6
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(), accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(),
                apiUri,
                MutableMap.of(
                        HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(),
                        HttpHeaders.ACCEPT, "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname="+Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server "+this+" via "+apiUri+": "+response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming {} ({}): {}",
                    new Object[]{apiUri, response.getResponseCode(), response.getContentAsString()});
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using "+apiUri+": "+e, e);
    }
}
 
Example 7
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void installSLA() {
    LOG.info("SeaCloudsInitializerPolicy is installing SLA Agreements for " + entity.getId());

    HttpToolResponse response = post(getConfig(SLA_ENDPOINT) + "/seaclouds/agreements", MediaType.APPLICATION_XML_UTF_8.toString(),
            getConfig(SLA_USERNAME), getConfig(SLA_PASSWORD), BaseEncoding.base64().decode(getConfig(SLA_AGREEMENT)));

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong during the SLA Agreements installation. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    } else {
        entity.sensors().set(SLA_ID, agreement.getAgreementId());
    }

}
 
Example 8
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void notifyRulesReady() {
    LOG.info("SeaCloudsInitializerPolicy is starting to enforce SLA Agreements for " + entity.getId());

    HttpToolResponse response = post(getConfig(SLA_ENDPOINT) + "/seaclouds/commands/rulesready?agreementId=" +
                    agreement.getAgreementId(), MediaType.APPLICATION_XML_UTF_8.toString(),
            getConfig(SLA_USERNAME), getConfig(SLA_PASSWORD), "".getBytes());

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong during the SLA Agreements installation. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    }
}
 
Example 9
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void installInfluxDbObservers() {
    LOG.info("SeaCloudsInitializerPolicy is installing InfluxDB Observers for " + entity.getId());

    for (String metricName : extractMetricNames()) {
        HttpToolResponse response = post(getConfig(T4C_ENDPOINT) + "/v1/metrics/" + metricName + "/observers",
                MediaType.JSON_UTF_8.toString(), getConfig(T4C_USERNAME),
                getConfig(T4C_PASSWORD), observerInitializerPayload.getBytes());

        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            throw new RuntimeException("Something went wrong while attaching the observers to the Rules. " +
                    "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
        }
    }
}
 
Example 10
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void removeGrafanaDashboard() {
    LOG.info("SeaCloudsInitializerPolicy is removing Grafana Dashboard for " + entity.getId());

    HttpToolResponse response = delete(getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db/" + grafanaDashboardSlug,
            MediaType.JSON_UTF_8.toString(), getConfig(GRAFANA_USERNAME), getConfig(GRAFANA_PASSWORD));

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong while removing Grafana Dashboards. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    }
}
 
Example 11
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void removeSlaAgreement() {
    LOG.info("SeaCloudsInitializerPolicy is removing SLA Agreeement for " + entity.getId());

    HttpToolResponse response = delete(getConfig(SLA_ENDPOINT) + "/agreements/" + agreement.getAgreementId(),
            MediaType.APPLICATION_XML_UTF_8.toString(), getConfig(SLA_USERNAME), getConfig(SLA_PASSWORD));

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong while removing the SLA Agreements. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    }
}
 
Example 12
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private void removeMonitoringRules() {
    LOG.info("SeaCloudsInitializerPolicy is removing T4C Monitoring Rules for " + entity.getId());
    for (MonitoringRule rule : monitoringRules.getMonitoringRules()) {
        HttpToolResponse response = delete(getConfig(T4C_ENDPOINT) + "/v1/monitoring-rules/" + rule.getId(),
                MediaType.JSON_UTF_8.toString(), getConfig(T4C_USERNAME), getConfig(T4C_PASSWORD));

        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            throw new RuntimeException("Something went wrong while removing the Monitoring Rules. " +
                    "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
        }
    }

}
 
Example 13
Source File: EntityHttpClient.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Integer input) {
    return HttpTool.isStatusCodeHealthy(input);
}
 
Example 14
Source File: ResourceUtils.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private InputStream getResourceViaHttp(String resource, @Nullable String username, @Nullable String password) throws IOException {
    URI uri = URI.create(resource);
    HttpClientBuilder builder = HttpTool.httpClientBuilder()
            .laxRedirect(true)
            .uri(uri);
    Credentials credentials;
    if (username != null) {
        credentials = new UsernamePasswordCredentials(username, password);
    } else {
        credentials = getUrlCredentials(uri.getRawUserInfo());
    }

    if (credentials != null) {
        builder.credentials(credentials);
    }
    HttpClient client = builder.build();
    HttpResponse result = client.execute(new HttpGet(resource));
    int statusCode = result.getStatusLine().getStatusCode();
    if (HttpTool.isStatusCodeHealthy(statusCode)) {
        HttpEntity entity = result.getEntity();
        if (entity != null) {
            return entity.getContent();
        } else {
            return new ByteArrayInputStream(new byte[0]);
        }
    } else {
        EntityUtils.consume(result.getEntity());
        StringBuilder message = new StringBuilder();
        if (statusCode == 401 && credentials != null) {
            message.append("User '")
                    .append(credentials.getUserPrincipal().getName())
                    .append("' is not authorized to access ")
                    .append(resource);
        } else if (statusCode == 401) {
            message.append("Unable to retrieve ")
                    .append(resource)
                    .append(": unauthorized");
        } else {
            message.append("Invalid response invoking ")
                    .append(resource)
                    .append(": response code ")
                    .append(statusCode);
        }
        throw new IllegalStateException(message.toString());
    }
}