0
votes

I am new to AWS.I am trying to attach an object to AWS SQS Message (software.amazon.awssdk.services.sqs.model.Message)

AWS Documentation on the matter is outdated (https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-java-send-message-with-attributes.html)
(does not compile as written for a previous version. It is easily fixed to be compilable, but is not very useful)

There are many ways to attach a String, but to attach an object the only way seems to be
1 putting the SourceObject into an "SdkBytes"
2 making a Collection of triples (Map<String,MessagAttributes>) to define the name, dataType, and "SdkBytes"
3 feed this Collection into a builder

It seems to me this is the process:
SourceObject -> some InputStreamer -> "SdkBytes" object -> MessageAttributes Object -> AttributesMap <String,MessageAttributes> -> Message.builder().attributes()

Can anyone point me towards a cleaner / better solution? I expect something should exist that looks like:
Message.Builder().MessageBody(JsonObject j).build();
Or Message.Builder().MessageBody(File f).build();

1

1 Answers

1
votes

I'm not sure I'm following what the issue is. If I wanted to send a file I could do:

FileInputStream fileInputStream = new FileInputStream(fileName);
SendMessageRequest sendMessageRequest = SendMessageRequest.builder()
            .queueUrl(queueUrl)
            .messageBody(Base64.getEncoder().encodeToString(fileInputStream.readAllBytes()))
            .build();
sqsClient.sendMessage(sendMessageRequest);

I have to use Base64 as SQS messages must be, according the the docs:

A message can include only XML, JSON, and unformatted text

If you're positive that your file is only text you don't need to Base64 encode. Realize that the maximum size of the message body is 256KB and that Base64 encoding will increase the file size by roughly 1/3.

In the case of an ASCII file, you'd do something like:

SendMessageRequest sendMessageRequest = SendMessageRequest.builder()
            .queueUrl(queueUrl)
            .messageBody(Files.readString(Paths.get(fileName), StandardCharsets.US_ASCII))
            .build();
sqsClient.sendMessage(sendMessageRequest)

If you wanted to send a JsonObject (and I mean javax.json.JsonObject in Java EE as this is a highly overloaded Java class name) you could do:

JsonObject jsonObject = Json.createObjectBuilder()
        .add("message", "hello")
        .build();
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stringWriter);
jsonWriter.write(jsonObject);

SendMessageRequest sendMessageRequest = SendMessageRequest.builder()
        .queueUrl(queueUrl)
        .messageBody(stringWriter.toString())
        .build();
sqsClient.sendMessage(sendMessageRequest);

This one doesn't require Base64 as it should be regular Json.

Sure, you've got to convert the file or the Json to a String but that really isn't that bad.