From 095d60680bdd243aefd5078f5eeb897777f61bde Mon Sep 17 00:00:00 2001 From: Manoj Date: Thu, 7 Sep 2017 17:21:32 +0530 Subject: [PATCH] Use listObjects to check if bucket exists --- .../indix/gocd/utils/store/S3ArtifactStore.java | 10 ++-------- .../gocd/utils/store/S3ArtifactStoreTest.java | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/utils/src/main/java/com/indix/gocd/utils/store/S3ArtifactStore.java b/utils/src/main/java/com/indix/gocd/utils/store/S3ArtifactStore.java index 200d479..497b646 100644 --- a/utils/src/main/java/com/indix/gocd/utils/store/S3ArtifactStore.java +++ b/utils/src/main/java/com/indix/gocd/utils/store/S3ArtifactStore.java @@ -111,13 +111,8 @@ public void getPrefix(String prefix, String to) { public boolean bucketExists() { try { - List buckets = client.listBuckets(); - return Lists.exists(buckets, new Functions.Predicate() { - @Override - public Boolean execute(Bucket input) { - return input.getName().equals(bucket); - } - }); + client.listObjects(new ListObjectsRequest(bucket, null, null, null, 0)); + return true; } catch (Exception ex) { return false; } @@ -215,7 +210,6 @@ public static AmazonS3 getS3client(GoEnvironment env) { amazonS3ClientBuilder.withCredentials(new AWSStaticCredentialsProvider(basicCreds)); } - return amazonS3ClientBuilder.build(); } } diff --git a/utils/src/test/java/com/indix/gocd/utils/store/S3ArtifactStoreTest.java b/utils/src/test/java/com/indix/gocd/utils/store/S3ArtifactStoreTest.java index 3ee304e..a383549 100644 --- a/utils/src/test/java/com/indix/gocd/utils/store/S3ArtifactStoreTest.java +++ b/utils/src/test/java/com/indix/gocd/utils/store/S3ArtifactStoreTest.java @@ -1,6 +1,8 @@ package com.indix.gocd.utils.store; import com.amazonaws.services.s3.AmazonS3Client; +import com.amazonaws.services.s3.model.ListObjectsRequest; +import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.PutObjectRequest; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -54,4 +56,18 @@ public void shouldUseGlacierStorageClass() { assertThat(putRequest.getStorageClass(), is("GLACIER")); } + @Test + public void shouldSuccessfullyCheckIfBucketExists() { + doReturn(new ObjectListing()).when(mockClient).listObjects(any(ListObjectsRequest.class)); + S3ArtifactStore store = new S3ArtifactStore(mockClient, "foo-bar"); + assertThat(store.bucketExists(), is(true)); + } + + @Test + public void shouldHandleBucketDoesNotExists() { + doThrow(new RuntimeException("Bucket does not exist")).when(mockClient).listObjects(any(ListObjectsRequest.class)); + S3ArtifactStore store = new S3ArtifactStore(mockClient, "foo-bar"); + assertThat(store.bucketExists(), is(false)); + } + } \ No newline at end of file