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.hawkular.agent.monitor.service.MonitorService.java

License:Apache License

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

    String statusUrl = Util.getContextUrlString(configuration.getStorageAdapter().getUrl(),
            configuration.getStorageAdapter().getMetricsContext()).append("status").toString();
    Request request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null);
    int counter = 0;
    while (true) {
        Response response = null;
        try {/*from  w  w w .  j  ava2s.  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);
        counter++;
        if (counter % 12 == 0) {
            log.warnConnectionDelayed(counter, "metrics", statusUrl);
        }
    }

    if (this.configuration.getStorageAdapter().getType() == StorageReportTo.HAWKULAR) {
        statusUrl = Util.getContextUrlString(configuration.getStorageAdapter().getUrl(),
                configuration.getStorageAdapter().getInventoryContext()).append("status").toString();
        request = this.httpClientBuilder.buildJsonGetRequest(statusUrl, null);
        counter = 0;
        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);
            counter++;
            if (counter % 5 == 0) {
                log.warnConnectionDelayed(counter, "inventory", statusUrl);
            }
        }
    }
}

From source file:org.hawkular.agent.monitor.service.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
 *//*www .  j  a  va  2s .  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(configuration.getStorageAdapter().getUrl(),
            configuration.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.storage.MetricsOnlyStorageAdapter.java

License:Apache License

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

    try {/* w w  w  .  j  a  v  a2  s.  c o  m*/
        // 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(),
                Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload);

        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                log.errorFailedToStoreMetricData(e, jsonPayloadFinal);
                diagnostics.getStorageErrorRate().mark(1);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // 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);
                    throw e;
                }

                // looks like everything stored successfully
                diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints());

            }
        });

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

From source file:org.hawkular.agent.monitor.storage.MetricsOnlyStorageAdapter.java

License:Apache License

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

    try {/*from   w  w w . j av a 2 s .co  m*/
        // 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(),
                Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload);

        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                log.errorFailedToStoreAvailData(e, jsonPayloadFinal);
                diagnostics.getStorageErrorRate().mark(1);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // 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);
                    throw e;
                }

                // looks like everything stored successfully
                diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints());

            }
        });

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

From source file:org.hawkular.commons.rest.status.itest.StatusEndpointITest.java

License:Apache License

@Test(groups = { GROUP })
public void testStatusEndpoint() throws IOException, InterruptedException {

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().addHeader("Accept", "application/json").url(statusUrl).build();

    Response response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        String foundBody = response.body().string();

        /* see src/test/resources/rest-status/MANIFEST.MF */
        String expected = "{\"Implementation-Version\":\"1.2.3.4\","//
                + "\"Built-From-Git-SHA1\":\"cofeebabe\","//
                + "\"testKey1\":\"testValue1\"}";
        Assert.assertEquals(foundBody, expected);
    } else {//from   w w w. j a  va  2 s.co m
        Assert.fail("Could not get [" + statusUrl + "]: " + response.code() + " " + response.message());
    }

}

From source file:org.hawkular.wildfly.agent.itest.util.AbstractITest.java

License:Apache License

protected String getWithRetries(String url, int attemptCount, long attemptDelay) throws Throwable {
    Throwable e = null;/*from  w  w  w .j av  a  2s . c  om*/
    for (int i = 0; i < attemptCount; i++) {
        try {
            Request request = newAuthRequest().url(url).build();
            Response response = client.newCall(request).execute();
            System.out.println("Got code " + response.code() + " and message [" + response.message()
                    + "] retries: " + url);
            AssertJUnit.assertEquals(200, response.code());
            System.out.println("Got after " + (i + 1) + " retries: " + url);
            return response.body().string();
        } catch (Throwable t) {
            /* some initial attempts may fail */
            e = t;
        }
        System.out.println("URL [" + url + "] not ready yet on " + (i + 1) + " of " + attemptCount
                + " attempts, about to retry after " + attemptDelay + " ms");
        Thread.sleep(attemptDelay);
    }
    if (e != null) {
        throw e;
    } else {
        throw new AssertionError("Could not get [" + url + "]");
    }
}

