Quarkus - Amazon S3 Client

Amazon S3 is an object storage service. It can be employed to store any type of object which allows for uses like storage for Internet applications, backup and recovery, disaster recovery, data archives, data lakes for analytics, any hybrid cloud storage. This extension provides functionality that allows the client to communicate with the service when running in Quarkus. You can find more information about S3 at the Amazon S3 website.

The S3 extension is based on AWS Java SDK 2.x. It’s a major rewrite of the 1.x code base that offers two programming models (Blocking & Async).

The Quarkus extension supports two programming models:

  • Blocking access using URL Connection HTTP client (by default) or the Apache HTTP Client

  • Asynchronous programming based on JDK’s CompletableFuture objects and the Netty HTTP client.

In this guide, we see how you can get your REST services to use S3 locally and on AWS.

Prerequisites

To complete this guide, you need:

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • an IDE

  • Apache Maven 3.5.3+

  • AWS Command line interface

  • An AWS Account to access the S3 service. Before you can use the AWS SDKs with Amazon S3, you must get an AWS access key ID and secret access key.

  • Optionally, Docker for your system to run S3 locally for testing purposes

Provision S3 locally

The easiest way to start working with S3 is to run a local instance as a container.

  1. docker run -it --publish 8008:4572 -e SERVICES=s3 -e START_WEB=0 localstack/localstack

This starts a S3 instance that is accessible on port 8008.

Create an AWS profile for your local instance using AWS CLI:

  1. $ aws configure --profile localstack
  2. AWS Access Key ID [None]: test-key
  3. AWS Secret Access Key [None]: test-secret
  4. Default region name [None]: us-east-1
  5. Default output format [None]:

Create a S3 bucket

Create a S3 bucket using AWS CLI

  1. aws s3 mb s3://quarkus.s3.quickstart --profile localstack --endpoint-url=http://localhost:8008

Solution

The application built here allows to manage files stored in Amazon S3.

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the amazon-s3-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=amazon-s3-quickstart \
  4. -DclassName="org.acme.s3.S3SyncClientResource" \
  5. -Dpath="/s3" \
  6. -Dextensions="resteasy-jsonb,amazon-s3"
  7. cd amazon-s3-quickstart

This command generates a Maven structure importing the RESTEasy/JAX-RS and S3 Client extensions. After this, the amazon-s3 extension has been added to your pom.xml.

Then, we’ll add the following dependency to support multipart/form-data requests:

  1. <dependency>
  2. <groupId>org.jboss.resteasy</groupId>
  3. <artifactId>resteasy-multipart-provider</artifactId>
  4. </dependency>

Setting up the model

In this example, we will create an application to manage a list of files. The example application will demonstrate the two programming models supported by the extension.

Because the primary goal of our application is to upload a file into the S3 bucket, we need to setup the model we will be using to define the multipart/form-data payload, in the form of a MultipartBody POJO.

Create a org.acme.s3.FormData class as follows:

  1. package org.acme.s3;
  2. import java.io.InputStream;
  3. import javax.ws.rs.FormParam;
  4. import javax.ws.rs.core.MediaType;
  5. import org.jboss.resteasy.annotations.providers.multipart.PartType;
  6. public class FormData {
  7. @FormParam("file")
  8. @PartType(MediaType.APPLICATION_OCTET_STREAM)
  9. public InputStream data;
  10. @FormParam("filename")
  11. @PartType(MediaType.TEXT_PLAIN)
  12. public String fileName;
  13. @FormParam("mimetype")
  14. @PartType(MediaType.TEXT_PLAIN)
  15. public String mimeType;
  16. }

The class defines three fields:

  • data that fill capture stream of uploaded bytes from the client

  • fileName that captures a filename as provided by the submited form

  • mimeType content type of the uploaded file

In the second step let’s create a bean that will represent a file in a Amazon S3 bucket as follows:

  1. package org.acme.s3;
  2. import software.amazon.awssdk.services.s3.model.S3Object;
  3. public class FileObject {
  4. private String objectKey;
  5. private Long size;
  6. public FileObject() {
  7. }
  8. public static FileObject from(S3Object s3Object) {
  9. FileObject file = new FileObject();
  10. if (s3Object != null) {
  11. file.setObjectKey(s3Object.key());
  12. file.setSize(s3Object.size());
  13. }
  14. return file;
  15. }
  16. public String getObjectKey() {
  17. return objectKey;
  18. }
  19. public Long getSize() {
  20. return size;
  21. }
  22. public FileObject setObjectKey(String objectKey) {
  23. this.objectKey = objectKey;
  24. return this;
  25. }
  26. public FileObject setSize(Long size) {
  27. this.size = size;
  28. return this;
  29. }
  30. }

