From 0600a94936de876f89fee7b7cb80c62e6fa59940 Mon Sep 17 00:00:00 2001 From: Sachin Karve Date: Thu, 11 Jul 2024 13:31:31 -0700 Subject: [PATCH] moving creds generation to constructor + assigning staticCredentialsProvider in a way the variable can be static --- src/main/java/com/meta/cp4m/S3PreProcessor.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/meta/cp4m/S3PreProcessor.java b/src/main/java/com/meta/cp4m/S3PreProcessor.java index 8e8a07f..648e1e3 100644 --- a/src/main/java/com/meta/cp4m/S3PreProcessor.java +++ b/src/main/java/com/meta/cp4m/S3PreProcessor.java @@ -33,7 +33,7 @@ public class S3PreProcessor implements PreProcessor { private final String region; private final String bucket; private final @Nullable String textMessageAddition; - private @Nullable StaticCredentialsProvider staticCredentialsProvider; + private final AwsCredentialsProvider credentials; public S3PreProcessor( String awsAccessKeyID, @@ -46,13 +46,17 @@ public S3PreProcessor( this.region = region; this.bucket = bucket; this.textMessageAddition = textMessageAddition; - this.staticCredentialsProvider = null; + @Nullable StaticCredentialsProvider staticCredentialsProvider; if (!this.awsAccessKeyID.isEmpty() && !this.awsSecretAccessKey.isEmpty()) { AwsSessionCredentials sessionCredentials = AwsSessionCredentials.create(this.awsAccessKeyID, this.awsSecretAccessKey, ""); staticCredentialsProvider = StaticCredentialsProvider.create(sessionCredentials); + } else { + staticCredentialsProvider = null; } + + this.credentials = Objects.requireNonNullElse(staticCredentialsProvider, DefaultCredentialsProvider.create()); } @Override @@ -60,10 +64,10 @@ public ThreadState run(ThreadState in) { switch (in.tail().payload()) { case Payload.Image i -> { - this.sendRequest(i.value(), in.userId().toString(), i.extension()); + this.sendRequest(i.value(), in.userId().toString(), i.extension(), this.credentials); } case Payload.Document i -> { - this.sendRequest(i.value(), in.userId().toString(), i.extension()); + this.sendRequest(i.value(), in.userId().toString(), i.extension(), this.credentials); } default -> { return in; @@ -79,13 +83,12 @@ public ThreadState run(ThreadState in) { Identifier.random())); // TODO: remove last message } - public void sendRequest(byte[] media, String senderID, String extension) { + public void sendRequest(byte[] media, String senderID, String extension, AwsCredentialsProvider credentials) { String key = senderID + '_' + Instant.now().toEpochMilli() + '.' + extension; - AwsCredentialsProvider credentialsProvider = Objects.requireNonNullElse(this.staticCredentialsProvider, DefaultCredentialsProvider.create()); try (S3Client s3Client = S3Client.builder() .region(Region.of(this.region)) - .credentialsProvider(credentialsProvider) + .credentialsProvider(credentials) .build()) { PutObjectRequest request =