AmazonS3Client(credentials) is deprecated

JavaAmazon Web-ServicesAmazon S3Aws SdkDeprecated

Java Problem Overview


I'm trying to read the files available on Amazon S3, as the question explains the problem. I couldn't find an alternative call for the deprecated constructor.

Here's the code:

private String AccessKeyID = "xxxxxxxxxxxxxxxxxxxx";
private String SecretAccessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static String bucketName     = "documentcontainer";
private static String keyName     = "test";
//private static String uploadFileName    = "/PATH TO FILE WHICH WANT TO UPLOAD/abc.txt";

AWSCredentials credentials = new BasicAWSCredentials(AccessKeyID, SecretAccessKey);

void downloadfile() throws IOException
{

    // Problem lies here - AmazonS3Client is deprecated
    AmazonS3 s3client = new AmazonS3Client(credentials);
        try {
        System.out.println("Downloading an object...");
        S3Object s3object = s3client.getObject(new GetObjectRequest(
                bucketName, keyName));
        System.out.println("Content-Type: "  +
                s3object.getObjectMetadata().getContentType());
        InputStream input = s3object.getObjectContent();

        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("    " + line);
        }
        System.out.println();
    } catch (AmazonServiceException ase) {
          //do something
    } catch (AmazonClientException ace) {
        // do something
    }
 }

Any help? If more explanation is needed please mention it. I have checked on the sample code provided in .zip file of SDK, and it's the same.

Java Solutions


Solution 1 - Java

You can either use AmazonS3ClientBuilder or AwsClientBuilder as alternatives.

For S3, simplest would be with AmazonS3ClientBuilder,

BasicAWSCredentials creds = new BasicAWSCredentials("access_key", "secret_key"); 
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).build();

Solution 2 - Java

Use the code listed below to create an S3 client without credentials:

AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();

An usage example would be a lambda function calling S3.

Solution 3 - Java

You need to pass the region information through the

com.amazonaws.regions.Region object.

Use AmazonS3Client(credentials, Region.getRegion(Regions.REPLACE_WITH_YOUR_REGION))

Solution 4 - Java

You can create S3 default client as follows(with aws-java-sdk-s3-1.11.232):

AmazonS3ClientBuilder.defaultClient();

Solution 5 - Java

Deprecated with only creentials in constructor, you can use something like this:

 val awsConfiguration = AWSConfiguration(context)
 val awsCreds = CognitoCachingCredentialsProvider(context, awsConfiguration)
 val s3Client = AmazonS3Client(awsCreds, Region.getRegion(Regions.EU_CENTRAL_1))

Solution 6 - Java

implementation 'com.amazonaws:aws-android-sdk-s3:2.16.12'

val key = "XXX"
val secret = "XXX"
val credentials = BasicAWSCredentials(key, secret)
val s3 = AmazonS3Client(
    credentials, com.amazonaws.regions.Region.getRegion(
        Regions.US_EAST_2
    )
)
val expires = Date(Date().time + 1000 * 60 * 60)

val keyFile = "13/thumbnail_800x600_13_photo.jpeg"
val generatePresignedUrlRequest = GeneratePresignedUrlRequest(
    "bucket_name",
    keyFile
)
generatePresignedUrlRequest.expiration = expires
val url: URL = s3.generatePresignedUrl(generatePresignedUrlRequest)

GlideApp.with(this)
    .load(url.toString())
    .apply(RequestOptions.centerCropTransform())
    .into(image)

Solution 7 - Java

Using the AWS SDK for Java 2.x, one can also build its own credentialProvider like so:

// Credential provider

package com.myproxylib.aws;

import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;

public class CustomCredentialsProvider implements AwsCredentialsProvider {

    private final String accessKeyId;
    private final String secretAccessKey;

    public CustomCredentialsProvider(String accessKeyId, String secretAccessKey) {
        this.secretAccessKey = secretAccessKey;
        this.accessKeyId = accessKeyId;
    }

    @Override
    public AwsCredentials resolveCredentials() {
        return new CustomAwsCredentialsResolver(accessKeyId, secretAccessKey);
    }

}

// Crenditals resolver


package com.myproxylib.aws;

import software.amazon.awssdk.auth.credentials.AwsCredentials;

public class CustomAwsCredentialsResolver implements AwsCredentials {

    private final String accessKeyId;
    private final String secretAccessKey;

    CustomAwsCredentialsResolver(String accessKeyId, String secretAccessKey) {
        this.secretAccessKey = secretAccessKey;
        this.accessKeyId = accessKeyId;
    }

    @Override
    public String accessKeyId() {
        return accessKeyId;
    }

    @Override
    public String secretAccessKey() {
        return secretAccessKey;
    }
}

// Usage of the provider


package com.myproxylib.aws.s3;

public class S3Storage implements IS3StorageCapable {

    private final S3Client s3Client;

    public S3Storage(String accessKeyId, String secretAccessKey, String region) {

        this.s3Client = S3Client.builder().credentialsProvider(new CustomCredentialsProvider(accessKeyId, secretAccessKey)).region(of(region)).build();
    }

NOTE:

  1. of course, the library user can get the credentials from wherever he wants, parse it into a java Properties before calling the S3 constructor.

  2. When possible, favour the other methods mentionned in other answers and doc. My use case was necessary for this.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsif AliView Question on Stackoverflow
Solution 1 - JavafranklinsijoView Answer on Stackoverflow
Solution 2 - JavaSidView Answer on Stackoverflow
Solution 3 - JavaAbhay PratapView Answer on Stackoverflow
Solution 4 - JavaSachView Answer on Stackoverflow
Solution 5 - JavaSiarheiView Answer on Stackoverflow
Solution 6 - JavaSantiago BattaglinoView Answer on Stackoverflow
Solution 7 - JavaexaucaeView Answer on Stackoverflow