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:io.fabric8.docker.client.impl.ContainerOutputHandle.java

License:Apache License

@Override
public void onFailure(IOException ioe, Response response) {
    LOGGER.error(response != null ? response.message() : "Exec Failure.", ioe);
    //We only need to queue startup failures.
    if (!started.get()) {
        queue.add(ioe);/*from   w ww.  jav a 2  s . co  m*/
    }
}

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

License:Apache License

@Override
public InputStream getOutput() {
    try {//w  w w.j a  v a 2s  . c o  m
        if (latch.await(timeoutMillis, TimeUnit.MILLISECONDS)) {
            Throwable t = error.get();
            Response r = response.get();

            if (t != null) {
                throw DockerClientException.launderThrowable(t);
            } else if (r == null) {
                throw new DockerClientException("Response not available");
            } else if (!r.isSuccessful()) {
                throw new DockerClientException(r.message());
            } else if (pin == null) {
                throw new DockerClientException(
                        "InputStream not available. Have you used redirectingOutput()?");
            } else {
                return pin;
            }
        } else {
            throw new DockerClientException("Timed out waiting for response");
        }
    } catch (InterruptedException e) {
        try {
            close();
        } catch (IOException ioe) {
            throw DockerClientException.launderThrowable(e);
        } finally {
            Thread.currentThread().interrupt();
        }
    }
    throw new DockerClientException("Could not obtain stream");
}

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  a v a  2s.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());
}

From source file:io.fabric8.kubernetes.client.dsl.base.OperationSupport.java

License:Apache License

public static Status createStatus(Response response) {
    int statusCode = response.code();
    String statusMessage = "";
    ResponseBody body = response != null ? response.body() : null;
    try {//w  w  w  . jav a2s. co  m
        if (response == null) {
            statusMessage = "No response";
        } else if (body != null) {
            statusMessage = body.string();
        } else if (response.message() != null) {
            statusMessage = response.message();
        }
        return JSON_MAPPER.readValue(statusMessage, Status.class);
    } catch (JsonParseException e) {
        return createStatus(statusCode, statusMessage);
    } catch (IOException e) {
        return createStatus(statusCode, statusMessage);
    }
}

From source file:io.kubernetes.client.util.Watch.java

License:Apache License

/**
 * Creates a watch on a TYPENAME (T) using an API Client and a Call object.
 * @param client the API client/* www  . j av  a  2s . c o  m*/
 * @param call the call object returned by api.{ListOperation}Call(...)
 *             method. Make sure watch flag is set in the call.
 * @param watchType The type of the WatchResponse&lt;T&gt;. Use something like
 *                  new TypeToken&lt;Watch.Response&lt;TYPENAME&gt;&gt;(){}.getType()
 * @param <T> TYPENAME.
 * @return Watch object on TYPENAME
 * @throws ApiException on IO exceptions.
 */
public static <T> Watch<T> createWatch(ApiClient client, Call call, Type watchType) throws ApiException {
    try {
        com.squareup.okhttp.Response response = call.execute();
        if (!response.isSuccessful()) {
            String respBody = null;
            if (response.body() != null) {
                try {
                    respBody = response.body().string();
                } catch (IOException e) {
                    throw new ApiException(response.message(), e, response.code(),
                            response.headers().toMultimap());
                }
            }
            throw new ApiException(response.message(), response.code(), response.headers().toMultimap(),
                    respBody);
        }
        return new Watch<>(client.getJSON(), response.body(), watchType);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:io.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {

    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE || (!slf4j.isDebugEnabled())) {
        return chain.proceed(request);
    }/*from  w  ww  . jav  a 2 s  .c  o m*/

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    try {

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
        String requestStartMessage = "--> " + request.method() + ' ' + request.httpUrl() + ' '
                + protocol(protocol);
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        log(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a
                // network interceptor. Force
                // them to be included (when available) so there values are
                // known.
                if (requestBody.contentType() != null) {
                    log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);

                if (name.equalsIgnoreCase("authorization")) {
                    log(name + ": ************");
                } else {
                    // Skip headers from the request body as they are
                    // explicitly
                    // logged above.
                    if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                        log(name + ": " + headers.value(i));
                    }
                }
            }

            if (!logBody || !hasRequestBody) {
                slf4j.debug("--> END " + request.method());
            } else if (bodyEncoded(request.headers())) {
                log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    contentType.charset(UTF8);
                }

                log("");
                String body = redactRequestBody(buffer.readString(charset));

                log(body);

                log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            }
        }

    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    try {
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " ("
                + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "")
                + ')');

        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log(headers.name(i) + ": " + headers.value(i));
            }

            if (!logBody || !HttpEngine.hasBody(response)) {
                log("<-- END HTTP");
            } else if (!isResponseBodyPrintable(response)) {
                log("<-- END HTTP (body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(maxPrintableBodySize); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                if (responseBody.contentLength() != 0) {
                    log("");
                    log(redactResponseBody(buffer.clone().readString(charset)));
                }

                log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString());
    }

    return response;
}

From source file:it.smartcommunitylab.ApiClient.java

License:Apache License

/**
 * Handle the given response, return the deserialized object when the response is successful.
 *
 * @param <T> Type/* w  w w  .  j av a 2 s. com*/
 * @param response Response
 * @param returnType Return type
 * @throws ApiException If the response has a unsuccessful status code or
 *   fail to deserialize the response body
 * @return Type
 */
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
    if (response.isSuccessful()) {
        if (returnType == null || response.code() == 204) {
            // returning null if the returnType is not defined,
            // or the status code is 204 (No Content)
            if (response.body() != null) {
                try {
                    response.body().close();
                } catch (IOException e) {
                    throw new ApiException(response.message(), e, response.code(),
                            response.headers().toMultimap());
                }
            }
            return null;
        } else {
            return deserialize(response, returnType);
        }
    } else {
        String respBody = null;
        if (response.body() != null) {
            try {
                respBody = response.body().string();
            } catch (IOException e) {
                throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
            }
        }
        throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
    }
}

From source file:library.util.OkHttpStack.java

License:Apache License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    Builder okHttpRequestBuilder = new Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/* w w  w . j a va2s.c o m*/
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:lumbermill.elasticsearch.IndexFailedException.java

License:Apache License

public static IndexFailedException of(Response response) {
    try {/*from w ww .  j a v a 2  s  .  co  m*/
        return new IndexFailedException(response,
                response.code() + ", message:" + response.message() + ", body: " + response.body().string());
    } catch (IOException e) {
        LOGGER.warn("Failed to extract body from error message: " + e.getMessage());
        return new IndexFailedException(response, response.code() + ", message:" + response.message());
    }
}

From source file:lumbermill.internal.elasticsearch.ElasticSearchOkHttpClientImpl.java

License:Apache License

public static FatalIndexException createFatalIndexException(RequestSigner.SignableRequest request,
        Response response) {
    try {/*from  ww w . j  ava2s  . co m*/
        return new FatalIndexException(
                response.code() + ", message:" + response.message() + ", body: " + response.body().string());
    } catch (IOException e) {
        LOGGER.warn("Failed to extract body from error message: " + e.getMessage());
        return new FatalIndexException(response.code() + ", message:" + response.message());
    }
}