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:me.lock8.Mzigo.java

License:Apache License

private boolean checkForDuplicatedRequest(final Request request) {

    final Call ongoingCall;
    if (request.method().equalsIgnoreCase("GET")
            && (ongoingCall = ongoingCallForPath(request.urlString())) != null) {

        if (duplicatedRequestPolicy == DUPLICATED_REQUEST_POLICY_CANCEL_ONGOING) {
            ongoingCall.cancel();//from  w  ww  .  j a  v a 2  s .c om
            return false;
        } else {
            return true;
        }
    }
    return false;
}

From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java

License:Open Source License

public <S> S request(Class<S> service, String username, String password) {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(60, TimeUnit.SECONDS);
    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.interceptors().add(new AuthenticationInterceptor(username, password));
    client.interceptors().add(new Interceptor() {
        @Override/*from  w ww  . j  a v  a 2s .c om*/
        public Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Request request = chain.request();
            Response response = chain.proceed(request);

            int retryCount = 0;
            while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) {
                Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
                response = chain.proceed(request);
                retryCount++;
            }
            if (!response.isSuccessful())
                log.error(request.urlString() + " request failed.");

            return response;
        }
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new TaskboardJacksonModule());
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl())
            .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build();

    return retrofit.create(service);
}

From source file:org.chromium.cronet_sample_apk.CronetSampleActivity.java

License:Open Source License

private void makeRequest(Request request) {
    final Request mRequest = request;
    if (OkHttpSynchronousFlag) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Response response = mOKHttpClient.newCall(mRequest).execute();
                    final String receivedData = response.body().string();
                    final String url = mRequest.urlString();
                    final String text = "Completed " + url + " (" + response.code() + ")";
                    CronetSampleActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mOkhttpResultText.setText(text);
                            mOkhttpReceiveDataText.setText(receivedData);

                        }/*  www .  ja  v a2  s . co m*/
                    });
                    if (!OKHttpFinishFlag) {
                        OKHttpFinishFlag = true;
                        Log.d(TAG, "set okhttp finish flag to true");
                    }
                } catch (IOException e) {
                    final String url = mRequest.urlString();
                    final String text = "Failed " + url + " (" + e.getMessage() + ")";
                    CronetSampleActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mOkhttpResultText.setText(text);

                        }
                    });
                    if (!OKHttpFinishFlag) {
                        OKHttpFinishFlag = true;
                        Log.d(TAG, "set okhttp finish flag to true");
                    }
                }
            }
        }).start();
    } else {
        mOKHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                final String url = mUrl;
                final String text = "Failed " + url + " (" + e.getMessage() + ")";
                CronetSampleActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mOkhttpResultText.setText(text);

                    }
                });
                if (!OKHttpFinishFlag) {
                    OKHttpFinishFlag = true;
                    Log.d(TAG, "set okhttp finish flag to true");
                }

            }

            @Override
            public void onResponse(Response response) throws IOException {

                final String receivedData = response.body().string();
                Log.d(TAG, receivedData);
                final String url = mUrl;
                final String text = "Completed " + url + " (" + response.code() + ")";
                CronetSampleActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mOkhttpResultText.setText(text);
                        mOkhttpReceiveDataText.setText(receivedData);
                    }
                });
                if (!OKHttpFinishFlag) {
                    OKHttpFinishFlag = true;
                    Log.d(TAG, "set okhttp finish flag to true");
                }

            }
        });
    }
}

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() + "]");
                    }/* www  .j  ava2s.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 {/*w  ww  .j a v  a  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   w  ww  .  j  a va2  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 2s . 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 {//from ww  w. j a v a  2 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("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  ww . j  a v a 2s  . co 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  w  w w.  j av  a  2 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(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);
    }
}