Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

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

Click Source Link

Usage

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Adds one or more data points for multiple counters all at once!
 * @param tenantId/*from   w ww . j a  va  2s .  com*/
 * @param data
 */
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) {
    try {
        URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$
        Request request = new Request.Builder().url(endpoint).post(toBody(data))
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Gets a list of buckets containing aggregate information about data in the
 * indicated counter.  The number of buckets is determined by the bucket size
 * and date/time range specified.//w  ww  .  j a v a2 s  .  c o  m
 * @param tenantId
 * @param counterId
 * @param from
 * @param to
 * @param bucketSize
 */
@SuppressWarnings("nls")
public List<BucketDataPointBean> getCounterData(String tenantId, String counterId, Date from, Date to,
        BucketSizeType bucketSize) {
    try {
        StringBuilder params = new StringBuilder();
        params.append("?").append("start=").append(from.getTime()).append("&end=").append(to.getTime())
                .append("&bucketDuration=").append(bucketSize.getValue());
        URL endpoint = serverUrl.toURI().resolve("counters/" + counterId + "/stats" + params.toString()) //$NON-NLS-1$
                .toURL();
        Request request = new Request.Builder().url(endpoint).header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
        if (response.code() == 204) {
            return Collections.EMPTY_LIST;
        }
        String responseBody = response.body().string();
        return readMapper.reader(new TypeReference<List<BucketDataPointBean>>() {
        }).readValue(responseBody);
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Gets a list of buckets containing aggregate information about data in the
 * indicated counter.  The number of buckets is passed in, the size of each
 * bucket is determined by the number asked for and the time range.
 * @param tenantId//from  ww  w  .  ja va  2 s.c o m
 * @param counterId
 * @param from
 * @param to
 * @param bucketSize
 */
@SuppressWarnings("nls")
public List<BucketDataPointBean> getCounterData(String tenantId, String counterId, Date from, Date to,
        int numBuckets) {
    try {
        StringBuilder params = new StringBuilder();
        params.append("?").append("start=").append(from.getTime()).append("&end=").append(to.getTime())
                .append("&buckets=").append(numBuckets);
        URL endpoint = serverUrl.toURI().resolve("counters/" + counterId + "/stats" + params.toString()) //$NON-NLS-1$
                .toURL();
        Request request = new Request.Builder().url(endpoint).header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
        if (response.code() == 204) {
            return Collections.EMPTY_LIST;
        }
        String responseBody = response.body().string();
        return readMapper.reader(new TypeReference<List<BucketDataPointBean>>() {
        }).readValue(responseBody);
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.common.net.hawkular.HawkularMetricsClient.java

License:Apache License

/**
 * Gets a list of buckets containing aggregate information about data in the
 * indicated counter.  The buckets returned are based on the values of the tag(s)
 * provided./*  ww  w  . jav  a  2s  .  c o m*/
 * @param tenantId
 * @param counterId
 * @param from
 * @param to
 * @param bucketSize
 */
@SuppressWarnings("nls")
public Map<String, BucketDataPointBean> getCounterData(String tenantId, String counterId, Date from, Date to,
        Map<String, String> tags) {
    try {
        StringBuilder params = new StringBuilder();
        params.append("?").append("start=").append(from.getTime()).append("&end=").append(to.getTime());
        URL endpoint = serverUrl.toURI()
                .resolve("counters/" + counterId + "/stats/tags/" + encodeTags(tags) + params.toString()) //$NON-NLS-1$
                .toURL();
        Request request = new Request.Builder().url(endpoint).header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$
                .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.code() >= 400) {
            throw hawkularMetricsError(response);
        }
        if (response.code() == 204) {
            return Collections.EMPTY_MAP;
        }
        String responseBody = response.body().string();
        return readMapper.reader(new TypeReference<Map<String, BucketDataPointBean>>() {
        }).readValue(responseBody);
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ok.HttpURLConnectionImpl.java

License:Apache License

private static String responseSourceHeader(Response response) {
    if (response.networkResponse() == null) {
        if (response.cacheResponse() == null) {
            return "NONE";
        }/*  w  w  w  . j a v  a 2 s . c o  m*/
        return "CACHE " + response.code();
    }
    if (response.cacheResponse() == null) {
        return "NETWORK " + response.code();
    }
    return "CONDITIONAL_CACHE " + response.networkResponse().code();
}

From source file:io.apptik.comm.jus.okhttp.OkHttpStack.java

License:Apache License

@Override
public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders,
        ByteArrayPool byteArrayPool) throws IOException {

    //clone to be able to set timeouts per call
    OkHttpClient client = this.client.clone();
    client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit.MILLISECONDS);
    com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder()
            .url(request.getUrlString()).headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders))
            .tag(request.getTag()).method(request.getMethod(), JusOk.okBody(request.getNetworkRequest()))
            .build();/*from w w  w .j  a va2s . c o  m*/

    long requestStart = System.nanoTime();

    Response response = client.newCall(okRequest).execute();

    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) {
        data = getContentBytes(response.body().source(), byteArrayPool, (int) response.body().contentLength());
    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder().setHeaders(JusOk.jusHeaders(response.headers()))
            .setStatusCode(response.code()).setBody(data).setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}

From source file:io.fabric8.docker.client.impl.EventHandle.java

License:Apache License

@Override
public void onResponse(Response r) throws IOException {
    response.set(r);//from   w  w  w.  java  2 s .c o  m
    if (r.code() == 200) {
        InputStreamPumper pumper = new InputStreamPumper(r.body().byteStream(), new Callback<byte[], Void>() {
            @Override
            public Void call(byte[] data) {
                onEvent(new String(data));
                return null;
            }
        }, new Callback<Boolean, Void>() {
            @Override
            public Void call(Boolean success) {
                if (success) {
                    if (succeded.compareAndSet(false, true) && !failed.get()) {
                        listener.onSuccess("Done.");
                    }
                } else {
                    if (failed.compareAndSet(false, true)) {
                        listener.onError("Failed.");
                    }
                }
                return null;
            }
        });
        closeables.add(pumper);
        executorService.submit(pumper);
    } else {
        onFailure(r.request(), new IOException(r.body().string()));
    }
    latch.countDown();
}

From source file:io.fabric8.docker.client.impl.OperationSupport.java

License:Apache License

protected <T> List<T> handleList(URL resourceUrl, Class<T> type)
        throws ExecutionException, InterruptedException, DockerClientException, IOException {
    Request request = new Request.Builder().get().url(resourceUrl).build();
    Response response = null;
    try {//from   w w  w .j av a2 s .co m
        response = client.newCall(request).execute();
    } catch (Exception e) {
        throw requestException(request, e);
    }

    if (response.code() == 404) {
        return Collections.emptyList();
    }
    assertResponseCodes(request, response, new int[] { 200, 404 });
    if (type != null) {
        return JSON_MAPPER.readValue(response.body().byteStream(),
                JSON_MAPPER.getTypeFactory().constructCollectionType(List.class, type));
    } else {
        return null;
    }
}

From source file:io.fabric8.docker.client.impl.OperationSupport.java

License:Apache License

/**
 * Checks if the response status code is the expected and throws the appropriate DockerClientException if not.
 *
 * @param request            The {#link Request} object.
 * @param response           The {@link Response} object.
 * @param expectedStatusCodes The expected status codes.
 * @throws DockerClientException When the response code is not the expected.
 *///  w  ww .  j a va2  s  .c o  m
protected void assertResponseCodes(Request request, Response response, int... expectedStatusCodes) {
    int statusCode = response.code();
    if (expectedStatusCodes.length > 0) {
        for (int expected : expectedStatusCodes) {
            if (statusCode == expected) {
                return;
            }
        }
        throw requestFailure(request, response);
    }
}

From source file:io.fabric8.docker.client.impl.OperationSupport.java

License:Apache License

DockerClientException requestFailure(Request request, Response response) {
    StringBuilder sb = new StringBuilder();
    sb.append("Failure executing: ").append(request.method()).append(" at: ").append(request.urlString())
            .append(".").append(" Status:").append(response.code()).append(".").append(" Message: ")
            .append(response.message()).append(".");
    try {//from  w  ww.j  ava 2  s  . com
        String body = response.body().string();
        sb.append(" Body: ").append(body);
    } catch (Throwable t) {
        sb.append(" Body: <unreadable>");
    }
    return new DockerClientException(sb.toString(), response.code());
}