Example usage for com.squareup.okhttp Response message

List of usage examples for com.squareup.okhttp Response message

Introduction

In this page you can find the example usage for com.squareup.okhttp Response message.

Prototype

String message

To view the source code for com.squareup.okhttp Response message.

Click Source Link

Usage

From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java

License:Apache License

@Override
public <L> void resourcesRemoved(InventoryEvent<L> event) {
    // due to the way inventory sync works and how we are using it, we only care about explicitly
    // removing root resources. We can't individually sync a root resource (because it doesn't exist!)
    // so we remove it here. Any children resources will be synced via discoveryCompleted so we don't
    // do anything in here.
    List<Resource<L>> removedResources = event.getPayload();
    for (Resource<L> removedResource : removedResources) {
        if (removedResource.getParent() == null) {
            try {
                log.debugf("Removing root resource: %s", removedResource);

                MonitoredEndpoint<EndpointConfiguration> endpoint = event.getSamplingService()
                        .getMonitoredEndpoint();
                String endpointTenantId = endpoint.getEndpointConfiguration().getTenantId();
                String tenantIdToUse = (endpointTenantId != null) ? endpointTenantId : config.getTenantId();

                // The final URL should be in the form: entity/<resource_canonical_path>
                // for example: entity/t;hawkular/f;myfeed/r;resource_id

                CanonicalPath resourceCanonicalPath = CanonicalPath.of().tenant(tenantIdToUse).feed(feedId)
                        .resource(removedResource.getID().getIDString()).get();

                StringBuilder deleteUrl = Util.getContextUrlString(config.getUrl(),
                        config.getInventoryContext());
                deleteUrl.append("entity").append(resourceCanonicalPath.toString());

                Request request = httpClientBuilder.buildJsonDeleteRequest(deleteUrl.toString(),
                        getTenantHeader(tenantIdToUse));

                long start = System.currentTimeMillis(); // we don't store this time in our diagnostics
                Response response = httpClientBuilder.getHttpClient().newCall(request).execute();

                try {
                    final long duration = System.currentTimeMillis() - start;

                    if (response.code() != 204 && response.code() != 404) {
                        // 204 means successfully deleted, 404 means it didn't exist in the first place.
                        // In either case, the resource no longer exists which is what we want;
                        // any other response code means it is an error and we didn't remove the resource.
                        throw new Exception("status-code=[" + response.code() + "], reason=["
                                + response.message() + "], url=[" + request.urlString() + "]");
                    }/*from  ww  w  .java  2s  . c o  m*/

                    log.debugf("Took [%d]ms to remove root resource [%s]", duration, removedResource);
                } finally {
                    response.body().close();
                }
            } catch (InterruptedException ie) {
                log.errorFailedToStoreInventoryData(ie);
                Thread.currentThread().interrupt(); // preserve interrupt
            } catch (Exception e) {
                log.errorFailedToStoreInventoryData(e);
                diagnostics.getStorageErrorRate().mark(1);
            }

        }
    }
    return;
}

From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java

License:Apache License

private <L> void performResourceSync(
        InventoryStructure<org.hawkular.inventory.api.model.Resource.Blueprint> resourceStructure,
        String tenantIdToUse, int totalResourceCount) {

    if (resourceStructure.getRoot() != null) {
        try {/*from  w w  w .j a  va 2 s  .c  om*/
            SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build();
            SyncRequest<org.hawkular.inventory.api.model.Resource.Blueprint> sync;
            sync = new SyncRequest<>(syncConfig, resourceStructure);

            StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(),
                    AsyncInventoryStorage.this.config.getInventoryContext());
            url.append("sync");
            url.append("/f;").append(this.feedId);
            url.append("/r;").append(Util.urlEncode(resourceStructure.getRoot().getId()));
            String jsonPayload = Util.toJson(sync);
            Map<String, String> headers = getTenantHeader(tenantIdToUse);

            log.tracef("Syncing [%d] resources to inventory: headers=[%s] body=[%s]", totalResourceCount,
                    headers, jsonPayload);

            Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload);
            Call call = this.httpClientBuilder.getHttpClient().newCall(request);
            final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time();
            Response response = call.execute();

            try {
                final long durationNanos = timer.stop();

                log.tracef("Received sync response from inventory: code [%d]", response.code());

                // HTTP status of 204 means success, anything else is an error
                if (response.code() != 204) {
                    throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message()
                            + "], url=[" + request.urlString() + "]");
                }

                diagnostics.getInventoryRate().mark(totalResourceCount);

                if (log.isDebugEnabled()) {
                    log.debugf("Took [%d]ms to sync [%d] resources to inventory",
                            TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS),
                            totalResourceCount);
                }
            } finally {
                response.body().close();
            }
        } catch (InterruptedException ie) {
            log.errorFailedToStoreInventoryData(ie);
            Thread.currentThread().interrupt(); // preserve interrupt
        } catch (Exception e) {
            log.errorFailedToStoreInventoryData(e);
            diagnostics.getStorageErrorRate().mark(1);
        }
    }

    return;
}