Nothing fancy. One important thing to note is that having a default constructor is required by the JSON serialization layer. The static from method creates a bean based on the S3Object object provided by the S3 client response when listing all the objects in a bucket.

Create JAX-RS resource

Now create a org.acme.s3.CommonResource that will consist of methods to prepare S3 request to get object from a S3 bucket, or to put file into a S3 bucket. Note a configuration property bucket.name is defined here as the request method required name of the S3 bucket.

  1. package org.acme.s3;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.nio.file.Files;
  5. import java.nio.file.StandardCopyOption;
  6. import java.util.Date;
  7. import java.util.UUID;
  8. import org.eclipse.microprofile.config.inject.ConfigProperty;
  9. import software.amazon.awssdk.services.s3.model.GetObjectRequest;
  10. import software.amazon.awssdk.services.s3.model.PutObjectRequest;
  11. abstract public class CommonResource {
  12. private final static String TEMP_DIR = System.getProperty("java.io.tmpdir");
  13. @ConfigProperty(name = "bucket.name")
  14. String bucketName;
  15. protected PutObjectRequest buildPutRequest(FormData formData) {
  16. return PutObjectRequest.builder()
  17. .bucket(bucketName)
  18. .key(formData.fileName)
  19. .contentType(formData.mimeType)
  20. .build();
  21. }
  22. protected GetObjectRequest buildGetRequest(String objectKey) {
  23. return GetObjectRequest.builder()
  24. .bucket(bucketName)
  25. .key(objectKey)
  26. .build();
  27. }
  28. protected File tempFilePath() {
  29. return new File(TEMP_DIR, new StringBuilder().append("s3AsyncDownloadedTemp")
  30. .append((new Date()).getTime()).append(UUID.randomUUID())
  31. .append(".").append(".tmp").toString());
  32. }
  33. protected File uploadToTemp(InputStream data) {
  34. File tempPath;
  35. try {
  36. tempPath = File.createTempFile("uploadS3Tmp", ".tmp");
  37. Files.copy(data, tempPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
  38. } catch (Exception ex) {
  39. throw new RuntimeException(ex);
  40. }
  41. return tempPath;
  42. }
  43. }

Then, create a org.acme.s3.S3SyncClientResource that will provides an API to upload/download files as well as to list all the files in a bucket.

  1. package org.acme.s3;
  2. import java.io.ByteArrayOutputStream;
  3. import java.util.Comparator;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. import javax.inject.Inject;
  7. import javax.ws.rs.Consumes;
  8. import javax.ws.rs.GET;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.core.MediaType;
  13. import javax.ws.rs.core.Response;
  14. import javax.ws.rs.core.Response.ResponseBuilder;
  15. import javax.ws.rs.core.Response.Status;
  16. import javax.ws.rs.core.StreamingOutput;
  17. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  18. import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
  19. import software.amazon.awssdk.core.sync.RequestBody;
  20. import software.amazon.awssdk.core.sync.ResponseTransformer;
  21. import software.amazon.awssdk.services.s3.S3Client;
  22. import software.amazon.awssdk.services.s3.model.GetObjectResponse;
  23. import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
  24. import software.amazon.awssdk.services.s3.model.PutObjectResponse;
  25. import software.amazon.awssdk.services.s3.model.S3Object;
  26. @Path("/s3")
  27. public class S3SyncClientResource extends CommonResource {
  28. @Inject
  29. S3Client s3;
  30. @POST
  31. @Path("upload")
  32. @Consumes(MediaType.MULTIPART_FORM_DATA)
  33. public Response uploadFile(@MultipartForm FormData formData) throws Exception {
  34. if (formData.fileName == null || formData.fileName.isEmpty()) {
  35. return Response.status(Status.BAD_REQUEST).build();
  36. }
  37. if (formData.mimeType == null || formData.mimeType.isEmpty()) {
  38. return Response.status(Status.BAD_REQUEST).build();
  39. }
  40. PutObjectResponse putResponse = s3.putObject(buildPutRequest(formData),
  41. RequestBody.fromFile(uploadToTemp(formData.data)));
  42. if (putResponse != null) {
  43. return Response.ok().status(Status.CREATED).build();
  44. } else {
  45. return Response.serverError().build();
  46. }
  47. }
  48. @GET
  49. @Path("download/{objectKey}")
  50. @Produces(MediaType.APPLICATION_OCTET_STREAM)
  51. public Response downloadFile(@PathParam("objectKey") String objectKey) {
  52. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  53. GetObjectResponse object = s3.getObject(buildGetRequest(objectKey), ResponseTransformer.toOutputStream(baos));
  54. ResponseBuilder response = Response.ok((StreamingOutput) output -> baos.writeTo(output));
  55. response.header("Content-Disposition", "attachment;filename=" + objectKey);
  56. response.header("Content-Type", object.contentType());
  57. return response.build();
  58. }
  59. @GET
  60. @Produces(MediaType.APPLICATION_JSON)
  61. public List<FileObject> listFiles() {
  62. ListObjectsRequest listRequest = ListObjectsRequest.builder().bucket(bucketName).build();
  63. //HEAD S3 objects to get metadata
  64. return s3.listObjects(listRequest).contents().stream().sorted(Comparator.comparing(S3Object::lastModified).reversed())
  65. .map(FileObject::from).collect(Collectors.toList());
  66. }
  67. }

Configuring S3 clients

Both S3 clients (sync and async) are configurable via the application.properties file that can be provided in the src/main/resources directory.

You need to add to the classpath a proper implementation of the sync client. By default the extension uses the URL connection HTTP client, so add a URL connection client dependency to the pom.xml file:
  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>url-connection-client</artifactId>
  4. </dependency>

If you want to use Apache HTTP client instead, configure it as follows:

  1. quarkus.s3.sync-client.type=apache

And add following dependency to the application pom.xml:

  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>apache-client</artifactId>
  4. </dependency>

For asynchronous client refer to Going asynchronous for more information.

If you’re going to use a local S3 instance, configure it as follows:

  1. quarkus.s3.endpoint-override=http://localhost:8008
  2. quarkus.s3.aws.region=us-east-1
  3. quarkus.s3.aws.credentials.type=static
  4. quarkus.s3.aws.credentials.static-provider.access-key-id=test-key
  5. quarkus.s3.aws.credentials.static-provider.secret-access-key=test-secret
  6. bucket.name=quarkus.s3.quickstart
  • quarkus.s3.aws.region - It’s required by the client, but since you’re using a local S3 instance you can pick any valid AWS region.

  • quarkus.s3.aws.credentials.type - Set static credentials provider with any values for access-key-id and secret-access-key

  • quarkus.s3.endpoint-override - Override the S3 client to use a local instance instead of an AWS service

  • bucket.name - Name of the S3 bucket

If you want to work with an AWS account, you’d need to set it with:

  1. bucket.name=<your-bucket-name>
  2. quarkus.s3.aws.region=<YOUR_REGION>
  3. quarkus.s3.aws.credentials.type=default
  • bucket.name - name of the S3 bucket on your AWS account.

  • quarkus.s3.aws.region you should set it to the region where your S3 bucket was created,

  • quarkus.s3.aws.credentials.type - use the default credentials provider chain that looks for credentials in this order:

    • Java System Properties - aws.accessKeyId and aws.secretAccessKey

    • Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY

    • Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI

    • Credentials delivered through the Amazon ECS if the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable is set and the security manager has permission to access the variable,

    • Instance profile credentials delivered through the Amazon EC2 metadata service

Creating a frontend

Now let’s add a simple web page to interact with our S3SyncClientResource. Quarkus automatically serves static resources located under the META-INF/resources directory. In the src/main/resources/META-INF/resources directory, add a s3.html file with the content from this s3.html file in it.

You can now interact with your REST service:

  • start Quarkus with ./mvnw compile quarkus:dev

  • open a browser to [http://localhost:8080/s3.html](http://localhost:8080/s3.html)

  • upload new file to the current S3 bucket via the form and see the list of files in the bucket

Next steps

Packaging

Packaging your application is as simple as ./mvnw clean package. It can be run with java -jar target/amazon-s3-quickstart-1.0-SNAPSHOT-runner.jar.

With GraalVM installed, you can also create a native executable binary: ./mvnw clean package -Dnative. Depending on your system, that will take some time.

Going asynchronous

Thanks to the AWS SDK v2.x used by the Quarkus extension, you can use the asynchronous programming model out of the box.

Create a org.acme.s3.S3AsyncClientResource that will be similar to our S3SyncClientResource but using an asynchronous programming model.

  1. package org.acme.s3;
  2. import java.io.File;
  3. import java.util.Comparator;
  4. import java.util.List;
  5. import java.util.stream.Collectors;
  6. import javax.inject.Inject;
  7. import javax.ws.rs.Consumes;
  8. import javax.ws.rs.GET;
  9. import javax.ws.rs.POST;
  10. import javax.ws.rs.Path;
  11. import javax.ws.rs.Produces;
  12. import javax.ws.rs.core.MediaType;
  13. import javax.ws.rs.core.Response;
  14. import javax.ws.rs.core.Response.Status;
  15. import org.jboss.resteasy.annotations.jaxrs.PathParam;
  16. import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
  17. import io.smallrye.mutiny.Uni;
  18. import software.amazon.awssdk.core.async.AsyncRequestBody;
  19. import software.amazon.awssdk.core.async.AsyncResponseTransformer;
  20. import software.amazon.awssdk.services.s3.S3AsyncClient;
  21. import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
  22. import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
  23. import software.amazon.awssdk.services.s3.model.S3Object;
  24. @Path("/async-s3")
  25. public class S3AsyncClientResource extends CommonResource {
  26. @Inject
  27. S3AsyncClient s3;
  28. @POST
  29. @Path("upload")
  30. @Consumes(MediaType.MULTIPART_FORM_DATA)
  31. public Uni<Response> uploadFile(@MultipartForm FormData formData) throws Exception {
  32. if (formData.fileName == null || formData.fileName.isEmpty()) {
  33. return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
  34. }
  35. if (formData.mimeType == null || formData.mimeType.isEmpty()) {
  36. return Uni.createFrom().item(Response.status(Status.BAD_REQUEST).build());
  37. }
  38. return Uni.createFrom()
  39. .completionStage(() -> {
  40. return s3.putObject(buildPutRequest(formData), AsyncRequestBody.fromFile(uploadToTemp(formData.data)));
  41. })
  42. .onItem().ignore().andSwitchTo(Uni.createFrom().item(Response.created(null).build()))
  43. .onFailure().recoverWithItem(th -> {
  44. th.printStackTrace();
  45. return Response.serverError().build();
  46. });
  47. }
  48. @GET
  49. @Path("download/{objectKey}")
  50. @Produces(MediaType.APPLICATION_OCTET_STREAM)
  51. public Uni<Response> downloadFile(@PathParam("objectKey") String objectKey) throws Exception {
  52. File tempFile = tempFilePath();
  53. return Uni.createFrom()
  54. .completionStage(() -> s3.getObject(buildGetRequest(objectKey), AsyncResponseTransformer.toFile(tempFile)))
  55. .onItem()
  56. .apply(object -> Response.ok(tempFile)
  57. .header("Content-Disposition", "attachment;filename=" + objectKey)
  58. .header("Content-Type", object.contentType()).build());
  59. }
  60. @GET
  61. @Produces(MediaType.APPLICATION_JSON)
  62. public Uni<List<FileObject>> listFiles() {
  63. ListObjectsRequest listRequest = ListObjectsRequest.builder()
  64. .bucket(bucketName)
  65. .build();
  66. return Uni.createFrom().completionStage(() -> s3.listObjects(listRequest))
  67. .onItem().transform(result -> toFileItems(result));
  68. }
  69. private List<FileObject> toFileItems(ListObjectsResponse objects) {
  70. return objects.contents().stream()
  71. .sorted(Comparator.comparing(S3Object::lastModified).reversed())
  72. .map(FileObject::from).collect(Collectors.toList());
  73. }
  74. }

You need the RESTEasy Mutiny support for asynchronous programming. Add the dependency to the pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-resteasy-mutiny</artifactId>
  4. </dependency>

Or you can alternatively run this command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="resteasy-mutiny"

And add the Netty HTTP client dependency to the pom.xml:

  1. <dependency>
  2. <groupId>software.amazon.awssdk</groupId>
  3. <artifactId>netty-nio-client</artifactId>
  4. </dependency>

Configuration Reference

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.

About the MemorySize format

A size configuration option recognises string in this format (shown as a regular expression): [0-9]+[KkMmGgTtPpEeZzYy]?. If no suffix is given, assume bytes.