com.truelayer.java.http.TrueLayerResponseCallAdapter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of truelayer-java Show documentation
Show all versions of truelayer-java Show documentation
TrueLayer Java SDK for https://truelayer.com
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();
}
}