Hướng đẫn sử dụng Amazon’s S3 với Java

Trong hướng dẫn này, tôi sẽ giải thích làm thế nào để sử dụng lưu trữ S3 của Amazon với các API Java được cung cấp bởi Amazon. Các ví dụ cho bạn thấy làm thế nào để tạo ra một bucket, liệt kê nội dung của bucket, tạo ra một folder vào một bucket, upload một file, cung cấp quyền truy cập cho các file và cuối cùng là làm thế nào để xóa tất cả những thứ đã tạo ra.

Tạo tài khoản Amazon


Mở http://aws.amazon.com/, và sau đó nhấn Sign Up và t
hực hiện theo các hướng dẫn trên màn hình.

Để cung cấp thông tin truy cập cho một người sử dụng IAM. 
Đăng nhập vào Management Console AWS và mở giao diện điều khiển IAM tại https://console.aws.amazon.com/iam/.

    1. Click vào Users để xem người sử dụng IAM của bạn.

    2. Nếu bạn không có bất kỳ người sử dụng IAM thiết lập, nhấn Create User để tạo.
    3. Click vào sử dụng IAM cho người mà bạn muốn cung cấp thông tin truy cập.
    4. Dưới Credentials Security, Click  vào Manage Access Keys.
    5. Click vào Tạo Access Key để tạo một khóa truy cập mới.
    6. Trên hộp thoại hiện ra, nhấn nút Download Credentials để tải về các tập tin ủy nhiệm cho máy tính của bạn, hoặc bấm Hiện Credentials tài Security để xem quyền truy cập của người sử dụng IAM ID access key ID và secret access key.
Chú ý: Bạn không thể có được secret access key một khi bạn đóng hộp thoại. Nếu bạn bị mất secret access key, bạn sẽ cần phải tạo ra một access key mới.
   7. Click Close để đóng hộp thoại.


Setting up project

1. Bạn cần download AWS SDK cho Java tại http://aws.amazon.com/sdk-for-java/ hoặc thêm dependency vào maven project.

        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.10.10</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-dynamodb</artifactId>
            <version>1.10.10</version>
       </dependency>

2. Lấy access key ID và secret access key đã tạo ở bước trên bạn sẽ cần để kết nối với S3
3. Thêm quyền “AWSConnector” “AmazonS3FullAccess” cho user. (Tạo group và thêm quyền sau đó thêm user vào group).


Authenticate with Amazon S3

Có 4 cách để bạn authenticate với Amazon S3: 
1. Sử dụng default credential profile file :
Tạo file credentials với nội dung sau :

  1. # Move this credentials file to (~/.aws/credentials)
  2. # after you fill in your access and secret keys in the default profile
  3. # WARNING: To avoid accidental leakage of your credentials,
  4. # DO NOT keep this file in your source directory.
  5. [default]
  6. aws_access_key_id=
  7. aws_secret_access_key=
sau đó lưu vào thư mục C:\Users\user\.aws\credentials cho windows và /home cho Linux
(Dùng lệnh mkdir để tạo thư mục .aws)

Nếu bạn chọn cách này thì get credentials bằng cách
AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials();
2. Sử dụng biến môi trường set biến môi trường trong hệ thống với tên là:
AWS_ACCESS_KEY_ID và AWS_SECRET_ACCESS_KEY

3. Sử dụng java system properties sau đó dùng SystemPropertiesCredentialsProvider để load lên trong chương trình.

4. Cách hay dùng là set credentials trong lúc chạy bằng keys
AWSCredentials credentials = new BasicAWSCredentials("YourAccessKeyID", "YourSecretAccessKey");

Create S3 Client

AmazonS3 s3client = new AmazonS3Client(credentials);

Create a bucket

String bucketName = "bucketName";
s3client.createBucket(bucketName);

List all buckets

for (Bucket bucket : s3client.listBuckets()) {
 System.out.println(" - " + bucket.getName());
}

Create folder in bucket

public static void createFolder(String bucketName, String folderName, AmazonS3 client) {
 // create meta-data for your folder and set content-length to 0
 ObjectMetadata metadata = new ObjectMetadata();
 metadata.setContentLength(0);

 // create empty content
 InputStream emptyContent = new ByteArrayInputStream(new byte[0]);

 // create a PutObjectRequest passing the folder name suffixed by /
 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
    folderName + SUFFIX, emptyContent, metadata);

 // send request to S3 to create folder
 client.putObject(putObjectRequest);
}

Complete Example

  1. public class MyAmazonS3Client extends AmazonS3Client { private static final String SUFFIX = "/"; private static MyAmazonS3Client instance = null; public MyAmazonS3Client () { super(); } public MyAmazonS3Client (AWSCredentials awsCredentials) { super(awsCredentials); } public static MyAmazonS3Client getS3Client() { if (instance == null) { instance = new MyAmazonS3Client (); } return instance; } public static MyAmazonS3Client getS3Client(AWSCredentials awsCredentials) { if (instance == null) { instance = new MyAmazonS3Client (awsCredentials); } return instance; } /** * Get S3 Client with Access Key and Secret Key * * @param awsAccessKey * @param awsSecretKey * @return AmazonS3 */ public static MyAmazonS3Client getS3Client(String awsAccessKey, String awsSecretKey) { AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); return getS3Client(credentials); } public void createFolder(String bucketName, String folderName) { // create meta-data for your folder and set content-length to 0 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0); // create empty content InputStream emptyContent = new ByteArrayInputStream(new byte[0]); // create a PutObjectRequest passing the folder name suffixed by / PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folderName + SUFFIX, emptyContent, metadata); // send request to S3 to create folder this.putObject(putObjectRequest); } public void uploadFile(String bucketName, String s3filePath, File fileUpload, CannedAccessControlList accessControlList) { // upload file to folder and set it to public this.putObject(new PutObjectRequest(bucketName, s3filePath, fileUpload) .withCannedAcl(accessControlList)); } /** * Get file from S3 at an InputStream * * @param bucketName - The name of the Amazon S3 bucket * @param s3filePath - The path to file on S3. * @return InputStream */ public InputStream getFileInputStream(String bucketName, String s3filePath) { S3Object object = this.getObject(new GetObjectRequest(bucketName, s3filePath)); return object.getObjectContent(); } /** * Get file from S3 * * @param bucketName * @param s3filePath * @param fileLocalPath path file you want to save at local * @return File * @throws IOException */ public File getFile(String bucketName, String s3filePath, String fileLocalPath) throws IOException { S3Object object = this.getObject(new GetObjectRequest(bucketName, s3filePath)); File file = new File(fileLocalPath); try ( // read this file into InputStream InputStream inputStream = object.getObjectContent(); // write the inputStream to a FileOutputStream OutputStream outputStream = new FileOutputStream(file)) { int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } return file; } /** * @param bucketName - The name of the Amazon S3 bucket containing the * object to delete. * @param s3filePath - The path to file on S3. */ public void deleteFile(String bucketName, String s3filePath) { // upload file to folder and set it to public this.deleteObject(new DeleteObjectRequest(bucketName, s3filePath)); } /** * Delete folder on S3 * * @param bucketName * @param folderName */ public void deleteFolder(String bucketName, String folderName) { List<S3ObjectSummary> fileList = this.listObjects(bucketName, folderName).getObjectSummaries(); for (S3ObjectSummary file : fileList) { this.deleteObject(bucketName, file.getKey()); } this.deleteObject(bucketName, folderName); } }

SHARE THIS

0 comments: