2

Is there a way to handle more than one event objects in Java for AWS Lambda? For example, when handling an SNSEvent, I can do the following:

public class Hello implements RequestHandler<SNSEvent, Response> {
    public Response handleRequest(SNSEvent event, Context context) {
         //handle SNSEvent here
    }
}

Is there a way I can handle both SNSEvent and SQSEvent in the same lambda?

1 Answer 1

4

There are multiple ways to handle a Lambda event in Java. You're showing the POJO model with AWS defined POJO's where the deserialization of the object is handled for you.

However, there is also the IO Stream method. This gives you an InputStream and OutputStream to handle yourself. The code derived from the second link above could start something like:

public class Hello implements RequestStreamHandler{
    public void handler(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        // copy and convert the inputStream
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }

        String inputString = result.toString("UTF-8");
        // now try to convert to a SNSEvent using Google GSON
        try {
            SNSEvent snsEvent = new Gson().fromJson(inputString, SNSEvent.class);
        }
        catch( JsonSyntaxException jse ) {
            // this is where it's weird - what if it is really bad JSON?
        }
    }
}

Ultimately what this does is take the JSON input, copies it to a String, and then used GSON to convert to attempt to convert to an object. You could have any number of objects that the code tries to convert to. The GSON fromJson method throws a JsonSyntaxException if it can't be converted. But it would also do that if there was totally garbage JSON so you need to be a bit careful.

I'm showing it with GSON as I've had too many weird interactions with Jackson which is what Lambda used under the covers for JSON parsing.

But this allows you to handle the InputStream yourself, deciding what to do with the input and sending your own Response in the OutputStream.

Sign up to request clarification or add additional context in comments.

2 Comments

Would there be a way to differentiate an SNSEvent from a SQSEvent? Or would I have to try converting to one. If it fails, try the conversion to the other?
There may be some introspection you can do on the String (i.e. does it contain a particular substring) you build but otherwise I would do a series of catch / try blocks to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.