How to Receive a Message from AWS SQS with JAX-RS

import static java.lang.System.out;
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.Form;
import javax.ws.rs.core.Response;

@SuppressWarnings("serial")
@WebServlet(name = "SampleSqsServlet", value = "/")
public final class SampleSqsServlet 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/sqs/aws4_request\n" + sha256Hex("POST\n/accountId/SampleQueue\n\nhost:host\nx-amz-date:longDate\n\nhost;x-amz-date\n" + sha256Hex("Action=ReceiveMessage"));

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

    final Response res = client.target("queueUrl").request().header("X-Amz-Date", longDate).header("Authorization", "AWS4-HMAC-SHA256 Credential=accessKeyId/shortDate/regionName/sqs/aws4_request, SignedHeaders=host;x-amz-date, Signature=" + signature).post(Entity.form(new Form().param("Action", "ReceiveMessage")));

    out.println(res.readEntity(String.class));

    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