ghostrider
ghostrider

Reputation: 2238

Returning list of objects inside S3 bucket using S3AsynClient and SdkPublisher

I am trying to retrive the list of contents inside the S3 bucket using aws-java sdk 2 and S3 async client. However after running the below code, I dont see any output even though the bucket has one object inside it. Am I missing something here?

ListObjectsV2Request request = ListObjectsV2Request .builder().bucket("my-bucket").build();
ListObjectsV2Publisher response = s3AsyncClient.listObjectsV2Paginator(request);
response.contents().subscribe(s3object -> System.out.println(s3object));

Upvotes: 1

Views: 1335

Answers (1)

smac2020
smac2020

Reputation: 10724

To use the S3AsyncClient client to list objects in bucket using the listObjectsV2 method, you can use this code (your Paginator call does not work for me either).

public static void listObjects(S3AsyncClient s3AsyncClient, String bucketName) {
        try {
            ListObjectsV2Request listReq = ListObjectsV2Request.builder()
                .bucket(bucketName)
                .build();

            CompletableFuture<ListObjectsV2Response> future = s3AsyncClient.listObjectsV2(listReq);
            future.whenComplete((resp, err) -> {
                try {
                    if (resp != null) {
                        List<S3Object> objects = resp.contents();
                        for (S3Object myValue : objects) {
                            System.out.print("\n The name of the key is " + myValue.key());
                        }
                    } else {
                        // Handle error.
                        err.printStackTrace();
                    }
                } finally {
                    // Only close the client when you are completely done with it.
                    s3AsyncClient.close();
                }
            });
            future.join();

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

Upvotes: 2

Related Questions