Skip to content

Recipes

Dave Moten edited this page Nov 26, 2021 · 20 revisions

aws-lightweight-client-java recipes

Here are examples of usage for some common use cases so you don't have to research the AWS API too much!

S3

Create a bucket

String xml = Xml
    .create("CreateBucketConfiguration")
    .a("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
    .e("LocationConstraint").content(region)
    .toString();       
s3.path(bucketName)
    .method(HttpMethod.PUT)
    .requestBody(xml)
    .execute();

Delete a bucket

s3
    .path(bucketName) 
    .method(HttpMethod.DELETE) 
    .execute();

Put an object

s3
    .path(bucketName, objectName)
    .method(HttpMethod.PUT)
    .requestBody("hi there")
    .execute();

Put an object with metadata

s3
    .path(bucketName, objectName)
    .method(HttpMethod.PUT)
    .requestBody("hi there")
    .metadata("category", "something")
    .execute();

Check object exists

boolean exists = s3
  .path(bucket, objectName)
  .method(HttpMethod.HEAD)
  .exists();

Note that exists throws if status code is not 2xx or 404.

Read an object (text)

String text = s3
    .path(bucketName, objectName)
    .responseAsUtf8();

Read an object (bytes)

byte[] bytes = s3
    .path(bucketName, objectName)
    .responseAsBytes();      

Read an object (InputStream)

ResponseInputStream r = s3
    .path(bucketName, objectName)
    .responseInputStream);
System.out.println(r.statusCode());

Read an object with metadata

Response r = s3
    .path(bucketName, objectName)
    .response();
System.out.println("response ok=" + response.isOk());
System.out.println(r.content().length + " chars read");
System.out.println("category=" + r.metadata("category").orElse(""));

Read Last-Modified of an object

Response r = s3
  .path(bucket, objectName)
  .method(HttpMethod.HEAD)
  .response();
if (r.exists()) {
    Instant lastModified = r.firstHeaderFullDate("Last-Modified").get();
}

Delete an object

s3.path(bucketName, objectName) 
    .method(HttpMethod.DELETE) 
    .execute();

Multipart upload a file

Multipart 
  .s3(s3)
  .bucket("mybucket")
  .key("mykey")
  .upload(file);

Multipart upload using an InputStream factory

Multipart 
  .s3(s3)
  .bucket("mybucket")
  .key("mykey")
  .upload(() -> createInputStream());

Multipart upload using an OutputStream

try (MultipartOutputStream out = Multipart 
      .s3(s3)
      .bucket("mybucket")
      .key("mykey")
      .outputStream()) {
  out.write(bytes, 100, 1000);
  out.write(bytes2);
}

Multipart upload raw commands

For info only, you should use the Multipart helper above!!

// want to upload two large text fragments (at least 5MB each)
String text1 = ...
String text2 = ...

// start new multipart upload
String uploadId = s3 
        .path(bucketName, objectName) 
        .query("uploads") 
        .method(HttpMethod.POST) 
        .responseAsXml() 
        .content("UploadId");

// upload part 1
String tag1 = s3.path(bucketName, objectName) 
        .method(HttpMethod.PUT) 
        .query("partNumber", "1") 
        .query("uploadId", uploadId) 
        .requestBody(text1) 
        .response() 
        .headers() 
        .get("ETag") 
        .get(0);

// upload part 2
String tag2 = s3.path(bucketName, objectName) 
        .method(HttpMethod.PUT) 
        .query("partNumber", "2") 
        .query("uploadId", uploadId) 
        .requestBody(text2) 
        .response() 
        .headers() 
        .get("ETag") 
        .get(0);

// complete upload
String xml = Xml 
        .create("CompleteMultipartUpload") 
        .attribute("xmlns", "http:s3.amazonaws.com/doc/2006-03-01/") 
        .element("Part") 
        .element("ETag").content(tag1.substring(1, tag1.length() - 1)) 
        .up() 
        .element("PartNumber").content("1") 
        .up().up() 
        .element("Part") 
        .element("ETag").content(tag2.substring(1, tag2.length() - 1)) 
        .up() 
        .element("PartNumber").content("2") 
        .toString();

s3.path(bucketName, objectName) 
        .method(HttpMethod.POST) 
        .query("uploadId", uploadId) 
        .header("Content-Type", "application/xml") 
        .unsignedPayload() 
        .requestBody(xml) 
        .execute();

Presigned url to get object

String url = s3
    .path(bucketName, objectName)
    .presignedUrl(1, TimeUnit.HOURS);

Compare that bit of code to the verbosity of AWS SDK v2!

SQS

Create a queue

sqs.query("Action", "CreateQueue") 
    .query("QueueName", queueName) 
    .execute();

Create a FIFO queue

String queueUrl = sqs.query("Action", "CreateQueue") 
  .query("QueueName", queueName(applicationName, key)) 
  .attribute("FifoQueue", "true") 
  .attribute("ContentBasedDeduplication", "true") 
  .attribute("MessageRetentionPeriod", String.valueOf(TimeUnit.DAYS.toSeconds(14))) 
  .attribute("VisibilityTimeout", "30") 
  .responseAsXml() 
  .content("CreateQueueResult", "QueueUrl");

Get queue url

String queueUrl = sqs 
    .query("Action", "GetQueueUrl") 
    .query("QueueName", queueName) 
    .responseAsXml() 
    .content("GetQueueUrlResult", "QueueUrl");

Send a message to a queue

sqs.url(queueUrl) 
    .query("Action", "SendMessage") 
    .query("MessageBody", "hi there") 
    .execute();

Read from a queue

List<XmlElement> list;
do {
    list = sqs.url(queueUrl)
        .query("Action", "ReceiveMessage")
        .responseAsXml()
        .child("ReceiveMessageResult")
        .children();

    list.forEach(x -> {
	    String msg = x.child("Body").content();
	    System.out.println(msg);
	    // mark message as read
	    sqs.url(queueUrl)
	            .query("Action", "DeleteMessage")
	            .query("ReceiptHandle", x.child("ReceiptHandle").content())
	            .execute();
    });
} while (!list.isEmpty());

Delete a queue

sqs.url(queueUrl) 
    .query("Action", "DeleteQueue") 
    .execute();

SNS

Publish a message

sns
  .query("Action", "Publish") //
  .query("TopicArn", arn) //
  .query("Message", message) //
  .execute();