Search code examples
amazon-web-servicesamazon-sns

How do I handle incoming SNS notifications using the Amazon's SNS SDK for Java?


I have a java application that needs to process incoming push message notifications coming from an SNS topic. This is the code that I have so far:

    CreatePlatformEndpointRequest endpointRequest = new CreatePlatformEndpointRequest() //https://docs.aws.amazon.com/sns/latest/dg/mobile-platform-endpoint.html
            .withToken(platformApplicationArnToken)
            .withPlatformApplicationArn(platformApplicationArn)
            .withCustomUserData("This platform endpoint is used by " + applicationInstanceName);
    CreatePlatformEndpointResult platformEndpoint = amazonSnsClient.createPlatformEndpoint(endpointRequest);
    log.info("The Application Platform endpoint that this application instance will use is " + platformEndpoint.getEndpointArn());
    SubscribeRequest subscribeRequest = getSubscribeRequest(emailUnsubscribeARNSettingsMap.get("topicArn"),
                                                            emailUnsubscribeARNSettingsMap.get("protocol"),
                                                            platformEndpoint.getEndpointArn());
    SubscribeResult result = amazonSnsClient.subscribe(subscribeRequest);

I'm able to subscribe to a topic using the AmazonSNS client's subscribe method. But i have no idea how i should write a handler that is automatically invoked as soon as the app gets a notification through its subscription.

I've looked at all the methods that the AmazonSNS client has but none of them lets you write a handler for incoming notifications. You can push notifications from the app to the subscribed topic using the publish() method but that's not what I want.

So, using the SNS SDK, how do i process incoming push notifications?

PS: I am using Push messages but the app I have is not a mobile app. It is a regular java application that runs on an EC2 instance. I want to use Push messages instead of notifications via Http/s because push messages have a larger free tier and are also cheaper.


Solution

  • As you stated - the SNS Java Client does not support what you are describing. You can use the client to subscribe to topics, publish messages, and so on. However, it does not support use of an event handler.

    When working with Java and this AWS service, you should use AWS SDK for Java v2. The V1 which you are using is NOT Best practice as described in this AWS SDK Page. The 1st link references the V2 SNS Java client.