All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.truelayer.java.http.TrueLayerResponseCallAdapter Maven / Gradle / Ivy

There is a newer version: 16.0.0
Show newest version
package com.truelayer.java.http;

import com.truelayer.java.http.entities.ApiResponse;
import com.truelayer.java.http.mappers.ErrorMapper;
import java.lang.reflect.Type;
import java.util.concurrent.CompletableFuture;
import retrofit2.*;

/**
 * This class is extends Retrofit's ResponseCallAdapter
 * to support TrueLayer ApiResponse wrapper object.
 *
 * @see ApiResponse
 */
final class TrueLayerResponseCallAdapter implements CallAdapter>> {
    private final Type responseType;
    private final ErrorMapper errorMapper;

    TrueLayerResponseCallAdapter(Type responseType) {
        this.responseType = responseType;
        this.errorMapper = new ErrorMapper();
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public CompletableFuture> adapt(final Call call) {
        CompletableFuture> future = new CallCancelCompletableFuture<>(call);
        call.enqueue(new ResponseCallback(future));
        return future;
    }

    protected class ResponseCallback implements Callback {
        private final CompletableFuture> future;

        public ResponseCallback(CompletableFuture> future) {
            this.future = future;
        }

        @Override
        public void onResponse(Call call, Response response) {
            future.complete(handleResponse(response));
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            future.completeExceptionally(t);
        }
    }

    private static final class CallCancelCompletableFuture extends CompletableFuture {
        private final Call call;

        CallCancelCompletableFuture(Call call) {
            this.call = call;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (mayInterruptIfRunning) {
                call.cancel();
            }
            return super.cancel(mayInterruptIfRunning);
        }
    }

    private ApiResponse handleResponse(Response response) {
        if (response.isSuccessful()) {
            return ApiResponse.builder().data(response.body()).build();
        }

        return ApiResponse.builder()
                .error(errorMapper.toProblemDetails(response))
                .build();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy