Skip to content

Commit

Permalink
moving creds generation to constructor + assigning staticCredentialsP…
Browse files Browse the repository at this point in the history
…rovider in a way the variable can be static
  • Loading branch information
Sachin Karve committed Jul 11, 2024
1 parent 206ff79 commit 0600a94
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/main/java/com/meta/cp4m/S3PreProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class S3PreProcessor<T extends Message> implements PreProcessor<T> {
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,
Expand All @@ -46,24 +46,28 @@ 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
public ThreadState<T> run(ThreadState<T> 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;
Expand All @@ -79,13 +83,12 @@ public ThreadState<T> run(ThreadState<T> 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 =
Expand Down

0 comments on commit 0600a94

Please sign in to comment.