Skip to content

Commit

Permalink
feat: check if bucket exists with S3Template
Browse files Browse the repository at this point in the history
Closes #901
  • Loading branch information
straurob committed Oct 20, 2023
1 parent d6d9dce commit dbcafbb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ public interface S3Operations {
*/
void deleteBucket(String bucketName);

/**
* Checks if an S3 bucket exists.
*
* @param bucketName - the bucket name
* @return true if bucket exists; false otherwise
*/
boolean existsBucket(String bucketName);

/**
* Deletes an object from S3 bucket.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
Expand Down Expand Up @@ -74,6 +75,17 @@ public void deleteBucket(String bucketName) {
s3Client.deleteBucket(request -> request.bucket(bucketName));
}

@Override
public boolean existsBucket(String bucketName) {
Assert.notNull(bucketName, "bucketName is required");
try {
s3Client.headBucket(request -> request.bucket(bucketName));
} catch (NoSuchBucketException e) {
return false;
}
return true;
}

@Override
public void deleteObject(String bucketName, String key) {
Assert.notNull(bucketName, "bucketName is required");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,23 @@ void deletesBucket() {
assertThat(client.listBuckets()).satisfies(r -> this.bucketDoesNotExist(r, BUCKET_NAME));
}

@Test
void whenBucketExistsShouldReturnTrue() {
final boolean existsBucket = s3Template.existsBucket(BUCKET_NAME);

assertThat(existsBucket).isTrue();
assertThat(client.listBuckets()).satisfies(r -> this.bucketExists(r, BUCKET_NAME));
}

@Test
void whenBucketNotExistsShouldReturnFalse() {
destroyBuckets();

final boolean existsBucket = s3Template.existsBucket(BUCKET_NAME);

assertThat(existsBucket).isFalse();
}

@Test
void deletesObject() {
client.createBucket(r -> r.bucket(BUCKET_NAME));
Expand Down

0 comments on commit dbcafbb

Please sign in to comment.