From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java

License:Apache License

private <L> void performResourceTypeSync(
        Offline<org.hawkular.inventory.api.model.ResourceType.Blueprint> resourceTypeStructure,
        String tenantIdToUse) {/*from  ww w.jav a  2  s  .  co m*/

    if (resourceTypeStructure.getRoot() != null) {
        try {
            SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build();
            SyncRequest<org.hawkular.inventory.api.model.ResourceType.Blueprint> sync;
            sync = new SyncRequest<>(syncConfig, resourceTypeStructure);

            StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(),
                    AsyncInventoryStorage.this.config.getInventoryContext());
            url.append("sync");
            url.append("/f;").append(this.feedId);
            url.append("/rt;").append(Util.urlEncode(resourceTypeStructure.getRoot().getId()));
            String jsonPayload = Util.toJson(sync);
            Map<String, String> headers = getTenantHeader(tenantIdToUse);

            log.tracef("Syncing resource type to inventory: headers=[%s] body=[%s]", headers, jsonPayload);

            Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload);
            Call call = this.httpClientBuilder.getHttpClient().newCall(request);
            final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time();
            Response response = call.execute();

            try {
                final long durationNanos = timer.stop();

                log.tracef("Received sync response from inventory: code [%d]", response.code());

                // HTTP status of 204 means success, anything else is an error
                if (response.code() != 204) {
                    throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message()
                            + "], url=[" + request.urlString() + "]");
                }

                diagnostics.getInventoryRate().mark(1);

                if (log.isDebugEnabled()) {
                    log.debugf("Took [%d]ms to sync resource type to inventory",
                            TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS));
                }
            } finally {
                response.body().close();
            }
        } catch (InterruptedException ie) {
            log.errorFailedToStoreInventoryData(ie);
            Thread.currentThread().interrupt(); // preserve interrupt
        } catch (Exception e) {
            log.errorFailedToStoreInventoryData(e);
            diagnostics.getStorageErrorRate().mark(1);
        }
    }

    return;
}

From source file:org.fuse.hawkular.agent.monitor.storage.AsyncInventoryStorage.java

License:Apache License

private <L> void performMetricTypeSync(
        Offline<org.hawkular.inventory.api.model.MetricType.Blueprint> metricTypeStructure,
        String tenantIdToUse) {// w  w w. j  a v a 2 s  . c o  m

    if (metricTypeStructure.getRoot() != null) {
        try {
            SyncConfiguration syncConfig = SyncConfiguration.builder().withAllTypes().build();
            SyncRequest<org.hawkular.inventory.api.model.MetricType.Blueprint> sync;
            sync = new SyncRequest<>(syncConfig, metricTypeStructure);

            StringBuilder url = Util.getContextUrlString(AsyncInventoryStorage.this.config.getUrl(),
                    AsyncInventoryStorage.this.config.getInventoryContext());
            url.append("sync");
            url.append("/f;").append(this.feedId);
            url.append("/mt;").append(Util.urlEncode(metricTypeStructure.getRoot().getId()));
            String jsonPayload = Util.toJson(sync);
            Map<String, String> headers = getTenantHeader(tenantIdToUse);

            log.tracef("Syncing metric type to inventory: headers=[%s] body=[%s]", headers, jsonPayload);

            Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), headers, jsonPayload);
            Call call = this.httpClientBuilder.getHttpClient().newCall(request);
            final Timer.Context timer = diagnostics.getInventoryStorageRequestTimer().time();
            Response response = call.execute();

            try {
                final long durationNanos = timer.stop();

                log.tracef("Received sync response from inventory: code [%d]", response.code());

                // HTTP status of 204 means success, anything else is an error
                if (response.code() != 204) {
                    throw new Exception("status-code=[" + response.code() + "], reason=[" + response.message()
                            + "], url=[" + request.urlString() + "]");
                }

                diagnostics.getInventoryRate().mark(1);

                if (log.isDebugEnabled()) {
                    log.debugf("Took [%d]ms to sync metric type to inventory",
                            TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS));
                }
            } finally {
                response.body().close();
            }
        } catch (InterruptedException ie) {
            log.errorFailedToStoreInventoryData(ie);
            Thread.currentThread().interrupt(); // preserve interrupt
        } catch (Exception e) {
            log.errorFailedToStoreInventoryData(e);
            diagnostics.getStorageErrorRate().mark(1);
        }
    }

    return;
}

