How to Send a Push Notification to AWS SNS with JAX-RS

import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256;
import static org.apache.commons.codec.digest.HmacUtils.hmacSha256Hex;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

@SuppressWarnings("serial")
@WebServlet(name = "SampleSnsServlet", value = "/")
public final class SampleSnsServlet extends HttpServlet {

  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final Client client = ClientBuilder.newClient();

    final String stringToSign = "AWS4-HMAC-SHA256\nlongDate\nshortDate/regionName/sns/aws4_request\n" + sha256Hex("POST\n/accountId/SampleTopic\n\nhost:host\nx-amz-date:longDate\n\nhost;x-amz-date\n" + sha256Hex("Action=Publish&Message=Simples+Assim&TopicArn=topicArn"));

    final String signature = hmacSha256Hex(hmacSha256(hmacSha256(hmacSha256(hmacSha256("AWS4secretKey", shortDate), "regionName".getBytes()), "sns".getBytes()), "aws4_request".getBytes()), stringToSign.getBytes());

    final MultivaluedMap<String, String> params = new MultivaluedHashMap<>();

    params.putSingle("Action", "Publish");

    params.putSingle("Message", "Simples Assim");

    params.putSingle("TopicArn", "topicArn");

    client.target("queueUrl").request().header("X-Amz-Date", longDate).header("Authorization", "AWS4-HMAC-SHA256 Credential=accessKeyId/shortDate/regionName/sns/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + signature).post(Entity.form(params));

    client.close();
  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s