Example usage for com.squareup.okhttp ResponseBody source

List of usage examples for com.squareup.okhttp ResponseBody source

Introduction

In this page you can find the example usage for com.squareup.okhttp ResponseBody source.

Prototype

public abstract BufferedSource source() throws IOException;

Source Link

Usage

From source file:cz.muni.fi.pv256.movio.uco_374524.superprojekt.connection.moshi.MoshiResponseBodyConverter.java

License:Apache License

@Override
public T convert(ResponseBody value) throws IOException {
    BufferedSource source = value.source();
    try {/*from w  ww  .ja  v a  2s  .  c  om*/
        return adapter.fromJson(source);
    } finally {
        if (source != null) {
            try {
                source.close();
            } catch (IOException ignored) {
            }
        }
    }
}

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

License:Apache License

@Override
public void onMessage(ResponseBody message) throws IOException {
    try {/*  w w w  . j  av  a 2 s  .c om*/
        byte streamID = message.source().readByte();
        ByteString byteString = message.source().readByteString();
        if (byteString.size() > 0) {
            switch (streamID) {
            case 1:
                if (out != null) {
                    out.write(byteString.toByteArray());
                }
                break;
            case 2:
                if (err != null) {
                    err.write(byteString.toByteArray());
                }
                break;
            case 3:
                if (err != null) {
                    err.write(byteString.toByteArray());
                }
                break;
            default:
                throw new IOException("Unknown stream ID " + streamID);
            }
        }
    } finally {
        message.close();
    }
}

From source file:io.fabric8.kubernetes.client.dsl.internal.WatchConnectionManager.java

License:Apache License

private final void runWatch() throws MalformedURLException, ExecutionException, InterruptedException {
    URL requestUrl = baseOperation.getNamespacedUrl();

    HttpUrl.Builder httpUrlBuilder = HttpUrl.get(requestUrl).newBuilder();

    String labelQueryParam = baseOperation.getLabelQueryParam();
    if (labelQueryParam.length() > 0) {
        httpUrlBuilder.addQueryParameter("labelSelector", labelQueryParam);
    }/*w  w w  . j a  v a 2s.  c  o m*/

    String fieldQueryString = baseOperation.getFieldQueryParam();
    String name = baseOperation.getName();
    if (name != null && name.length() > 0) {
        if (fieldQueryString.length() > 0) {
            fieldQueryString += ",";
        }
        fieldQueryString += "metadata.name=" + name;
    }
    httpUrlBuilder.addQueryParameter("fieldSelector", fieldQueryString);

    httpUrlBuilder.addQueryParameter("resourceVersion", this.resourceVersion.get()).addQueryParameter("watch",
            "true");

    Request request = new Request.Builder().get().url(httpUrlBuilder.build())
            .addHeader("Origin",
                    requestUrl.getProtocol() + "://" + requestUrl.getHost() + ":" + requestUrl.getPort())
            .build();
    clonedClient.setReadTimeout(0, TimeUnit.MILLISECONDS);

    webSocketCall = WebSocketCall.create(clonedClient, request);
    webSocketCall.enqueue(new WebSocketListener() {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            webSocketRef.set(webSocket);
            currentReconnectAttempt.set(0);
        }

        @Override
        public void onFailure(IOException e, Response response) {
            e.printStackTrace();
            try {
                if (response != null && response.body() != null) {
                    response.body().close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            if (forceClosed.get()) {
                executor.shutdownNow();
                watcher.onClose(null);
                return;
            }

            onClose(4000, "Connection unexpectedly closed");
        }

        @Override
        public void onMessage(ResponseBody message) throws IOException {
            try {
                WatchEvent event = mapper.readValue(message.byteStream(), WatchEvent.class);
                T obj = (T) event.getObject();
                //Dirty cast - should always be valid though
                String currentResourceVersion = resourceVersion.get();
                String newResourceVersion = ((HasMetadata) obj).getMetadata().getResourceVersion();
                if (currentResourceVersion.compareTo(newResourceVersion) < 0) {
                    resourceVersion.compareAndSet(currentResourceVersion, newResourceVersion);
                }
                Watcher.Action action = Watcher.Action.valueOf(event.getType());
                watcher.eventReceived(action, obj);
            } catch (IOException e) {
                logger.error("Could not deserialize watch event: {}", message.source().readUtf8(), e);
            } catch (ClassCastException e) {
                logger.error("Received wrong type of object for watch", e);
            } catch (IllegalArgumentException e) {
                logger.error("Invalid event type", e);
            } finally {
                message.close();
            }
        }

        @Override
        public void onPong(Buffer buffer) {

        }

        @Override
        public void onClose(final int code, final String reason) {
            if (forceClosed.get()) {
                executor.shutdownNow();
                watcher.onClose(null);
                return;
            }
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        runWatch();
                    } catch (ExecutionException e) {
                        if (e.getCause() != null && e.getCause().getCause() != null
                                && e.getCause().getCause() instanceof ConnectException) {
                            if (reconnectLimit >= 0
                                    && currentReconnectAttempt.getAndIncrement() >= reconnectLimit) {
                                watcher.onClose(
                                        new KubernetesClientException("Connection unexpectedly closed", e));
                                return;
                            }
                            try {
                                TimeUnit.MILLISECONDS.sleep(reconnectInterval);
                            } catch (InterruptedException e1) {
                                watcher.onClose(
                                        new KubernetesClientException("Connection unexpectedly closed", e1));
                                return;
                            }
                            onClose(code, reason);
                        }
                    } catch (MalformedURLException | InterruptedException e) {
                        throw KubernetesClientException.launderThrowable(e);
                    }
                }
            });
        }
    });
}

