javaamazon-s3java-8aws-sdkaws-sdk-java-2.0

S3 Client Creation with AWS SDK for Java 2.X


I have an existing functionality where I create S3 client object from encrypted credentials and region in AWS SDK version 1.12.435. Now, I have to upgrade the entire code base to AWS SDK for Java 2 version(2.20.32). I am not seeing an equivalent class for the client credential or transfer manager. Following is my S3 client object creation function in version 1.X

public AmazonS3 getS3Client(final String s3AK, final String s3SK, final String s3Url, String region) throws Exception {         
        AWSStaticCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(EncryptDecryptUtils.decrypt(s3AK), EncryptDecryptUtils.decrypt(s3SK))); 
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withPathStyleAccessEnabled(true).withCredentials(credentialsProvider).withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(s3Url, region)).build();        
        return s3Client;
}

Let me know how I could replace this way of S3 client creation to an equivalent way in AWS SDK for java 2.X


Solution

  • The equivalent is something like below.

    The transfer manager is in a separate maven package software.amazon.awssdk.transfer.s3.S3TransferManager.

    In the 1.x SDK a lot of classes were AWS*, in 2.x it's now Aws* which is sometimes annoyingly subtle.

    public S3AsyncClient getS3Client(final String s3AK, final String s3SK, final String s3Url, String region) throws Exception {
        AwsCredentials creds = AwsBasicCredentials.create(EncryptDecryptUtils.decrypt(s3AK), EncryptDecryptUtils.decrypt(s3SK));
        AwsCredentialsProvider provider = StaticCredentialsProvider.create(creds);
    
        S3EndpointParams endpointParams = S3EndpointParams.builder()
            .endpoint(s3Url)
            .region(Region.of(region))
            // path style access is done by default if the url is not a
            // virtual host IIRC, if not you can force path style with
            // .forcePathStyle(true) // I think you only need this once here or in the client
            .build();
    
        Endpoint endpoint = S3EndpointProvider
            .defaultProvider()
            .resolveEndpoint(endpointParams.build()).join();
    
        S3AsyncClient s3Client = S3AsyncClient
            .builder()
            .credentialsProvider(awsCreds)
            .endpointOverride(endpoint.url())
            // path style access is done by default if the url is not a
            // virtual host IIRC, if not you can force path style with
            // .forcePathStyle(true) // I think you only need this once here or in the params
            .build();
        return s3Client;
    }