From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java

License:Apache License

@Override
public void store(MetricDataPayloadBuilder payloadBuilder, long waitMillis) {
    String jsonPayload = "?";

    try {/* w w  w. j av  a  2  s  . com*/
        // Determine what tenant header to use.
        // If no tenant override is specified in the payload, use the agent's tenant ID.
        Map<String, String> tenantIdHeader;
        String metricTenantId = payloadBuilder.getTenantId();
        if (metricTenantId == null) {
            tenantIdHeader = agentTenantIdHeader;
        } else {
            tenantIdHeader = getTenantHeader(metricTenantId);
        }

        // get the payload in JSON format
        jsonPayload = payloadBuilder.toPayload().toString();

        // build the REST URL...
        StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext());
        url.append("metrics/data");

        // now send the REST request
        Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), tenantIdHeader,
                jsonPayload);

        final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1);
        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                try {
                    log.errorFailedToStoreMetricData(e, jsonPayloadFinal);
                    diagnostics.getStorageErrorRate().mark(1);
                } finally {
                    if (latch != null) {
                        latch.countDown();
                    }
                }
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    // HTTP status of 200 means success; anything else is an error
                    if (response.code() != 200) {
                        IOException e = new IOException("status-code=[" + response.code() + "], reason=["
                                + response.message() + "], url=[" + request.urlString() + "]");
                        log.errorFailedToStoreMetricData(e, jsonPayloadFinal);
                        diagnostics.getStorageErrorRate().mark(1);
                    } else {
                        // looks like everything stored successfully
                        diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints());
                    }
                } finally {
                    if (latch != null) {
                        latch.countDown();
                    }
                    response.body().close();
                }
            }
        });

        if (latch != null) {
            latch.await(waitMillis, TimeUnit.MILLISECONDS);
        }

    } catch (Throwable t) {
        log.errorFailedToStoreMetricData(t, jsonPayload);
        diagnostics.getStorageErrorRate().mark(1);
    }
}

From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java

License:Apache License

@Override
public void store(AvailDataPayloadBuilder payloadBuilder, long waitMillis) {
    String jsonPayload = "?";

    try {/* w  w w .j  a va2  s. c  o  m*/
        // Determine what tenant header to use.
        // If no tenant override is specified in the payload, use the agent's tenant ID.
        Map<String, String> tenantIdHeader;
        String metricTenantId = payloadBuilder.getTenantId();
        if (metricTenantId == null) {
            tenantIdHeader = agentTenantIdHeader;
        } else {
            tenantIdHeader = getTenantHeader(metricTenantId);
        }

        // get the payload in JSON format
        jsonPayload = payloadBuilder.toPayload().toString();

        // build the REST URL...
        StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext());
        url.append("availability/data");

        // now send the REST request
        Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), tenantIdHeader,
                jsonPayload);

        final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1);
        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                try {
                    log.errorFailedToStoreAvailData(e, jsonPayloadFinal);
                    diagnostics.getStorageErrorRate().mark(1);
                } finally {
                    if (latch != null) {
                        latch.countDown();
                    }
                }
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    // HTTP status of 200 means success; anything else is an error
                    if (response.code() != 200) {
                        IOException e = new IOException("status-code=[" + response.code() + "], reason=["
                                + response.message() + "], url=[" + request.urlString() + "]");
                        log.errorFailedToStoreAvailData(e, jsonPayloadFinal);
                        diagnostics.getStorageErrorRate().mark(1);
                    } else {
                        // looks like everything stored successfully
                        diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints());
                    }
                } finally {
                    if (latch != null) {
                        latch.countDown();
                    }
                    response.body().close();
                }
            }
        });

        if (latch != null) {
            latch.await(waitMillis, TimeUnit.MILLISECONDS);
        }

    } catch (Throwable t) {
        log.errorFailedToStoreAvailData(t, jsonPayload);
        diagnostics.getStorageErrorRate().mark(1);
    }
}