From source file:org.jamienicol.episodes.tvdb.Client.java

License:Open Source License

public List<Show> searchShows(String query) {

    try {//w w  w  .  j a  v a2s.  c om
        final String escapedQuery = URLEncoder.encode(query, "UTF-8");
        final String url = String.format("%s/GetSeries.php?seriesname=%s", baseUrl, escapedQuery);
        Log.d(TAG, String.format("Sending request to %s", url));

        final Request request = new Request.Builder().url(url).build();

        final Response response = http.newCall(request).execute();

        Log.d(TAG, String.format("Received response %d: %s", response.code(), response.message()));

        if (response.isSuccessful()) {
            final SearchShowsParser parser = new SearchShowsParser();

            return parser.parse(response.body().byteStream());
        } else {
            return null;
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}

From source file:org.jamienicol.episodes.tvdb.Client.java

License:Open Source License

public Show getShow(int id) {
    try {//from  w  ww.  j  av  a 2  s.com
        final String url = String.format(Locale.US, "%s/%s/series/%d/all/en.xml", baseUrl, apiKey, id);
        Log.d(TAG, String.format("Sending request to %s", url));

        final Request request = new Request.Builder().url(url).build();

        final Response response = http.newCall(request).execute();

        Log.d(TAG, String.format("Received response %d: %s", response.code(), response.message()));

        if (response.isSuccessful()) {
            final GetShowParser parser = new GetShowParser();

            return parser.parse(response.body().byteStream());
        } else {
            return null;
        }
    } catch (IOException e) {
        Log.w(TAG, e);
        return null;
    }
}

From source file:org.jboss.arquillian.ce.proxy.AbstractProxy.java

License:Open Source License

public <T> T post(String url, Class<T> returnType, Object requestObject) throws Exception {
    final OkHttpClient httpClient = getHttpClient();

    Request.Builder builder = new Request.Builder();
    builder.url(url);//from w ww .j  ava  2 s  .c o m

    if (requestObject != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(requestObject);
            oos.flush();
        } catch (Exception e) {
            throw new RuntimeException("Error sending request Object, " + requestObject, e);
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), baos.toByteArray());
        builder.post(body);
    }

    Request request = builder.build();
    Response response = httpClient.newCall(request).execute();

    int responseCode = response.code();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        Object o;
        try (ObjectInputStream ois = new ObjectInputStream(response.body().byteStream())) {
            o = ois.readObject();
        }

        if (returnType.isInstance(o) == false) {
            throw new IllegalStateException(
                    "Error reading results, expected a " + returnType.getName() + " but got " + o);
        }

        return returnType.cast(o);
    } else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
        return null;
    } else if (responseCode != HttpURLConnection.HTTP_NOT_FOUND) {
        throw new IllegalStateException(
                "Error launching test at " + url + ". Got " + responseCode + " (" + response.message() + ")");
    }

    return null; // TODO
}

From source file:org.jclouds.http.okhttp.OkHttpCommandExecutorService.java

License:Apache License

@Override
protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {
    OkHttpClient requestScopedClient = globalClient.clone();
    requestScopedClient.setProxy(proxyForURI.apply(nativeRequest.uri()));

    Response response = requestScopedClient.newCall(nativeRequest).execute();

    HttpResponse.Builder<?> builder = HttpResponse.builder();
    builder.statusCode(response.code());
    builder.message(response.message());

    Builder<String, String> headerBuilder = ImmutableMultimap.builder();
    Headers responseHeaders = response.headers();
    for (String header : responseHeaders.names()) {
        headerBuilder.putAll(header, responseHeaders.values(header));
    }/*from  w  w  w  .  j  a v  a 2  s  .c  o m*/

    ImmutableMultimap<String, String> headers = headerBuilder.build();

    if (response.code() == 204 && response.body() != null) {
        response.body().close();
    } else {
        Payload payload = newInputStreamPayload(response.body().byteStream());
        contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);
        builder.payload(payload);
    }

    builder.headers(filterOutContentHeaders(headers));

    return builder.build();
}