Goal
We want to add persistence using an S3 Bucket to an Hello World Application already hosted on Poja that exposes the /hello?name=your-name
endpoint, for which it :
Writes a Hello World message inside a .txt file
Uploads the file to an S3 bucket
Returns a presigned uri to download the file
How-to in 2 steps
Step 1: Enable file storage for the preprod environment
Select the preprod environment, click on the Edit button on the Poja Configuration section and then:
Enable the File Storage
Click on the Save button
Once it’s done, wait for the deployment to finish.
/health/bucket
Once the File Storage option is activated,
/health/bucket
endpoint will be added to the application. It returns a presigned URI which gives you read-only access to tiny files created in the bucket for testing purpose.
Step 2: Code your endpoint
The BucketComponent class
To interact with the S3 Bucket associated to your application, Poja provides the BucketComponent class which has 4 public methods:
upload()
download()
to download a specific file by specifying its name
presign()
to get a presigned uri to access a specific file for a specified duration
getBucketName()
package com.my.company.service;
import static java.io.File.createTempFile;
import com.my.company.file.bucket.BucketComponent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class HelloWorldService {
private final BucketComponent bucketComponent;
@SneakyThrows
public String uploadHelloWorldMessage(String name) {
var fileSuffix = ".txt";
var filePrefix = "hello-world-" + name;
var bucketKey = filePrefix + fileSuffix;
var fileToUpload = createTempFile(filePrefix, fileSuffix);
writeMessageIntoFile("Hello World " + name + " !", fileToUpload);
bucketComponent.upload(fileToUpload, bucketKey);
return bucketComponent.presign(bucketKey, Duration.ofMinutes(5)).toString();
}
private void writeMessageIntoFile(String message, File file) throws IOException {
FileWriter writer = new FileWriter(file);
writer.write(message);
writer.close();
}
}
package com.my.company.endpoint.rest.controller;
import com.my.company.service.HelloWorldService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@AllArgsConstructor
public class HelloWorldController {
private final HelloWorldService service;
@GetMapping("/hello")
public String helloWorld(@RequestParam String name) {
return service.uploadHelloWorldMessage(name);
}
}
To trigger a deployment, just commit and push the code to the preprod branch of the repository. Wait. And voilà!