Upload / download / bulk delete data to S3 using Amazon S3 Client Builder with AWS SDK for Java

The use of the AmazonS3Client class provided in the old SDK is treated as Deprecated, and it is written in the reference that AmazonS3ClientBuilder can be used, but it seems that there are few Japanese documents, so I will leave it as a reminder.

Sample code

S3Access.java


package s3test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.DeleteObjectsRequest;
import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion;
import com.amazonaws.services.s3.model.DeleteObjectsResult;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

public class S3Access {

    private static final String ENDPOINT_URL = "https://s3-ap-northeast-1.amazonaws.com";
    private static final String REGION       = "ap-northeast-1";
    private static final String ACCESS_KEY   = "【access key】";
    private static final String SECRET_KEY   = "[Secret key]";

    //--------------------------------------------------
    //upload
    //--------------------------------------------------
    public void putObject(String bucketName, String objectKey, int objectSize, InputStream is) throws Exception {

        //Client generation
        AmazonS3 client = getClient(bucketName);

        ObjectMetadata metadata = new ObjectMetadata();
        //Set only the size just in case (Exception if inconsistent)
        metadata.setContentLength(objectSize);

        //upload
        client.putObject(bucketName, objectKey, is, metadata);
    }

    //--------------------------------------------------
    //download
    //--------------------------------------------------
    public S3ObjectInputStream getObject(String bucketName, String objectKey) throws Exception {

        //Client generation
    	AmazonS3 client = getClient(bucketName);

    	//download
    	S3Object s3Object = client.getObject(bucketName, objectKey);

	return s3Object.getObjectContent();
    }

    //--------------------------------------------------
    //Bulk deletion
    //--------------------------------------------------
    public List<String> deleteObjects(String bucketName, List<String> objectKeys) throws Exception {

        //Client generation
        AmazonS3 client = getClient(bucketName);

        List<KeyVersion> keys = new ArrayList<KeyVersion>();
        objectKeys.forEach(obj -> keys.add(new KeyVersion(obj)));

        //File deletion
        DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName).withKeys(keys);
        DeleteObjectsResult  result  = client.deleteObjects(request);

        //Get the key of the deleted object
        List<String>         deleted = new ArrayList<String>();
        result.getDeletedObjects().forEach(obj -> deleted.add(obj.getKey()));

        return deleted;
    }

    //--------------------------------------------------
    //Client generation
    //--------------------------------------------------
    private AmazonS3 getClient(String bucketName) throws Exception {

        //Authentication information
    	AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);

    	//Client settings
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTPS);  //protocol
        clientConfig.setConnectionTimeout(10000);   //Connection timeout(ms)	

        //Endpoint setting
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ENDPOINT_URL, REGION);

        //Client generation
        AmazonS3 client = AmazonS3ClientBuilder.standard()
                        .withCredentials(new AWSStaticCredentialsProvider(credentials))
                        .withClientConfiguration(clientConfig)
                        .withEndpointConfiguration(endpointConfiguration).build();

        if(!client.doesBucketExist(bucketName)) {
        //Exception if there is no bucket
            throw new Exception("S3 bucket[" + bucketName + "]there is not");
        }

        return client;
    }
}

Supplement

Recommended Posts

Upload / download / bulk delete data to S3 using Amazon S3 Client Builder with AWS SDK for Java
Encrypt data uploaded to S3 using AWS SDK for Java / SSE-KMS
Try Spark Submit to EMR using AWS SDK for Java
[Java] Test S3 upload / download using "S3 ninja"
Get a list of S3 files with ListObjectsV2Request (AWS SDK for Java)
[AWS SDK for Java] Set a retry policy on the S3 client
I tried to operate SQS using AWS Java SDK
Set a signed cookie (for CloudFront) with a custom policy using the AWS SDK for Java
Get S3 object size with AWS SDK for Ruby
Investigated how to call services with Watson SDK for Java
Access S3 buckets using SSE-KMS encryption in an EC2 IAM Role environment (AWS SDK for Java)
Upload files to Aspera that comes with IBM Cloud Object Storage (ICOS) using SDK (Java version)
Sample of using Salesforce's Bulk API from Java client with PK-chunking
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
[Rails] How to upload images to AWS S3 using refile and refile-s3
[Note] Download from S3, upload to S3
AWS SDK for Java 1.11.x and 2.x
Using Java with AWS Lambda-Eclipse Preparation
How to deploy to AWS using NUXTJS official S3 and CloudFront? With docker-compose
Using Java with AWS Lambda-Implementation-Check CloudWatch Arguments
Using Java with AWS Lambda-Implementation-Stop / Launch EC2
How to delete data with foreign key
Until you run a Java program with the AWS SDK local to Windows
Try local development of AWS (S3, DynamoDB) with AWS SDK for JavaScript and Docker