From source file:org.fuse.hawkular.agent.monitor.storage.HawkularStorageAdapter.java

License:Apache License

@Override
public void store(MetricTagPayloadBuilder payloadBuilder, long waitMillis) {
    Map<String, String> jsonPayloads = null;

    try {/*from  ww w.  j  a va 2s  . c  o  m*/
        // Determine what tenant header to use.
        // If no tenant override is specified in the payload, use the agent's tenant ID.
        Map<String, String> tenantIdHeader;
        String metricTenantId = payloadBuilder.getTenantId();
        if (metricTenantId == null) {
            tenantIdHeader = agentTenantIdHeader;
        } else {
            tenantIdHeader = getTenantHeader(metricTenantId);
        }

        // get the payload(s)
        jsonPayloads = payloadBuilder.toPayload();

        // build the REST URL...
        String url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext()).toString();

        // The way the metrics REST API works is you can only add tags for one metric at a time
        // so loop through each metric ID and send one REST request for each one.
        for (Map.Entry<String, String> jsonPayload : jsonPayloads.entrySet()) {
            String relativePath = jsonPayload.getKey(); // this identifies the metric (e.g. "gauges/<id>")
            String tagsJson = jsonPayload.getValue();
            String currentUrl = url + relativePath + "/tags";

            // now send the REST request
            Request request = this.httpClientBuilder.buildJsonPutRequest(currentUrl, tenantIdHeader, tagsJson);
            final CountDownLatch latch = (waitMillis <= 0) ? null : new CountDownLatch(1);

            this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    try {
                        log.errorFailedToStoreMetricTags(e, tagsJson);
                        diagnostics.getStorageErrorRate().mark(1);
                    } finally {
                        if (latch != null) {
                            latch.countDown();
                        }
                    }
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        // HTTP status of 200 means success; anything else is an error
                        if (response.code() != 200) {
                            IOException e = new IOException("status-code=[" + response.code() + "], reason=["
                                    + response.message() + "], url=[" + request.urlString() + "]");
                            log.errorFailedToStoreMetricTags(e, tagsJson);
                            diagnostics.getStorageErrorRate().mark(1);
                        }
                    } finally {
                        if (latch != null) {
                            latch.countDown();
                        }
                        response.body().close();
                    }
                }
            });

            if (latch != null) {
                latch.await(waitMillis, TimeUnit.MILLISECONDS);
            }
        }

    } catch (Throwable t) {
        log.errorFailedToStoreMetricTags(t, (jsonPayloads == null) ? "?" : jsonPayloads.toString());
        diagnostics.getStorageErrorRate().mark(1);
    }
}

From source file:org.fuse.hawkular.agent.MonitorService.java

License:Apache License

private void waitForHawkularServer() throws Exception {
    OkHttpClient httpclient = this.httpClientBuilder.getHttpClient();

    String statusUrl = Util.getContextUrlString(subsystemConfiguration.getStorageAdapter().getUrl(),
            subsystemConfiguration.getStorageAdapter().getMetricsContext()).append("status").toString();
    Request request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null);
    while (true) {
        Response response = null;
        try {//from ww  w.  j  a va 2s .co m
            response = httpclient.newCall(request).execute();
            if (response.code() != 200) {
                log.debugf("Hawkular Metrics is not ready yet: %d/%s", response.code(), response.message());
            } else {
                log.debugf("Hawkular Metrics is ready: %s", response.body().string());
                break;
            }
        } catch (Exception e) {
            log.debugf("Hawkular Metrics is not ready yet: %s", e.toString());
        } finally {
            if (response != null) {
                response.body().close();
            }
        }
        Thread.sleep(5000L);
    }

    if (this.subsystemConfiguration.getStorageAdapter().getType().toString().equals("HAWKULAR")) {
        statusUrl = Util
                .getContextUrlString(subsystemConfiguration.getStorageAdapter().getUrl(),
                        subsystemConfiguration.getStorageAdapter().getInventoryContext())
                .append("status").toString();
        request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null);
        while (true) {
            Response response = null;
            try {
                response = httpclient.newCall(request).execute();
                if (response.code() != 200) {
                    log.debugf("Hawkular Inventory is not ready yet: %d/%s", response.code(),
                            response.message());
                } else {
                    log.debugf("Hawkular Inventory is ready: %s", response.body().string());
                    break;
                }
            } catch (Exception e) {
                log.debugf("Hawkular Inventory is not ready yet: %s", e.toString());
            } finally {
                if (response != null) {
                    response.body().close();
                }
            }
            Thread.sleep(5000L);
        }
    }
}

