Java / Gradle

Use the Micronaut Object Storage API to store files in Amazon S3

Learn how to upload and retrieve files from Amazon S3 using the Micronaut Object Storage API

Álvaro Sánchez-Mariscal
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

It will be a microservice to store, retrieve and delete profile pictures for users.

What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE (e.g. IntelliJ IDEA)

  • JDK 21 or greater installed with JAVA_HOME configured appropriately

  • An AWS account with:

    • An IAM user with permissions to create and manage AWS S3 buckets.

    • The AWS CLI configured to use the IAM user above.

Amazon Web Services (AWS)

If you don’t have one already, create an AWS Account.

AWS CLI

Follow the AWS documentation for installing or updating the latest version of the AWS CLI.

Administrator IAM user

Instead of using your AWS root account, it is recommended that you use an IAM administrative user. If you don’t have one already, follow the steps below to create one:

aws iam create-group --group-name Administrators
aws iam create-user --user-name Administrator
aws iam add-user-to-group --user-name Administrator --group-name Administrators
aws iam attach-group-policy --group-name Administrators --policy-arn $(aws iam list-policies --query 'Policies[?PolicyName==`AdministratorAccess`].{ARN:Arn}' --output text)
aws iam create-access-key --user-name Administrator

Then, run aws configure to configure your AWS CLI to use the Administrator IAM user just created.

Solution

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.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=object-storage-aws,graalvm \
    --build=gradle \
    --lang=java \
    --test=junit
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add object-storage-aws, and graalvm features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Create an Amazon S3 bucket

First, we are going to create an Amazon S3 bucket using the aws CLI:

aws s3api create-bucket --bucket micronaut-guide-object-storage --region=us-east-1
Warning
Bucket names must be unique across all AWS accounts.
Tip

If you want to create the bucket in a region other than us-east-1, you need additional parameters. For example, to create the bucket in the eu-west-3 region:

aws s3api create-bucket \
          --bucket micronaut-guide-object-storage \
          --region eu-west-3 \
          --create-bucket-configuration LocationConstraint=eu-west-3

Then, configure the bucket in application.properties:

src/main/resources/application.properties
micronaut.object-storage.aws.default.bucket=micronaut-guide-object-storage

Controller API

Let’s define an interface with the endpoints of the profile pictures microservice:

src/main/java/example/micronaut/ProfilePicturesApi.java

And then, an implementation with the required dependencies:

java/src/main/java/example/micronaut/ProfilePicturesController.java

request. When uploading a picture, we will use the host to build an absolute URL for the Location header. Learn more about Host Resolution.

Upload endpoint

Implement the upload endpoint by receiving the file from the HTTP client via CompletedFileUpload, and the userId path parameter. Upload it to S3 using AwsS3Operations, and then return its ETag in an HTTP response header to the client:

java/src/main/java/example/micronaut/ProfilePicturesController.java

object. It also has a getNativeResponse() method that can be used for accessing the vendor-specific response object, in this case PutObjectResponse. <.> The upload can be customised by using Amazon’s PutObjectRequest.Builder methods. <.> We return the absolute URL of the resource in the Location header. <.> The response object contains some common properties for all cloud vendors, such as the ETag, that is sent in a header to the client.

Download endpoint

For the download endpoint, simply retrieve the entry from the expected key and transform it into a StreamedFile:

java/src/main/java/example/micronaut/ProfilePicturesController.java

AwsS3ObjectStorageEntry, which allows accessing the AWS-specific GetObjectResponse object in case you need more details about the object. <.> We transform the AwsS3ObjectStorageEntry into an HttpResponse<StreamedFile>. <.> The response contains not only the file, but also an ETag header.

Note
The HTTP client could have used the ETag from the upload operation and sent it in an If-None-Match header in the download request to implement caching, which then would have to be implemented in the download endpoint. But this is beyond the scope of this guide.

Delete endpoint

For the delete endpoint, all we have to do is invoke the delete method with the expected key:

java/src/main/java/example/micronaut/ProfilePicturesController.java
@Override
public void delete(String userId) {
    String key = buildKey(userId);
    objectStorage.delete(key);
}

Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.

Note
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

GraalVM Installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 25
sdk install java 25.0.2-graalce

Native Executable Generation

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle

Testing

We can test our application from the command line.

Uploading a profile picture

Note

If you want to upload a file larger than 1MB, you need to configure:

src/main/resources/application.properties
# 20 * 1024 * 1024 = 20MB
micronaut.server.multipart.max-file-size=20971520

Assuming you have locally a profile picture in a profile.jpg file, you can send it to your application with:

$ curl -i -F 'fileUpload=@profile.jpg' http://localhost:8080/pictures/alvaro

HTTP/1.1 201 Created
location: http://localhost:8080/pictures/alvaro
ETag: "617cb82e296e153c29b34cccf7af0908"
date: Wed, 14 Sep 2022 12:50:30 GMT
connection: keep-alive
transfer-encoding: chunked

Note the Location and ETag headers.

We can use the aws CLI to verify that the file has actually been uploaded to an S3 bucket:

aws s3 ls s3://micronaut-guide-object-storage/

Download a profile picture

curl http://localhost:8080/pictures/alvaro -O -J

The file will be saved as alvaro.jpg since our download endpoint includes a Content-Disposition: attachment header. Open it to check that it is actually the same image as profile.jpg.

Delete a profile picture

aws s3 ls s3://micronaut-guide-object-storage/

Cleanup

Once you are done with this guide, you can remove the bucket from S3 to not leave stale resources:

aws s3api delete-bucket --bucket micronaut-guide-object-storage --region eu-west-3

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).