Example usage for com.squareup.okhttp ResponseBody string

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

Introduction

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

Prototype

public final String string() throws IOException 

Source Link

Document

Returns the response as a string decoded with the charset of the Content-Type header.

Usage

From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onMessage(ResponseBody responseBody) throws IOException {

    BasicMessageWithExtraData<? extends BasicMessage> response;
    String requestClassName = "?";

    try {/*from   ww  w.  ja v a2s.c o  m*/
        try {
            BasicMessageWithExtraData<? extends BasicMessage> msgWithData;

            if (responseBody.contentType().equals(WebSocket.TEXT)) {
                String nameAndJsonStr = responseBody.string();
                msgWithData = new ApiDeserializer().deserialize(nameAndJsonStr);
            } else if (responseBody.contentType().equals(WebSocket.BINARY)) {
                InputStream input = responseBody.byteStream();
                msgWithData = new ApiDeserializer().deserialize(input);
            } else {
                throw new IllegalArgumentException(
                        "Unknown mediatype type, please report this bug: " + responseBody.contentType());
            }

            log.debug("Received message from server");

            BasicMessage msg = msgWithData.getBasicMessage();
            requestClassName = msg.getClass().getName();

            Class<? extends Command<?, ?>> commandClass = VALID_COMMANDS.get(requestClassName);
            if (commandClass == null) {
                log.errorInvalidCommandRequestFeed(requestClassName);
                String errorMessage = "Invalid command request: " + requestClassName;
                GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setErrorMessage(errorMessage)
                        .build();
                response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null);
            } else {
                Command command = commandClass.newInstance();
                CommandContext context = new CommandContext(this, this.config, this.discoveryService);
                response = command.execute(msgWithData, context);
            }
        } finally {
            // must ensure response is closed; this assumes if it was a stream that the command is finished with it
            responseBody.close();
        }
    } catch (Throwable t) {
        log.errorCommandExecutionFailureFeed(requestClassName, t);
        String errorMessage = "Command failed [" + requestClassName + "]";
        GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setThrowable(t)
                .setErrorMessage(errorMessage).build();
        response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null);
    }

    // send the response back to the server
    if (response != null) {
        try {
            sendSync(response);
        } catch (Exception e) {
            log.errorFailedToSendOverFeedComm(response.getClass().getName(), e);
        }
    }
}

From source file:org.hawkular.client.android.util.OperationManager.java

License:Apache License

private void create() {

    fetchCredentials();/*ww  w  . j  a  v  a2 s .c  om*/

    generateUri();

    WebSocketClientGenerator.Configuration config = new WebSocketClientGenerator.Configuration.Builder()
            .username(username).password(password).useSsl(false).sslContext(null).keystorePath("")
            .keystorePassword("").readTimeout(0).connectTimeout(0).build();

    WebSocketClientGenerator base = new WebSocketClientGenerator(config);
    Map<String, String> map = new HashMap<String, String>();
    map.put("Hawkular-Tenant", Preferences.of(context).personaId().get());
    WebSocketCall webSocketCall = base.createWebSocketCall(uri, map);

    webSocketCall.enqueue(new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            OperationManager.webSocket = webSocket;
            destroyed = false;
        }

        @Override
        public void onFailure(IOException e, Response response) {
            Timber.d(e.getMessage());
            destroyed = true;
            disconnect();
        }

        @Override
        public void onMessage(ResponseBody message) throws IOException {
            String m = message.string();
            String[] temp = m.split("=", 2);
            if (temp[0].equals(REQUEST_TOKEN)) {
                callback.onSuccess(context.getString(R.string.success_websocket_request));
            } else if (temp[0].equals(SUCCESS_TOKEN)) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(temp[1]);
                    if (jsonObject.getString("status").equals("OK")) {
                        callback.onSuccess(context.getString(R.string.success_websocket_operation_complete));
                    } else {
                        callback.onSuccess(context.getString(R.string.fail_websocket_operation_complete));
                    }
                } catch (JSONException e) {
                    callback.onFailure(e);
                }

            }
        }

        @Override
        public void onPong(Buffer payload) {
        }

        @Override
        public void onClose(int code, String reason) {
            destroyed = true;
            disconnect();
        }
    });
}

From source file:org.openhab.binding.bosesoundtouch.handler.BoseSoundTouchHandler.java

License:Open Source License

@Override
public void onMessage(ResponseBody message) throws IOException {
    String msg = message.string();
    logger.debug("onMessage(\"" + msg + "\")");
    try {/*from   ww  w .j a v a 2  s  . c o m*/
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(new ResponseHandler(this));
        reader.parse(new InputSource(new StringReader(msg)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.error("Could not parse XML from string '{}'; exception is: ", msg, e);
    } catch (Throwable s) {
        logger.error("Could not parse XML from string '{}'; exception is: ", msg, s);
    }
}

From source file:org.sonar.runner.impl.ServerConnection.java

License:Open Source License

/**
 * @throws IOException           if connectivity problem or timeout (network) or IO error (when writing to file)
 * @throws IllegalStateException if HTTP response code is different than 2xx
 *///from   w w w  .ja  va 2  s  . c  om
private String downloadString(String url, boolean saveCache) throws IOException {
    logger.debug(format("Download: %s", url));
    ResponseBody responseBody = callUrl(url);
    String content = responseBody.string();
    if (saveCache) {
        try {
            wsCache.put(url, content.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            logger.warn("Failed to cache WS call: " + e.getMessage());
        }
    }
    return content;
}

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 ww w .j  a v  a  2 s  . co 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 http204SkipsConverter() throws IOException {
    final Converter<ResponseBody, String> converter = spy(new Converter<ResponseBody, String>() {
        @Override//from   www  .j  a v  a 2s . com
        public String convert(ResponseBody value) throws IOException {
            return value.string();
        }
    });
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    return converter;
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setStatus("HTTP/1.1 204 Nothin"));

    Response<String> response = example.getString().execute();
    assertThat(response.code()).isEqualTo(204);
    assertThat(response.body()).isNull();
    verifyNoMoreInteractions(converter);
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void http205SkipsConverter() throws IOException {
    final Converter<ResponseBody, String> converter = spy(new Converter<ResponseBody, String>() {
        @Override//ww w.  j  a  va 2  s.c o  m
        public String convert(ResponseBody value) throws IOException {
            return value.string();
        }
    });
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(new ToStringConverterFactory() {
                @Override
                public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
                    return converter;
                }
            }).build();
    Service example = retrofit.create(Service.class);

    server.enqueue(new MockResponse().setStatus("HTTP/1.1 205 Nothin"));

    Response<String> response = example.getString().execute();
    assertThat(response.code()).isEqualTo(205);
    assertThat(response.body()).isNull();
    verifyNoMoreInteractions(converter);
}

From source file:retrofit.CallTest.java

License:Apache License

@Test
public void responseBodyStreams() 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("1234").setSocketPolicy(DISCONNECT_DURING_RESPONSE_BODY));

    Response<ResponseBody> response = example.getStreamingBody().execute();

    ResponseBody streamedBody = response.body();
    // When streaming we only detect socket problems as the ResponseBody is read.
    try {/*from w  w w  . j a  v a  2s. co  m*/
        streamedBody.string();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage("unexpected end of stream");
    }
}

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 {/*from 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:retrofit2.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//  ww w  .j  av  a 2s .co  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, ?> responseBodyConverter(Type type, Annotation[] annotations,
                        Retrofit retrofit) {
                    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");
    }
}