Example usage for com.squareup.okhttp Request urlString

List of usage examples for com.squareup.okhttp Request urlString

Introduction

In this page you can find the example usage for com.squareup.okhttp Request urlString.

Prototype

public String urlString() 

Source Link

Usage

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  .  ja v  a2 s. com
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.graylog2.radio.cluster.Ping.java

License:Open Source License

public void ping() throws IOException {
    final PingRequest pingRequest = PingRequest.create(ourUri.toString());

    final URI uri = serverUri.resolve("/system/radios/" + nodeId + "/ping");
    final Request request = new Request.Builder().url(uri.toURL())
            .put(RequestBody.create(CONTENT_TYPE, objectMapper.writeValueAsBytes(pingRequest))).build();

    final Response r = httpClient.newCall(request).execute();

    // fail on a non-ok status
    if (!r.isSuccessful()) {
        throw new RuntimeException("Expected successful HTTP response [2xx] but got [" + r.code()
                + "]. Request was " + request.urlString());
    }//from w w  w.  jav  a 2s. com
}

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. jav  a2 s  . co  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 {//  ww w. j  av 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 {/*  w ww  . ja  v a  2  s.  c om*/
        // 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.kegbot.api.KegbotApiImpl.java

License:Open Source License

private JsonNode requestJson(Request request) throws KegbotApiException {
    final Response response;
    final long startTime = SystemClock.elapsedRealtime();
    try {/*from   w  w  w. j  a  va 2  s .c  om*/
        response = mClient.newCall(request).execute();
    } catch (IOException e) {
        Log.w(TAG, String.format("--> %s %s [ERR]", request.method(), request.urlString()));
        throw new KegbotApiException(e);
    }
    final long endTime = SystemClock.elapsedRealtime();

    final int responseCode = response.code();
    final String logMessage = String.format("--> %s %s [%s] %sms", request.method(), request.urlString(),
            responseCode, endTime - startTime);
    if (responseCode >= 200 && responseCode < 300) {
        Log.d(TAG, logMessage);
    } else {
        Log.w(TAG, logMessage);
    }
    final ResponseBody body = response.body();

    final JsonNode rootNode;
    try {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            rootNode = mapper.readValue(body.byteStream(), JsonNode.class);
        } finally {
            body.close();
        }
    } catch (JsonParseException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (JsonMappingException e) {
        throw new KegbotApiMalformedResponseException(e);
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }

    boolean success = false;
    try {
        // Handle structural errors.
        if (!rootNode.has("meta")) {
            throw new KegbotApiMalformedResponseException("Response is missing 'meta' field.");
        }
        final JsonNode meta = rootNode.get("meta");
        if (!meta.isContainerNode()) {
            throw new KegbotApiMalformedResponseException("'meta' field is wrong type.");
        }

        final String message;
        if (rootNode.has("error") && rootNode.get("error").has("message")) {
            message = rootNode.get("error").get("message").getTextValue();
        } else {
            message = null;
        }

        // Handle HTTP errors.
        if (responseCode < 200 || responseCode >= 400) {
            switch (responseCode) {
            case 401:
                throw new NotAuthorizedException(message);
            case 404:
                throw new KegbotApi404(message);
            case 405:
                throw new MethodNotAllowedException(message);
            default:
                if (message != null) {
                    throw new KegbotApiServerError(message);
                } else {
                    throw new KegbotApiServerError("Server error, response code=" + responseCode);
                }
            }
        }

        success = true;
        return rootNode;
    } finally {
        if (!success) {
            Log.d(TAG, "Response JSON was: " + rootNode.toString());
        }
    }
}

From source file:org.runbuddy.libtomahawk.infosystem.hatchet.Store.java

License:Open Source License

public JsonElement get(JsonObject object, String memberName) throws IOException {
    JsonElement element = object.get(memberName);
    if (element == null) {
        JsonObject links = object.getAsJsonObject("links");
        if (links != null && links.has(memberName)) {
            Request request = new Request.Builder().url(HATCHET_BASE_URL + links.get(memberName).getAsString())
                    .build();//w  w w  .  j a v a 2s . co m
            Log.d(TAG, "following link: " + request.urlString());
            Response response = mOkHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("API request with URL '" + request.urlString()
                        + "' not successful. Code was " + response.code());
            }
            try {
                element = GsonHelper.get().fromJson(response.body().charStream(), JsonElement.class);
            } catch (JsonIOException | JsonSyntaxException e) {
                throw new IOException(e);
            } finally {
                response.body().close();
            }
        }
    }
    return element;
}

From source file:org.sonarqube.ws.client.HttpConnector.java

License:Open Source License

private HttpResponse doCall(Request okRequest) {
    Call call = okHttpClient.newCall(okRequest);
    try {//from ww  w . j  a  v a  2s  .  c  om
        Response okResponse = call.execute();
        return new HttpResponse(okResponse);
    } catch (IOException e) {
        throw new IllegalStateException("Fail to request " + okRequest.urlString(), e);
    }
}

From source file:retrofit.KGsonConverter.java

License:Apache License

public T fromBody(ResponseBody value, Request request) throws IOException {
    String string = value.string();
    Reader reader = new InputStreamReader((new ByteArrayInputStream(string.getBytes())), Util.UTF_8);
    try {/*  w  ww. j  a  v  a  2s.c  o  m*/
        T t = typeAdapter.fromJson(reader);
        if (t instanceof Result) {
            KResult kResult = (KResult) t;
            if (kResult != null && kResult.isSuccess()) {
                Entry entry = new Entry();

                entry.data = string.getBytes("UTF-8");
                entry.mimeType = value.contentType().toString();
                cache.put(request.urlString(), entry);
            }
        }
        return t;
    } finally {
        Utils.closeQuietly(reader);
    }
}

From source file:retrofit.KOkHttpCall.java

License:Apache License

private Response<T> execCacheRequest(Request request) {
    if (responseConverter instanceof KGsonConverter) {
        KGsonConverter<T> converter = (KGsonConverter<T>) responseConverter;
        Cache cache = converter.getCache();
        if (cache == null) {
            return null;
        }//from  www. j a  v  a2  s .  co m
        Entry entry = cache.get(request.urlString());// ?entry
        if (entry != null && entry.data != null) {// ?
            MediaType contentType = MediaType.parse(entry.mimeType);
            byte[] bytes = entry.data;
            try {
                com.squareup.okhttp.Response rawResponse = new com.squareup.okhttp.Response.Builder()//
                        .code(200).request(request).protocol(Protocol.HTTP_1_1)
                        .body(ResponseBody.create(contentType, bytes)).build();
                return parseResponse(rawResponse, request);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}