diff --git a/aws-lambda-java-runtime-interface-client/src/main/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoader.java b/aws-lambda-java-runtime-interface-client/src/main/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoader.java index 453b39e1..f7f4e6f9 100644 --- a/aws-lambda-java-runtime-interface-client/src/main/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoader.java +++ b/aws-lambda-java-runtime-interface-client/src/main/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoader.java @@ -31,21 +31,26 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.reflect.Array; import java.lang.reflect.Constructor; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import static com.amazonaws.services.lambda.runtime.api.client.UserFault.filterStackTrace; import static com.amazonaws.services.lambda.runtime.api.client.UserFault.makeUserFault; import static com.amazonaws.services.lambda.runtime.api.client.UserFault.trace; @@ -238,38 +243,107 @@ private static Type[] findInterfaceParameters(Class clazz, Class iface) { Type[] interfaces = curContext.clazz.getGenericInterfaces(); for (Type type : interfaces) { - if (type instanceof ParameterizedType) { - ParameterizedType candidate = (ParameterizedType) type; - Type rawType = candidate.getRawType(); - if (!(rawType instanceof Class)) { - //should be impossible - System.err.println("raw type is not a class: " + rawType); - continue; - } - Class rawClass = (Class) rawType; - if (iface.isAssignableFrom(rawClass)) { - return new ClassContext(candidate, curContext).actualTypeArguments; - } else { - clazzes.addFirst(new ClassContext(candidate, curContext)); - } - } else if (type instanceof Class) { - clazzes.addFirst(new ClassContext((Class) type, curContext)); - } else { - //should never happen? - System.err.println("Unexpected type class " + type.getClass().getName()); + ClassContext nextContext = nextClassContext(type, curContext); + if (nextContext == null) { + continue; } + if (type instanceof ParameterizedType && iface.isAssignableFrom(nextContext.clazz)) { + return nextContext.actualTypeArguments; + } + clazzes.addFirst(nextContext); } final Type superClass = curContext.clazz.getGenericSuperclass(); - if (superClass instanceof ParameterizedType) { - clazzes.addFirst(new ClassContext((ParameterizedType) superClass, curContext)); - } else if (superClass != null) { - clazzes.addFirst(new ClassContext((Class) superClass, curContext)); + if (superClass != null) { + ClassContext nextContext = nextClassContext(superClass, curContext); + if (nextContext != null) { + clazzes.addFirst(nextContext); + } } } return null; } + /** + * Finds the resolved generic type context of {@code targetClass} within {@code clazz}'s type hierarchy. + */ + private static ClassContext findClassContext(Class clazz, Class targetClass) { + if (clazz.equals(targetClass) || targetClass.getTypeParameters().length == 0) { + return null; + } + + LinkedList clazzes = new LinkedList<>(); + clazzes.addFirst(new ClassContext(clazz, (Type[]) null)); + Set> visitedParameterized = new HashSet<>(); + Set> visitedRaw = new HashSet<>(); + ClassContext rawFallback = null; + + while (!clazzes.isEmpty()) { + final ClassContext curContext = clazzes.removeLast(); + if (targetClass.equals(curContext.clazz)) { + if (curContext.actualTypeArguments != null) { + return curContext; + } + if (rawFallback == null) { + rawFallback = curContext; + } + continue; + } + + for (Type type : curContext.clazz.getGenericInterfaces()) { + enqueueClassContext(type, curContext, clazzes, visitedParameterized, visitedRaw); + } + + final Type superClass = curContext.clazz.getGenericSuperclass(); + if (superClass != null) { + enqueueClassContext(superClass, curContext, clazzes, visitedParameterized, visitedRaw); + } + } + return rawFallback; + } + + private static void enqueueClassContext( + Type type, + ClassContext curContext, + LinkedList clazzes, + Set> visitedParameterized, + Set> visitedRaw + ) { + ClassContext nextContext = nextClassContext(type, curContext); + if (nextContext == null) { + return; + } + Set> visited = nextContext.actualTypeArguments != null ? visitedParameterized : visitedRaw; + if (visited.add(nextContext.clazz)) { + clazzes.addFirst(nextContext); + } + } + + private static ClassContext nextClassContext(Type type, ClassContext curContext) { + if (type instanceof ParameterizedType) { + ParameterizedType candidate = (ParameterizedType) type; + if (!(candidate.getRawType() instanceof Class)) { + //should be impossible + System.err.println("raw type is not a class: " + candidate.getRawType()); + return null; + } + return new ClassContext(candidate, curContext); + } else if (type instanceof Class) { + return new ClassContext((Class) type, curContext); + } else { + //should never happen? + System.err.println("Unexpected type class " + type.getClass().getName()); + return null; + } + } + + private static Type resolveType(Type type, ClassContext context) { + if (context == null || type == null) { + return type; + } + return context.resolveType(type); + } + @SuppressWarnings({"rawtypes"}) private static LambdaRequestHandler wrapRequestHandlerClass(final Class clazz) { @@ -422,8 +496,21 @@ private static Optional getThreeLengthHandler( } private static Optional getHandlerFromOverload(Class clazz, Method m) { - final Type rType = m.getGenericReturnType(); - final Type[] pTypes = m.getGenericParameterTypes(); + final Type[] rawParamTypes = m.getGenericParameterTypes(); + if (rawParamTypes.length > 3) { + System.err.println("Ignoring an overload of method " + + m.getName() + + " because it has too many parameters: Expected at most 3, got " + + rawParamTypes.length); + return Optional.empty(); + } + + final ClassContext methodContext = findClassContext(clazz, m.getDeclaringClass()); + final Type rType = resolveType(m.getGenericReturnType(), methodContext); + final Type[] pTypes = new Type[rawParamTypes.length]; + for (int i = 0; i < rawParamTypes.length; i++) { + pTypes[i] = resolveType(rawParamTypes[i], methodContext); + } if (pTypes.length == 0) { return Optional.of(PojoMethodRequestHandler.makeRequestHandler(clazz, m, null, rType, false)); @@ -431,14 +518,8 @@ private static Optional getHandlerFromOverload(Class cl return getOneLengthHandler(clazz, m, pTypes[0], rType); } else if (pTypes.length == 2) { return getTwoLengthHandler(clazz, m, pTypes[0], pTypes[1], rType); - } else if (pTypes.length == 3) { - return getThreeLengthHandler(clazz, m, pTypes[0], pTypes[1], pTypes[2], rType); } else { - System.err.println("Ignoring an overload of method " - + m.getName() - + " because it has too many parameters: Expected at most 3, got " - + pTypes.length); - return Optional.empty(); + return getThreeLengthHandler(clazz, m, pTypes[0], pTypes[1], pTypes[2], rType); } } @@ -886,43 +967,255 @@ public ClassContext(Class clazz, ClassContext curContext) { @SuppressWarnings({"rawtypes"}) public ClassContext(ParameterizedType type, ClassContext curContext) { - Type[] types = type.getActualTypeArguments(); - for (int i = 0; i < types.length; i++) { - Type t = types[i]; - if (t instanceof TypeVariable) { - types[i] = curContext.resolveTypeVariable((TypeVariable) t); - } + Type[] rawTypes = type.getActualTypeArguments(); + Type[] resolvedTypes = new Type[rawTypes.length]; + for (int i = 0; i < resolvedTypes.length; i++) { + resolvedTypes[i] = curContext.resolveType(rawTypes[i]); } - Type t = type.getRawType(); - if (t instanceof Class) { - this.clazz = (Class) t; - } else if (t instanceof TypeVariable) { - this.clazz = (Class) ((TypeVariable) t).getGenericDeclaration(); + Type rawType = type.getRawType(); + if (rawType instanceof Class) { + this.clazz = (Class) rawType; + } else if (rawType instanceof TypeVariable) { + this.clazz = (Class) ((TypeVariable) rawType).getGenericDeclaration(); } else { - throw new RuntimeException("Type " + t + " is of unexpected type " + t.getClass()); + throw new RuntimeException("Type " + rawType + " is of unexpected type " + rawType.getClass()); + } + this.actualTypeArguments = resolvedTypes; + } + + public Type resolveType(Type type) { + if (type instanceof TypeVariable) { + return this.resolveTypeVariable((TypeVariable) type); + } else if (type instanceof ParameterizedType) { + return this.resolveParameterizedType((ParameterizedType) type); + } else if (type instanceof GenericArrayType) { + return this.resolveGenericArrayType((GenericArrayType) type); + } else if (type instanceof WildcardType) { + return this.resolveWildcardType((WildcardType) type); + } else { + return type; } - this.actualTypeArguments = types; } @SuppressWarnings({"rawtypes"}) public Type resolveTypeVariable(TypeVariable t) { - TypeVariable[] variables = getTypeParameters(); + TypeVariable[] variables = this.getTypeParameters(); for (int i = 0; i < variables.length; i++) { - if (t.getName().equals(variables[i].getName())) { - return actualTypeArguments == null ? variables[i] : actualTypeArguments[i]; + if (t.equals(variables[i])) { + return this.actualTypeArguments == null ? variables[i] : this.actualTypeArguments[i]; } } return t; } + private Type resolveParameterizedType(ParameterizedType parameterizedType) { + Type ownerType = parameterizedType.getOwnerType(); + Type resolvedOwner = ownerType != null ? this.resolveType(ownerType) : null; + Type[] originalArgs = parameterizedType.getActualTypeArguments(); + Type[] resolvedArgs = this.resolveTypeArray(originalArgs); + if (Objects.equals(ownerType, resolvedOwner) && Arrays.equals(originalArgs, resolvedArgs)) { + return parameterizedType; + } + return new ResolvedParameterizedType(parameterizedType.getRawType(), resolvedArgs, resolvedOwner); + } + + private Type resolveGenericArrayType(GenericArrayType genericArrayType) { + Type componentType = genericArrayType.getGenericComponentType(); + Type resolvedComponent = this.resolveType(componentType); + if (Objects.equals(componentType, resolvedComponent)) { + return genericArrayType; + } + if (resolvedComponent instanceof Class) { + return Array.newInstance((Class) resolvedComponent, 0).getClass(); + } + return new ResolvedGenericArrayType(resolvedComponent); + } + + private Type resolveWildcardType(WildcardType wildcardType) { + Type[] upperBounds = wildcardType.getUpperBounds(); + Type[] lowerBounds = wildcardType.getLowerBounds(); + Type[] resolvedUpper = this.resolveTypeArray(upperBounds); + Type[] resolvedLower = this.resolveTypeArray(lowerBounds); + if (Arrays.equals(upperBounds, resolvedUpper) && Arrays.equals(lowerBounds, resolvedLower)) { + return wildcardType; + } + return new ResolvedWildcardType(resolvedUpper, resolvedLower); + } + + private Type[] resolveTypeArray(Type[] types) { + Type[] resolved = new Type[types.length]; + for (int i = 0; i < types.length; i++) { + resolved[i] = this.resolveType(types[i]); + } + return resolved; + } + @SuppressWarnings({"rawtypes"}) private TypeVariable[] getTypeParameters() { - if (typeParameters == null) { - typeParameters = clazz.getTypeParameters(); + if (this.typeParameters == null) { + this.typeParameters = this.clazz.getTypeParameters(); + } + return this.typeParameters; + } + } + + private static final class ResolvedParameterizedType implements ParameterizedType { + private final Type rawType; + private final Type[] actualTypeArguments; + private final Type ownerType; + + private ResolvedParameterizedType(Type rawType, Type[] actualTypeArguments, Type ownerType) { + this.rawType = rawType; + this.actualTypeArguments = actualTypeArguments.clone(); + this.ownerType = ownerType; + } + + @Override + public Type[] getActualTypeArguments() { + return this.actualTypeArguments.clone(); + } + + @Override + public Type getRawType() { + return this.rawType; + } + + @Override + public Type getOwnerType() { + return this.ownerType; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ParameterizedType)) { + return false; + } + ParameterizedType that = (ParameterizedType) other; + return Objects.equals(this.ownerType, that.getOwnerType()) + && Objects.equals(this.rawType, that.getRawType()) + && Arrays.equals(this.actualTypeArguments, that.getActualTypeArguments()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(this.actualTypeArguments) + ^ Objects.hashCode(this.ownerType) + ^ Objects.hashCode(this.rawType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (this.ownerType != null) { + sb.append(this.ownerType.getTypeName()).append('.'); + if (this.rawType instanceof Class) { + sb.append(((Class) this.rawType).getSimpleName()); + } else { + sb.append(this.rawType.getTypeName()); + } + } else { + sb.append(this.rawType.getTypeName()); + } + if (this.actualTypeArguments.length > 0) { + sb.append('<'); + for (int i = 0; i < this.actualTypeArguments.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(this.actualTypeArguments[i].getTypeName()); + } + sb.append('>'); + } + return sb.toString(); + } + } + + private static final class ResolvedGenericArrayType implements GenericArrayType { + private final Type genericComponentType; + + private ResolvedGenericArrayType(Type genericComponentType) { + this.genericComponentType = genericComponentType; + } + + @Override + public Type getGenericComponentType() { + return this.genericComponentType; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof GenericArrayType)) { + return false; + } + GenericArrayType that = (GenericArrayType) other; + return Objects.equals(this.genericComponentType, that.getGenericComponentType()); + } + + @Override + public int hashCode() { + return Objects.hashCode(this.genericComponentType); + } + + @Override + public String toString() { + return this.genericComponentType.getTypeName() + "[]"; + } + } + + private static final class ResolvedWildcardType implements WildcardType { + private final Type[] upperBounds; + private final Type[] lowerBounds; + + private ResolvedWildcardType(Type[] upperBounds, Type[] lowerBounds) { + this.upperBounds = upperBounds.clone(); + this.lowerBounds = lowerBounds.clone(); + } + + @Override + public Type[] getUpperBounds() { + return this.upperBounds.clone(); + } + + @Override + public Type[] getLowerBounds() { + return this.lowerBounds.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof WildcardType)) { + return false; + } + WildcardType that = (WildcardType) other; + return Arrays.equals(this.lowerBounds, that.getLowerBounds()) + && Arrays.equals(this.upperBounds, that.getUpperBounds()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(this.lowerBounds) ^ Arrays.hashCode(this.upperBounds); + } + + @Override + public String toString() { + if (this.lowerBounds.length > 0) { + return "? super " + this.lowerBounds[0].getTypeName(); + } + if (this.upperBounds.length == 1 && Object.class.equals(this.upperBounds[0])) { + return "?"; } - return typeParameters; + return "? extends " + this.upperBounds[0].getTypeName(); } } diff --git a/aws-lambda-java-runtime-interface-client/src/test/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoaderTest.java b/aws-lambda-java-runtime-interface-client/src/test/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoaderTest.java index aae2f1af..0d539f93 100644 --- a/aws-lambda-java-runtime-interface-client/src/test/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoaderTest.java +++ b/aws-lambda-java-runtime-interface-client/src/test/java/com/amazonaws/services/lambda/runtime/api/client/EventHandlerLoaderTest.java @@ -1,18 +1,33 @@ package com.amazonaws.services.lambda.runtime.api.client; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.CustomPojoSerializer; +import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.api.client.runtimeapi.dto.InvocationRequest; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class EventHandlerLoaderTest { @@ -59,6 +74,379 @@ void PojoHandlerTest_twoParams() throws Exception { assertSuccessfulInvocation(lambdaRequestHandler); } + @Test + void GenericInheritedRequestHandlerMethodSyntax_usesExactTypesWithCustomSerializer() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + new ExampleRequest("hello"), + "{\"result\":\"echo:hello\"}" + ); + withCustomSerializer(recorder, () -> { + String handler = ExampleLambdaFunction.class.getName() + "::handleRequest"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"hello\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"echo:hello\"}", result.toString()); + assertEquals(ExampleRequest.class, recorder.fromJsonStreamType.get()); + assertEquals(ExampleResponse.class, recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedRequestHandlerMethodSyntax_deserializesAndSerializesWithJackson() throws Exception { + clearTypeCache(); + String handler = ExampleLambdaFunction.class.getName() + "::handleRequest"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"hello\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"echo:hello\"}", result.toString()); + } + + @Test + void GenericInheritedPojoBaseWithoutRequestHandler_usesExactTypes() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + new ExampleRequest("pojo"), + "{\"result\":\"pojo:pojo\"}" + ); + withCustomSerializer(recorder, () -> { + String handler = ConcretePojoHandler.class.getName() + "::handle"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"pojo\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"pojo:pojo\"}", result.toString()); + assertEquals(ExampleRequest.class, recorder.fromJsonStreamType.get()); + assertEquals(ExampleResponse.class, recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedInterfaceDefaultMethod_usesExactTypes() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + new ExampleRequest("iface"), + "{\"result\":\"iface:iface\"}" + ); + withCustomSerializer(recorder, () -> { + String handler = ConcreteInterfaceHandler.class.getName() + "::handleDefault"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"iface\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"iface:iface\"}", result.toString()); + assertEquals(ExampleRequest.class, recorder.fromJsonStreamType.get()); + assertEquals(ExampleResponse.class, recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedMultiLevelNestedParameterizedAndArrayTypes_usesExactTypes() throws Exception { + Type expectedInputType = ConcreteMultiLevelFunction.class.getMethod("expectedInputSignature", List.class) + .getGenericParameterTypes()[0]; + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + Collections.singletonList(new ExampleRequest("multi")), + "[{\"result\":\"multi:multi\"}]" + ); + withCustomSerializer(recorder, () -> { + String handler = ConcreteMultiLevelFunction.class.getName() + "::handleRequest"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("[{\"value\":\"multi\"}]"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("[{\"result\":\"multi:multi\"}]", result.toString()); + Type actualInputType = recorder.fromJsonStreamType.get(); + assertTrue(actualInputType instanceof ParameterizedType); + assertEquals(expectedInputType, actualInputType); + assertEquals(ExampleResponse[].class, recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedBoundedRequestHandlerMethodSyntax_usesExactTypes() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + new ExampleRequest("bounded"), + "{\"result\":\"bounded:bounded\"}" + ); + withCustomSerializer(recorder, () -> { + String handler = BoundedLambdaFunction.class.getName() + "::handleRequest"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"bounded\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"bounded:bounded\"}", result.toString()); + assertEquals(ExampleRequest.class, recorder.fromJsonStreamType.get()); + assertEquals(ExampleResponse.class, recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedVoidReturnTypeMethodSyntax_skipsOutputSerialization() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + new ExampleRequest("void"), + "ignored" + ); + withCustomSerializer(recorder, () -> { + String handler = VoidLambdaFunction.class.getName() + "::handleRequest"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("{\"value\":\"void\"}"); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("null", result.toString()); + assertEquals(ExampleRequest.class, recorder.fromJsonStreamType.get()); + assertNull(recorder.toJsonType.get()); + }); + } + + @Test + void GenericInheritedMethodWithShadowedTypeVariableName_preservesMethodTypeVarAndResolvesClassTypeVar() throws Exception { + RecordingCustomSerializer recorder = new RecordingCustomSerializer( + "raw-input", + "{\"result\":\"shadowed\"}" + ); + withCustomSerializer(recorder, () -> { + String handler = ShadowedMethodHandler.class.getName() + "::handleShadowed"; + LambdaRequestHandler lambdaRequestHandler = getLambdaRequestHandler(handler); + InvocationRequest invocationRequest = getJsonInvocationRequest("\"raw-input\""); + + ByteArrayOutputStream result = lambdaRequestHandler.call(invocationRequest); + assertEquals("{\"result\":\"shadowed\"}", result.toString()); + Type actualInputType = recorder.fromJsonStreamType.get(); + assertNotNull(actualInputType); + assertTrue(actualInputType instanceof TypeVariable); + assertEquals(ShadowedBase.class.getDeclaredMethod("handleShadowed", Object.class, Context.class), + ((TypeVariable) actualInputType).getGenericDeclaration()); + assertEquals(ExampleResponse.class, recorder.toJsonType.get()); + }); + } + + private interface ThrowingRunnable { + void run() throws Exception; + } + + private static void withCustomSerializer(CustomPojoSerializer serializer, ThrowingRunnable action) throws Exception { + Field serializerField = PojoSerializerLoader.class.getDeclaredField("customPojoSerializer"); + serializerField.setAccessible(true); + Field initializedField = PojoSerializerLoader.class.getDeclaredField("initialized"); + initializedField.setAccessible(true); + try { + clearTypeCache(); + serializerField.set(null, serializer); + initializedField.set(null, true); + action.run(); + } finally { + clearTypeCache(); + serializerField.set(null, null); + initializedField.set(null, false); + } + } + + private static void clearTypeCache() throws Exception { + Field typeCacheField = EventHandlerLoader.class.getDeclaredField("typeCache"); + typeCacheField.setAccessible(true); + ((ThreadLocal) typeCacheField.get(null)).remove(); + } + + private static InvocationRequest getJsonInvocationRequest(String json) { + InvocationRequest invocationRequest = new InvocationRequest(); + invocationRequest.setContent(json.getBytes(StandardCharsets.UTF_8)); + invocationRequest.setId("id"); + invocationRequest.setXrayTraceId("traceId"); + return invocationRequest; + } + + private static final class RecordingCustomSerializer implements CustomPojoSerializer { + final AtomicReference fromJsonStreamType = new AtomicReference<>(); + final AtomicReference toJsonType = new AtomicReference<>(); + private final Object deserializedValue; + private final String serializedOutput; + + RecordingCustomSerializer(Object deserializedValue, String serializedOutput) { + this.deserializedValue = deserializedValue; + this.serializedOutput = serializedOutput; + } + + @Override + @SuppressWarnings("unchecked") + public T fromJson(InputStream input, Type type) { + fromJsonStreamType.set(type); + return (T) deserializedValue; + } + + @Override + @SuppressWarnings("unchecked") + public T fromJson(String input, Type type) { + fromJsonStreamType.set(type); + return (T) deserializedValue; + } + + @Override + public void toJson(T value, OutputStream output, Type type) { + toJsonType.set(type); + try { + output.write(serializedOutput.getBytes(StandardCharsets.UTF_8)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + public static class BaseRequest { + private String value; + + public BaseRequest() { + } + + public BaseRequest(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + } + + public static class ExampleRequest extends BaseRequest { + public ExampleRequest() { + } + + public ExampleRequest(String value) { + super(value); + } + } + + public static class BaseResponse { + private String result; + + public BaseResponse() { + } + + public BaseResponse(String result) { + this.result = result; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + } + + public static class ExampleResponse extends BaseResponse { + public ExampleResponse() { + } + + public ExampleResponse(String result) { + super(result); + } + } + + public abstract static class LambdaFunctionBase implements RequestHandler { + @Override + public OutputT handleRequest(InputT input, Context context) { + return doHandleRequest(input, context); + } + + protected abstract OutputT doHandleRequest(InputT input, Context context); + } + + public static class ExampleLambdaFunction extends LambdaFunctionBase { + @Override + protected ExampleResponse doHandleRequest(ExampleRequest input, Context context) { + return new ExampleResponse("echo:" + input.getValue()); + } + } + + public abstract static class GenericPojoBase { + public O handle(I input) { + return process(input); + } + + protected abstract O process(I input); + } + + public static class ConcretePojoHandler extends GenericPojoBase { + @Override + protected ExampleResponse process(ExampleRequest input) { + return new ExampleResponse("pojo:" + input.getValue()); + } + } + + public interface GenericHandlerInterface { + default O handleDefault(I input, Context context) { + return process(input); + } + + O process(I input); + } + + public static class ConcreteInterfaceHandler implements GenericHandlerInterface { + @Override + public ExampleResponse process(ExampleRequest input) { + return new ExampleResponse("iface:" + input.getValue()); + } + } + + public abstract static class MidLevelGenericBase extends LambdaFunctionBase, RespT[]> { + } + + public static class ConcreteMultiLevelFunction extends MidLevelGenericBase { + @SuppressWarnings("unused") + public void expectedInputSignature(List items) { + } + + @Override + protected ExampleResponse[] doHandleRequest(List input, Context context) { + return new ExampleResponse[]{new ExampleResponse("multi:" + input.get(0).getValue())}; + } + } + + public abstract static class BoundedLambdaBase + implements RequestHandler { + @Override + public OutputT handleRequest(InputT input, Context context) { + return process(input); + } + + protected abstract OutputT process(InputT input); + } + + public static class BoundedLambdaFunction extends BoundedLambdaBase { + @Override + protected ExampleResponse process(ExampleRequest input) { + return new ExampleResponse("bounded:" + input.getValue()); + } + } + + public static class VoidLambdaFunction extends LambdaFunctionBase { + @Override + protected Void doHandleRequest(ExampleRequest input, Context context) { + Objects.requireNonNull(input); + return null; + } + } + + public abstract static class ShadowedBase { + @SuppressWarnings("hiding") + public OutputT handleShadowed(InputT input, Context context) { + return convert(input); + } + + protected abstract OutputT convert(Object input); + } + + public static class ShadowedMethodHandler extends ShadowedBase { + @Override + protected ExampleResponse convert(Object input) { + return new ExampleResponse("shadowed"); + } + } + private LambdaRequestHandler getLambdaRequestHandler(String handler) throws ClassNotFoundException { ClassLoader cl = this.getClass().getClassLoader(); HandlerInfo handlerInfo = HandlerInfo.fromString(handler, cl);