Search in sources :

Example 11 with Converter

use of retrofit2.Converter in project mobile-sdk-android by meniga.

the class MenigaTransactionUpdateConverter method responseBodyConverter.

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, final Retrofit retrofit) {
    Type typeOfTransactionUpdate = new TypeToken<MenigaTransactionUpdate>() {
    }.getType();
    if (typeOfTransactionUpdate.equals(type)) {
        return new Converter<ResponseBody, Object>() {

            @Override
            public Object convert(ResponseBody resBody) throws IOException {
                Gson gson = GsonProvider.getGsonBuilder();
                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(resBody.byteStream());
                    JsonElement element = new JsonParser().parse(isr);
                    isr.close();
                    JsonObject json = element.getAsJsonObject();
                    List<MenigaTransaction> updatedTransactions = new ArrayList<>();
                    if (json.get("data").isJsonArray()) {
                        updatedTransactions = gson.fromJson(json.getAsJsonArray("data"), new TypeToken<List<MenigaTransaction>>() {
                        }.getType());
                    } else {
                        MenigaTransaction updated = gson.fromJson(json.getAsJsonObject("data"), new TypeToken<MenigaTransaction>() {
                        }.getType());
                        updatedTransactions.add(updated);
                    }
                    List<MenigaTransaction> transactions = new ArrayList<>();
                    if (json.has("meta")) {
                        transactions = gson.fromJson(json.getAsJsonArray("meta"), new TypeToken<List<MenigaTransaction>>() {
                        }.getType());
                    }
                    return MenigaTransactionUpdate.fromList(updatedTransactions, transactions);
                } finally {
                    if (isr != null) {
                        isr.close();
                    }
                }
            }
        };
    }
    return null;
}
Also used : InputStreamReader(java.io.InputStreamReader) MenigaTransaction(com.meniga.sdk.models.transactions.MenigaTransaction) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) MenigaTransactionUpdate(com.meniga.sdk.models.transactions.MenigaTransactionUpdate) JsonElement(com.google.gson.JsonElement) TypeToken(com.google.gson.reflect.TypeToken) Converter(retrofit2.Converter) ArrayList(java.util.ArrayList) List(java.util.List) JsonParser(com.google.gson.JsonParser)

Example 12 with Converter

use of retrofit2.Converter in project xabber-android by redsolution.

the class RetrofitErrorConverter method throwableToHttpError.

@Nullable
public static String throwableToHttpError(Throwable throwable) {
    String errorMessage = null;
    APIError error = null;
    if (throwable instanceof HttpException) {
        HttpException exception = (HttpException) throwable;
        Response response = exception.response();
        ResponseBody responseBody = response.errorBody();
        if (responseBody != null) {
            Converter<ResponseBody, APIError> converter = HttpApiManager.getRetrofit().responseBodyConverter(APIError.class, new Annotation[0]);
            try {
                error = converter.convert(responseBody);
            } catch (IOException | JsonSyntaxException e) {
                e.printStackTrace();
            }
        }
        if (error != null) {
            if (error.getDetail() != null)
                errorMessage = error.getDetail();
            else if (error.getEmail() != null && error.getEmail().size() > 0)
                errorMessage = error.getEmail().get(0);
            else if (error.getCredentials() != null && error.getCredentials().size() > 0)
                errorMessage = error.getCredentials().get(0);
            else if (error.getCode() != null && error.getCode().size() > 0)
                errorMessage = error.getCode().get(0);
            else if (error.getUsername() != null && error.getUsername().size() > 0)
                errorMessage = error.getUsername().get(0);
            else if (error.getPhone() != null && error.getPhone().size() > 0)
                errorMessage = error.getPhone().get(0);
        }
    }
    return errorMessage;
}
Also used : Response(retrofit2.Response) JsonSyntaxException(com.google.gson.JsonSyntaxException) HttpException(retrofit2.HttpException) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Nullable(android.support.annotation.Nullable)

Example 13 with Converter

use of retrofit2.Converter in project retrofit by square.

the class CallTest method conversionProblemIncomingMaskedByConverterIsUnwrapped.

@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.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.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();
        }
    }).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");
    }
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) OkHttpClient(okhttp3.OkHttpClient) ForwardingSource(okio.ForwardingSource) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) Interceptor(okhttp3.Interceptor) BufferedSource(okio.BufferedSource) Test(org.junit.Test)

Example 14 with Converter

use of retrofit2.Converter in project retrofit by square.

the class CallTest method conversionProblemOutgoingAsync.

@Test
public void conversionProblemOutgoingAsync() throws InterruptedException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(new ToStringConverterFactory() {

        @Override
        public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
            return new Converter<String, RequestBody>() {

                @Override
                public RequestBody convert(String value) throws IOException {
                    throw new UnsupportedOperationException("I am broken!");
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    example.postString("Hi").enqueue(new Callback<String>() {

        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            throw new AssertionError();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            failureRef.set(t);
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    assertThat(failureRef.get()).isInstanceOf(UnsupportedOperationException.class).hasMessage("I am broken!");
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) RequestBody(okhttp3.RequestBody) Test(org.junit.Test)

Example 15 with Converter

use of retrofit2.Converter in project retrofit by square.

the class CallTest method conversionProblemIncomingAsync.

@Test
public void conversionProblemIncomingAsync() throws InterruptedException {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).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 {
                    throw new UnsupportedOperationException("I am broken!");
                }
            };
        }
    }).build();
    Service example = retrofit.create(Service.class);
    server.enqueue(new MockResponse().setBody("Hi"));
    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    example.postString("Hi").enqueue(new Callback<String>() {

        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            throw new AssertionError();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            failureRef.set(t);
            latch.countDown();
        }
    });
    assertTrue(latch.await(10, SECONDS));
    assertThat(failureRef.get()).isInstanceOf(UnsupportedOperationException.class).hasMessage("I am broken!");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) ToStringConverterFactory(retrofit2.helpers.ToStringConverterFactory) Test(org.junit.Test)

Aggregations

Type (java.lang.reflect.Type)19 ResponseBody (okhttp3.ResponseBody)18 Test (org.junit.Test)12 Converter (retrofit2.Converter)10 JsonObject (com.google.gson.JsonObject)8 ParameterizedType (java.lang.reflect.ParameterizedType)8 MediaType (okhttp3.MediaType)8 NonMatchingConverterFactory (retrofit2.helpers.NonMatchingConverterFactory)8 JsonElement (com.google.gson.JsonElement)7 IOException (java.io.IOException)7 ToStringConverterFactory (retrofit2.helpers.ToStringConverterFactory)7 Gson (com.google.gson.Gson)6 JsonParser (com.google.gson.JsonParser)6 InputStreamReader (java.io.InputStreamReader)6 JsonArray (com.google.gson.JsonArray)5 Annotation (java.lang.annotation.Annotation)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 DelegatingCallAdapterFactory (retrofit2.helpers.DelegatingCallAdapterFactory)4