Skip to content

Commit

Permalink
Add S3Template#bucketExists (#915)
Browse files Browse the repository at this point in the history
Closes #901
  • Loading branch information
straurob authored Nov 1, 2023
1 parent a2ad6c0 commit 0a176d0
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 bucketExists(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 bucketExists(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.bucketExists(BUCKET_NAME);

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

@Test
void whenBucketNotExistsShouldReturnFalse() {
destroyBuckets();

final boolean existsBucket = s3Template.bucketExists(BUCKET_NAME);

assertThat(existsBucket).isFalse();
}

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

0 comments on commit 0a176d0

Please sign in to comment.