From source file:io.fabric8.kubernetes.server.mock.KubernetesWebSocketReader.java

License:Apache License

@Override
public byte[] read(ResponseBody message) {
    try {/*from  w  w  w . j  av a 2s  .com*/
        byte streamID = message.source().readByte();
        ByteString byteString = message.source().readByteString();
        if (byteString.size() > 0) {
            switch (streamID) {
            case 1:
            case 2:
            case 3:
                return byteString.toByteArray();
            default:
                throw new IOException("Unknown stream ID " + streamID);
            }
        }
    } catch (IOException e) {

    } finally {
        Closeables.closeQuietly(message);
    }
    throw new IllegalStateException("Failed to read websocket response body.");
}

From source file:io.fabric8.kubernetes.server.mock.WebSocketSession.java

License:Apache License

private String read(ResponseBody message) throws IOException {
    try {/*from  w  w  w.  ja  v a2  s.  c o  m*/
        byte streamID = message.source().readByte();
        ByteString byteString = message.source().readByteString();
        if (byteString.size() > 0) {
            switch (streamID) {
            case 1:
            case 2:
            case 3:
                return byteString.toString();
            default:
                throw new IOException("Unknown stream ID " + streamID);
            }
        }
    } finally {
        message.close();
    }
    throw new IllegalArgumentException("Not a string message");
}

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  w w  .java2  s .  co  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:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }//  w  w w.j  a  v  a  2s.c om

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

    RequestBody requestBody = request.body();

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    UUID requestId = UUID.randomUUID();
    StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n')
            .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol);
    if (!logHeaders && requestBody != null) {
        requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");
    }
    requestMessage.append('\n');

    if (logHeaders) {
        if (requestBody != null) {
            // 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) {
                requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n');
            }
            if (requestBody.contentLength() != -1) {
                requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n');
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name)
                    || "Proxy-Authorization".equalsIgnoreCase(name)
                    || "WWW-Authenticate".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": *****\n");
            }
            // Skip headers from the request body as they are explicitly
            // logged above.
            else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (!logBody || requestBody == null) {
            requestMessage.append("--> END ").append(requestId).append('\n');
        } else if (bodyEncoded(request.headers())) {
            requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n');
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            requestMessage.append('\n');
            if (isPlaintext(buffer)) {
                requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId)
                        .append(" (").append(requestBody.contentLength()).append("-byte body)\n");
            } else {
                requestMessage.append("--> END ").append(requestId).append(" (binary ")
                        .append(requestBody.contentLength()).append("-byte body omitted)\n");
            }
        }
    }

    logger.log(requestMessage.substring(0, requestMessage.length() - 1));

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- " + requestId + "HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ')
            .append(response.request().url()).append(" (").append(tookMs).append("ms");
    if (!logHeaders) {
        responseMessage.append(", ");
        if (contentLength != -1) {
            responseMessage.append(contentLength).append("-byte");
        } else {
            responseMessage.append("unknown-length");
        }
        responseMessage.append(" body");
    }
    responseMessage.append(")\n");

    responseMessage.append(response.code()).append(' ').append(response.message()).append('\n');

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

        if (!logBody || !HttpEngine.hasBody(response)) {
            responseMessage.append("<-- END HTTP\n");
        } else if (bodyEncoded(response.headers())) {
            responseMessage.append("<-- END HTTP (encoded body omitted)\n");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

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

            if (!isPlaintext(buffer)) {
                responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size())
                        .append("-byte body omitted)");
                logger.log(responseMessage.toString());
                return response;
            }

            if (contentLength != 0) {
                responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n');
            }

            responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n");
        }
    }

    logger.log(responseMessage.substring(0, responseMessage.length() - 1));
    return response;
}

