github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit2/play24/Play24CallAdapterFactory.mustache (about) 1 package {{invokerPackage}}; 2 3 import play.libs.F; 4 import retrofit2.*; 5 6 import java.lang.annotation.Annotation; 7 import java.lang.reflect.ParameterizedType; 8 import java.lang.reflect.Type; 9 import java.lang.reflect.WildcardType; 10 11 /** 12 * Creates {@link CallAdapter} instances that convert {@link Call} into {@link play.libs.F.Promise} 13 */ 14 public class Play24CallAdapterFactory extends CallAdapter.Factory { 15 16 @Override 17 public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { 18 if (!(returnType instanceof ParameterizedType)) { 19 return null; 20 } 21 22 ParameterizedType type = (ParameterizedType) returnType; 23 if (type.getRawType() != F.Promise.class) { 24 return null; 25 } 26 27 return createAdapter((ParameterizedType) returnType); 28 } 29 30 private CallAdapter<?, F.Promise<?>> createAdapter(ParameterizedType returnType) { 31 Type[] types = returnType.getActualTypeArguments(); 32 if (types.length != 1) { 33 throw new IllegalStateException("Must be exactly one type parameter"); 34 } 35 36 Type resultType = types[0]; 37 Class<?> rawTypeParam = getRawType(resultType); 38 39 boolean includeResponse = false; 40 if (rawTypeParam == Response.class) { 41 if (!(resultType instanceof ParameterizedType)) { 42 throw new IllegalStateException("Response must be parameterized" 43 + " as Response<T>"); 44 } 45 resultType = ((ParameterizedType) resultType).getActualTypeArguments()[0]; 46 includeResponse = true; 47 } 48 49 return new ValueAdapter(resultType, includeResponse); 50 } 51 52 /** 53 * Adapter that coverts values returned by API interface into CompletionStage 54 */ 55 private static final class ValueAdapter<R> implements CallAdapter<R, F.Promise<R>> { 56 57 private final Type responseType; 58 private final boolean includeResponse; 59 60 ValueAdapter(Type responseType, boolean includeResponse) { 61 this.responseType = responseType; 62 this.includeResponse = includeResponse; 63 } 64 65 @Override 66 public Type responseType() { 67 return responseType; 68 } 69 70 @Override 71 public F.Promise<R> adapt(final Call<R> call) { 72 final F.RedeemablePromise<R> promise = F.RedeemablePromise.empty(); 73 74 call.enqueue(new Callback<R>() { 75 76 @Override 77 public void onResponse(Call<R> call, Response<R> response) { 78 if (response.isSuccessful()) { 79 if (includeResponse) { 80 promise.success((R) response); 81 } else { 82 promise.success(response.body()); 83 } 84 } else { 85 promise.failure(new HttpException(response)); 86 } 87 } 88 89 @Override 90 public void onFailure(Call<R> call, Throwable t) { 91 promise.failure(t); 92 } 93 94 }); 95 96 return promise; 97 } 98 } 99 100 }