From source file:org.fuse.hawkular.agent.MonitorService.java

License:Apache License

/**
 * Registers the feed with the Hawkular system under the given tenant.
 * Note, it is OK to re-register the same feed/tenant combinations.
 *
 * If retryMillis > 0 then this will not return until the feed is properly registered.
 * If the Hawkular server is not up, this could mean we are stuck here for a long time.
 *
 * @param tenantId the feed is registered under the given tenantId
 * @param retryMillis if >0 the amount of millis to elapse before retrying
 * @throws Exception if failed to register feed
 *//*w  w w .jav  a 2 s  . c  o m*/
public void registerFeed(String tenantId, int retryMillis) throws Exception {
    // get the payload in JSON format
    Feed.Blueprint feedPojo = new Feed.Blueprint(this.feedId, null);
    String jsonPayload = Util.toJson(feedPojo);

    // build the REST URL...
    // start with the protocol, host, and port, plus context
    StringBuilder url = Util.getContextUrlString(subsystemConfiguration.getStorageAdapter().getUrl(),
            subsystemConfiguration.getStorageAdapter().getInventoryContext());

    // rest of the URL says we want the feeds API
    url.append("entity/feed");

    // now send the REST requests - one for each tenant to register
    OkHttpClient httpclient = this.httpClientBuilder.getHttpClient();

    Map<String, String> header = Collections.singletonMap("Hawkular-Tenant", tenantId);
    Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(), header, jsonPayload);

    boolean keepRetrying = (retryMillis > 0);
    do {
        try {
            // note that we retry if newCall.execute throws an exception (assuming we were told to retry)
            Response httpResponse = httpclient.newCall(request).execute();

            try {
                // HTTP status of 201 means success; 409 means it already exists, anything else is an error
                if (httpResponse.code() == 201) {
                    keepRetrying = false;
                    final String feedObjectFromServer = httpResponse.body().string();
                    final Feed feed = Util.fromJson(feedObjectFromServer, Feed.class);
                    if (this.feedId.equals(feed.getId())) {
                        log.infoUsingFeedId(feed.getId(), tenantId);
                    } else {
                        // do not keep retrying - this is a bad error; we need to abort
                        log.errorUnwantedFeedId(feed.getId(), this.feedId, tenantId);
                        throw new Exception(String.format("Received unwanted feed [%s]", feed.getId()));
                    }
                } else if (httpResponse.code() == 409) {
                    keepRetrying = false;
                    log.infoFeedIdAlreadyRegistered(this.feedId, tenantId);
                } else if (httpResponse.code() == 404) {
                    // the server is probably just starting to come up - wait for it if we were told to retry
                    keepRetrying = (retryMillis > 0);
                    throw new Exception(String.format("Is the Hawkular Server booting up? (%d=%s)",
                            httpResponse.code(), httpResponse.message()));
                } else {
                    // futile to keep retrying and getting the same 500 or whatever error
                    keepRetrying = false;
                    throw new Exception(String.format("status-code=[%d], reason=[%s]", httpResponse.code(),
                            httpResponse.message()));
                }
            } finally {
                httpResponse.body().close();
            }
        } catch (Exception e) {
            log.warnCannotRegisterFeed(this.feedId, tenantId, request.urlString(), e.toString());
            if (keepRetrying) {
                Thread.sleep(retryMillis);
            } else {
                throw e;
            }
        }
    } while (keepRetrying);
}

From source file:org.hawkular.agent.monitor.scheduler.OpsGroupRunnable.java

License:Apache License

private void submitResult(String operationId, String tenantId, OpsResult result) throws Exception {

    Request request;/*from  w w  w  . j a va2 s .co m*/

    String uri = baseuri + "/" + selfIdentifiers.getFullIdentifier() + "/" + operationId;
    String json = Util.toJson(result);
    RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json);

    request = new Request.Builder().url(uri).post(body).addHeader("Hawkular-Tenant", tenantId).build();

    // Asynchronous POST
    httpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            LOG.warn("Sending of response failed: " + e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.code() != 200) {
                LOG.warn("Send failed : " + response.message());
            }

        }
    });
}