From source file:qm.vp.kiev.qmhttplib.retrofit.Utils.java

License:Apache License

/**
 * Replace a {@link com.squareup.okhttp.Response} with an identical copy whose body is backed by a
 * {@link okio.Buffer} rather than a {@link okio.Source}.
 *//*from ww  w .j  a v  a 2 s. co  m*/
static Response readBodyToBytesIfNecessary(Response response) throws IOException {
    final ResponseBody body = response.body();
    if (body == null) {
        return response;
    }

    BufferedSource source = body.source();
    final Buffer buffer = new Buffer();
    buffer.writeAll(source);
    source.close();

    return response.newBuilder().body(new ResponseBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public BufferedSource source() {
            return buffer.clone();
        }
    }).build();
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
    // MWS has no way to trigger IOExceptions during the response body so use an interceptor.
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override//from  www.  j av  a2 s .c  o m
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Response response = chain.proceed(chain.request());
            ResponseBody body = response.body();
            BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
                @Override
                public long read(Buffer sink, long byteCount) throws IOException {
                    throw new IOException("cause");
                }
            });
            body = ResponseBody.create(body.contentType(), body.contentLength(), source);
            return response.newBuilder().body(body).build();
        }
    });

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client)
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    return new Converter<ResponseBody, String>() {
                        @Override
                        public String convert(ResponseBody value) throws IOException {
                            try {
                                return value.string();
                            } catch (IOException e) {
                                // Some serialization libraries mask transport problems in runtime exceptions. Bad!
                                throw new RuntimeException("wrapper", e);
                            }
                        }
                    };
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi"));

    Call<String> call = example.getString();
    try {
        call.execute();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("cause");
    }
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void rawResponseContentTypeAndLengthButNoSource() throws IOException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory()).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setBody("Hi").addHeader("Content-Type", "text/greeting"));

    Response<String> response = example.getString().execute();
    assertThat(response.body()).isEqualTo("Hi");
    ResponseBody rawBody = response.raw().body();
    assertThat(rawBody.contentLength()).isEqualTo(2);
    assertThat(rawBody.contentType().toString()).isEqualTo("text/greeting");
    try {//from ww  w  .java2s. c om
        rawBody.source();
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Cannot read raw response body of a converted body.");
    }
}