diff --git a/.doc_gen/metadata/s3_metadata.yaml b/.doc_gen/metadata/s3_metadata.yaml index c05b484ae5d..01aace9e324 100644 --- a/.doc_gen/metadata/s3_metadata.yaml +++ b/.doc_gen/metadata/s3_metadata.yaml @@ -113,9 +113,12 @@ s3_CreateBucket: github: javav2/example_code/s3 sdkguide: excerpts: - - description: + - description: Create a bucket. snippet_tags: - s3.java2.create_bucket_waiters.main + - description: Create a bucket with object lock enabled. + snippet_tags: + - S3LockWorkflow.javav2.CreateBucketWithLockOptions.main JavaScript: versions: - sdk_version: 3 @@ -963,6 +966,15 @@ s3_GetObjectLegalHoldConfiguration: synopsis: get the legal hold configuration of an S3 bucket. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.GetObjectLegalHold.main .NET: versions: - sdk_version: 3 @@ -980,6 +992,15 @@ s3_GetObjectLockConfiguration: synopsis: get the object lock configuration of an S3 bucket. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.GetBucketObjectLockConfiguration.main .NET: versions: - sdk_version: 3 @@ -997,6 +1018,15 @@ s3_GetObjectRetention: synopsis: get the retention configuration of an S3 object. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.GetObjectRetention.main .NET: versions: - sdk_version: 3 @@ -2148,6 +2178,15 @@ s3_PutObjectLegalHold: synopsis: set the legal hold configuration of an S3 object. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.ModifyObjectLegalHold.main .NET: versions: - sdk_version: 3 @@ -2165,6 +2204,15 @@ s3_PutObjectLockConfiguration: synopsis: set the object lock configuration of an existing S3 bucket. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.EnableObjectLockOnBucket.main .NET: versions: - sdk_version: 3 @@ -2182,6 +2230,15 @@ s3_PutObjectRetention: synopsis: set the retention period of an S3 object. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.ModifyObjectRetentionPeriod.main .NET: versions: - sdk_version: 3 @@ -2199,6 +2256,15 @@ s3_PutDefaultObjectLockConfiguration: synopsis: set the default retention period of an S3 bucket. category: languages: + Java: + versions: + - sdk_version: 2 + github: javav2/example_code/s3 + sdkguide: + excerpts: + - description: + snippet_tags: + - S3LockWorkflow.javav2.ModifyBucketDefaultRetention.main .NET: versions: - sdk_version: 3 @@ -3059,6 +3125,18 @@ s3_Scenario_ObjectLock: synopsis: work with S3 object lock features. category: Scenarios languages: + Java: + versions: + - sdk_version: 2 + github: java/usecases/s3_object_lock_scenario + sdkguide: + excerpts: + - description: Run an interactive scenario demonstrating &S3; object lock features. + snippet_tags: + - S3LockWorkflow.javav2.ObjectLockWorkflow.main + - description: A wrapper class for S3 functions. + snippet_tags: + - S3LockWorkflow.javav2.S3ActionsWrapper.main .NET: versions: - sdk_version: 3 diff --git a/javav2/example_code/s3/README.md b/javav2/example_code/s3/README.md index cadeef9236c..339fb7d151b 100644 --- a/javav2/example_code/s3/README.md +++ b/javav2/example_code/s3/README.md @@ -31,54 +31,62 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav ### Get started -- [Hello Amazon S3](src/main/java/com/example/s3/HelloS3.java#L6) (`ListBuckets`) +- [Hello Amazon S3](s3/src/main/java/com/example/s3/HelloS3.java#L6) (`ListBuckets`) ### Single actions Code excerpts that show you how to call individual service functions. -- [Add CORS rules to a bucket](src/main/java/com/example/s3/S3Cors.java#L6) (`PutBucketCors`) -- [Add a lifecycle configuration to a bucket](src/main/java/com/example/s3/LifecycleConfiguration.java#L6) (`PutBucketLifecycleConfiguration`) -- [Add a policy to a bucket](src/main/java/com/example/s3/SetBucketPolicy.java#L6) (`PutBucketPolicy`) -- [Copy an object from one bucket to another](src/main/java/com/example/s3/CopyObject.java#L6) (`CopyObject`) -- [Create a bucket](src/main/java/com/example/s3/CreateBucket.java#L6) (`CreateBucket`) -- [Delete a policy from a bucket](src/main/java/com/example/s3/DeleteBucketPolicy.java#L6) (`DeleteBucketPolicy`) -- [Delete an empty bucket](src/main/java/com/example/s3/S3BucketOps.java#L79) (`DeleteBucket`) -- [Delete multiple objects](src/main/java/com/example/s3/DeleteMultiObjects.java#L6) (`DeleteObjects`) -- [Delete the website configuration from a bucket](src/main/java/com/example/s3/DeleteWebsiteConfiguration.java#L6) (`DeleteBucketWebsite`) -- [Determine the existence and content type of an object](src/main/java/com/example/s3/GetObjectContentType.java#L6) (`HeadObject`) -- [Download objects to a local directory](src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java#L6) (`DownloadDirectory`) -- [Enable notifications](src/main/java/com/example/s3/SetBucketEventBridgeNotification.java#L6) (`PutBucketNotificationConfiguration`) -- [Get an object from a bucket](src/main/java/com/example/s3/GetObjectData.java#L6) (`GetObject`) -- [Get the ACL of a bucket](src/main/java/com/example/s3/GetAcl.java#L6) (`GetBucketAcl`) -- [Get the policy for a bucket](src/main/java/com/example/s3/GetBucketPolicy.java#L6) (`GetBucketPolicy`) -- [List buckets](src/main/java/com/example/s3/ListBuckets.java#L6) (`ListBuckets`) -- [List in-progress multipart uploads](src/main/java/com/example/s3/ListMultipartUploads.java#L6) (`ListMultipartUploads`) -- [List objects in a bucket](src/main/java/com/example/s3/ListObjects.java#L6) (`ListObjectsV2`) -- [Restore an archived copy of an object](src/main/java/com/example/s3/RestoreObject.java#L6) (`RestoreObject`) -- [Set a new ACL for a bucket](src/main/java/com/example/s3/SetAcl.java#L6) (`PutBucketAcl`) -- [Set the website configuration for a bucket](src/main/java/com/example/s3/SetWebsiteConfiguration.java#L6) (`PutBucketWebsite`) -- [Upload an object to a bucket](src/main/java/com/example/s3/PutObject.java#L6) (`PutObject`) -- [Upload directory to a bucket](src/main/java/com/example/s3/transfermanager/UploadADirectory.java#L6) (`UploadDirectory`) -- [Use SQL with Amazon S3 Select](src/main/java/com/example/s3/async/SelectObjectContentExample.java#L5) (`SelectObjectContent`) +- [Add CORS rules to a bucket](s3/src/main/java/com/example/s3/S3Cors.java#L6) (`PutBucketCors`) +- [Add a lifecycle configuration to a bucket](s3/src/main/java/com/example/s3/LifecycleConfiguration.java#L6) (`PutBucketLifecycleConfiguration`) +- [Add a policy to a bucket](s3/src/main/java/com/example/s3/SetBucketPolicy.java#L6) (`PutBucketPolicy`) +- [Copy an object from one bucket to another](s3/src/main/java/com/example/s3/CopyObject.java#L6) (`CopyObject`) +- [Create a bucket](s3/src/main/java/com/example/s3/CreateBucket.java#L6) (`CreateBucket`) +- [Delete a policy from a bucket](s3/src/main/java/com/example/s3/DeleteBucketPolicy.java#L6) (`DeleteBucketPolicy`) +- [Delete an empty bucket](s3/src/main/java/com/example/s3/S3BucketOps.java#L79) (`DeleteBucket`) +- [Delete multiple objects](s3/src/main/java/com/example/s3/DeleteMultiObjects.java#L6) (`DeleteObjects`) +- [Delete the website configuration from a bucket](s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java#L6) (`DeleteBucketWebsite`) +- [Determine the existence and content type of an object](s3/src/main/java/com/example/s3/GetObjectContentType.java#L6) (`HeadObject`) +- [Download objects to a local directory](s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java#L6) (`DownloadDirectory`) +- [Enable notifications](s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java#L6) (`PutBucketNotificationConfiguration`) +- [Get an object from a bucket](s3/src/main/java/com/example/s3/GetObjectData.java#L6) (`GetObject`) +- [Get the ACL of a bucket](s3/src/main/java/com/example/s3/GetAcl.java#L6) (`GetBucketAcl`) +- [Get the legal hold configuration of an object](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L94) (`GetObjectLegalHold`) +- [Get the object lock configuration of a bucket](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L345) (`GetObjectLockConfiguration`) +- [Get the policy for a bucket](s3/src/main/java/com/example/s3/GetBucketPolicy.java#L6) (`GetBucketPolicy`) +- [Get the retention configuration of an object](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L309) (`GetObjectRetention`) +- [List buckets](s3/src/main/java/com/example/s3/ListBuckets.java#L6) (`ListBuckets`) +- [List in-progress multipart uploads](s3/src/main/java/com/example/s3/ListMultipartUploads.java#L6) (`ListMultipartUploads`) +- [List objects in a bucket](s3/src/main/java/com/example/s3/ListObjects.java#L6) (`ListObjectsV2`) +- [Restore an archived copy of an object](s3/src/main/java/com/example/s3/RestoreObject.java#L6) (`RestoreObject`) +- [Set a new ACL for a bucket](s3/src/main/java/com/example/s3/SetAcl.java#L6) (`PutBucketAcl`) +- [Set the default retention period of a bucket](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L168) (`PutObjectLockConfiguration`) +- [Set the legal hold configuration of an object](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L255) (`PutObjectLegalHold`) +- [Set the object lock configuration of an bucket](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L206) (`PutObjectLockConfiguration`) +- [Set the retention period of an object](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java#L61) (`PutObjectRetention`) +- [Set the website configuration for a bucket](s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java#L6) (`PutBucketWebsite`) +- [Upload an object to a bucket](s3/src/main/java/com/example/s3/PutObject.java#L6) (`PutObject`) +- [Upload directory to a bucket](s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java#L6) (`UploadDirectory`) +- [Use SQL with Amazon S3 Select](s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java#L5) (`SelectObjectContent`) ### Scenarios Code examples that show you how to accomplish a specific task by calling multiple functions within the same service. -- [Get started with buckets and objects](src/main/java/com/example/s3/S3Scenario.java) -- [Parse URIs](src/main/java/com/example/s3/ParseUri.java) -- [Perform a multipart upload](src/main/java/com/example/s3/PerformMultiPartUpload.java) -- [Upload or download large files](src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java) -- [Upload stream of unknown size](src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java) -- [Use checksums](src/main/java/com/example/s3/BasicOpsWithChecksums.java) +- [Get started with buckets and objects](s3/src/main/java/com/example/s3/S3Scenario.java) +- [Lock Amazon S3 objects](scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3ObjectLockWorkflow.java) +- [Parse URIs](s3/src/main/java/com/example/s3/ParseUri.java) +- [Perform a multipart upload](s3/src/main/java/com/example/s3/PerformMultiPartUpload.java) +- [Upload or download large files](s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java) +- [Upload stream of unknown size](s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java) +- [Use checksums](s3/src/main/java/com/example/s3/BasicOpsWithChecksums.java) -- [Create a presigned URL for download](src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java) -- [Create a presigned URL for upload](src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java) +- [Create a presigned URL for download](s3/src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java) +- [Create a presigned URL for upload](s3/src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java) ## Run the examples @@ -112,6 +120,18 @@ This example shows you how to do the following: +#### Lock Amazon S3 objects + +This example shows you how to work with S3 object lock features. + + + + + + + + + #### Parse URIs This example shows you how to parse Amazon S3 URIs to extract important components like the bucket name and object key. diff --git a/javav2/example_code/s3/pom.xml b/javav2/example_code/s3/s3/pom.xml similarity index 100% rename from javav2/example_code/s3/pom.xml rename to javav2/example_code/s3/s3/pom.xml diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/AbortMultipartUpload.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/AbortMultipartUpload.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/AbortMultipartUpload.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/AbortMultipartUpload.java index 101d9a8bca1..9f33ea11930 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/AbortMultipartUpload.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/AbortMultipartUpload.java @@ -1,82 +1,82 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.abort_upload.main] -// snippet-start:[s3.java2.abort_upload.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest; -import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse; -import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.MultipartUpload; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.util.List; -// snippet-end:[s3.java2.abort_upload.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class AbortMultipartUpload { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - the Amazon Simple Storage Service (Amazon S3) bucket. - accountId - the id of the account that owns the Amazon S3 bucket. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String accountId = args[1]; - Region region = Region.US_WEST_2; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - abortUploads(s3, bucketName, accountId); - s3.close(); - } - - public static void abortUploads(S3Client s3, String bucketName, String accountId) { - try { - ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder() - .bucket(bucketName) - .build(); - - ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest); - List uploads = response.uploads(); - - AbortMultipartUploadRequest abortMultipartUploadRequest; - for (MultipartUpload upload : uploads) { - abortMultipartUploadRequest = AbortMultipartUploadRequest.builder() - .bucket(bucketName) - .key(upload.key()) - .expectedBucketOwner(accountId) - .uploadId(upload.uploadId()) - .build(); - - s3.abortMultipartUpload(abortMultipartUploadRequest); - } - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.abort_upload.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.abort_upload.main] +// snippet-start:[s3.java2.abort_upload.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest; +import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse; +import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.MultipartUpload; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.util.List; +// snippet-end:[s3.java2.abort_upload.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class AbortMultipartUpload { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - the Amazon Simple Storage Service (Amazon S3) bucket. + accountId - the id of the account that owns the Amazon S3 bucket. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String accountId = args[1]; + Region region = Region.US_WEST_2; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + abortUploads(s3, bucketName, accountId); + s3.close(); + } + + public static void abortUploads(S3Client s3, String bucketName, String accountId) { + try { + ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder() + .bucket(bucketName) + .build(); + + ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest); + List uploads = response.uploads(); + + AbortMultipartUploadRequest abortMultipartUploadRequest; + for (MultipartUpload upload : uploads) { + abortMultipartUploadRequest = AbortMultipartUploadRequest.builder() + .bucket(bucketName) + .key(upload.key()) + .expectedBucketOwner(accountId) + .uploadId(upload.uploadId()) + .build(); + + s3.abortMultipartUpload(abortMultipartUploadRequest); + } + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.abort_upload.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/BasicOpsWithChecksums.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/BasicOpsWithChecksums.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/BasicOpsWithChecksums.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/BasicOpsWithChecksums.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java similarity index 98% rename from javav2/example_code/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java index 7d31aa81b21..bab1a259c71 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CheckObjectIntegrity.java @@ -1,272 +1,272 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_object_check_integrity.main] -// snippet-start:[s3.java2.s3_object_check_integrity.import] -import software.amazon.awssdk.core.ResponseInputStream; -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; -import software.amazon.awssdk.services.s3.model.ChecksumMode; -import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; -import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; -import software.amazon.awssdk.services.s3.model.CompletedPart; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; -import software.amazon.awssdk.services.s3.model.GetObjectAttributesRequest; -import software.amazon.awssdk.services.s3.model.GetObjectAttributesResponse; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import software.amazon.awssdk.services.s3.model.ObjectAttributes; -import software.amazon.awssdk.services.s3.model.UploadPartRequest; -import software.amazon.awssdk.services.s3.model.UploadPartResponse; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; -// snippet-end:[s3.java2.s3_object_check_integrity.import] - -/** - * To run this AWS code example, ensure that you have setup your development - * environment, including your AWS credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CheckObjectIntegrity { - private final static int CHUNK_SIZE = 5 * 1024 * 1024; - - public static void main(String[] args) { - final String USAGE = """ - Usage: - \s - - Where: - bucketName - the Amazon S3 bucket to upload an object into. - objectKey - the object to upload (for example, book.pdf). - objectPath - the path where the file is located (for example, C:/AWS/book2.pdf).\s - """; - - if (args.length != 3) { - System.out.println(USAGE); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - String objectPath = args[2]; - System.out.println("Putting object " + objectKey + " into bucket " + bucketName - + " with checksum in algorithm sha256."); - System.out.println(" in bucket: " + bucketName); - - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - putS3MultipartObjectBracketedByChecksum(s3, bucketName, objectKey, objectPath); - downloadS3MultipartObjectBracketedByChecksum(s3, bucketName, objectKey); - validateExistingFileAgainstS3Checksum(s3, bucketName, objectKey, objectPath); - } - - public static void putS3MultipartObjectBracketedByChecksum(S3Client s3, String bucketName, String objectKey, - String objectPath) { - System.out.println("Starting uploading file with additional checksum."); - File file = new File(objectPath); - try (InputStream in = new FileInputStream(file)) { - CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest - .builder() - .bucket(bucketName) - .key(objectKey) - .checksumAlgorithm(ChecksumAlgorithm.SHA256) - .build(); - - CreateMultipartUploadResponse createdUpload = s3 - .createMultipartUpload(createMultipartUploadRequest); - List completedParts = new ArrayList<>(); - int partNumber = 1; - byte[] buffer = new byte[CHUNK_SIZE]; - int read = in.read(buffer); - - while (read != -1) { - UploadPartRequest uploadPartRequest = UploadPartRequest.builder() - .partNumber(partNumber) - .uploadId(createdUpload.uploadId()) - .bucket(bucketName) - .key(objectKey) - .checksumAlgorithm(ChecksumAlgorithm.SHA256) - .build(); - - UploadPartResponse uploadedPart = s3.uploadPart(uploadPartRequest, - RequestBody.fromByteBuffer(ByteBuffer.wrap(buffer, 0, read))); - CompletedPart part = CompletedPart.builder() - .partNumber(partNumber) - .checksumSHA256(uploadedPart.checksumSHA256()) - .eTag(uploadedPart.eTag()).build(); - completedParts.add(part); - read = in.read(buffer); - partNumber++; - } - - CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() - .parts(completedParts).build(); - CompleteMultipartUploadResponse completedUploadResponse = s3.completeMultipartUpload( - CompleteMultipartUploadRequest.builder() - .bucket(bucketName) - .key(objectKey) - .uploadId(createdUpload.uploadId()) - .multipartUpload(completedMultipartUpload).build()); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void downloadS3MultipartObjectBracketedByChecksum(S3Client s3, String bucketName, - String objectKey) { - System.out.println("Starting downloading file and doing validation"); - File file = new File("DOWNLOADED_" + objectKey); - try (OutputStream out = new FileOutputStream(file)) { - GetObjectAttributesResponse objectAttributes = s3.getObjectAttributes(GetObjectAttributesRequest - .builder().bucket(bucketName).key(objectKey) - .objectAttributes(ObjectAttributes.OBJECT_PARTS, ObjectAttributes.CHECKSUM) - .build()); - // Initialize the digester to calculate checksum of checksums. - MessageDigest sha256ChecksumOfChecksums = MessageDigest.getInstance("SHA-256"); - - // If you retrieve the object in parts, and set the ChecksumMode to enabled, the - // SDK will automatically validate the part checksum - for (int partNumber = 1; partNumber <= objectAttributes.objectParts() - .totalPartsCount(); partNumber++) { - MessageDigest sha256PartChecksum = MessageDigest.getInstance("SHA-256"); - ResponseInputStream response = s3 - .getObject(GetObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .partNumber(partNumber) - .checksumMode(ChecksumMode.ENABLED).build()); - GetObjectResponse getObjectResponse = response.response(); - byte[] buffer = new byte[CHUNK_SIZE]; - int read = response.read(buffer); - while (read != -1) { - out.write(buffer, 0, read); - sha256PartChecksum.update(buffer, 0, read); - read = response.read(buffer); - } - byte[] sha256PartBytes = sha256PartChecksum.digest(); - sha256ChecksumOfChecksums.update(sha256PartBytes); - - String base64PartChecksum = Base64.getEncoder().encodeToString(sha256PartBytes); - String base64PartChecksumFromObjectAttributes = objectAttributes.objectParts().parts() - .get(partNumber - 1).checksumSHA256(); - if (!base64PartChecksum.equals(getObjectResponse.checksumSHA256()) - || !base64PartChecksum.equals(base64PartChecksumFromObjectAttributes)) { - throw new IOException("Part checksum didn't match for the part"); - } - System.out.println(partNumber + " " + base64PartChecksum); - } - - // Before finalizing, do the final checksum validation. - String base64ChecksumOfChecksums = Base64.getEncoder() - .encodeToString(sha256ChecksumOfChecksums.digest()); - String base64ChecksumOfChecksumFromAttributes = objectAttributes.checksum().checksumSHA256(); - if (base64ChecksumOfChecksumFromAttributes != null - && !base64ChecksumOfChecksums.equals(base64ChecksumOfChecksumFromAttributes)) { - throw new IOException( - "Failed checksum validation for full object checksum of checksums"); - } - System.out.println("Checksum of checksums: " + base64ChecksumOfChecksumFromAttributes); - out.flush(); - } catch (IOException | NoSuchAlgorithmException e) { - // Cleanup bad file - file.delete(); - e.printStackTrace(); - } - } - - public static void validateExistingFileAgainstS3Checksum(S3Client s3, String bucketName, String objectKey, - String objectPath) { - System.out.println("Starting validating the locally persisted file."); - File file = new File(objectPath); - GetObjectAttributesResponse objectAttributes = s3.getObjectAttributes(GetObjectAttributesRequest - .builder().bucket(bucketName).key(objectKey) - .objectAttributes(ObjectAttributes.OBJECT_PARTS, ObjectAttributes.CHECKSUM).build()); - try (InputStream in = new FileInputStream(file)) { - MessageDigest sha256ChecksumOfChecksums = MessageDigest.getInstance("SHA-256"); - MessageDigest sha256Part = MessageDigest.getInstance("SHA-256"); - byte[] buffer = new byte[CHUNK_SIZE]; - int currentPart = 0; - int partBreak = Math.toIntExact(objectAttributes.objectParts().parts().get(currentPart).size()); - int totalRead = 0; - int read = in.read(buffer); - while (read != -1) { - totalRead += read; - if (totalRead >= partBreak) { - int difference = totalRead - partBreak; - byte[] partChecksum; - if (totalRead != partBreak) { - sha256Part.update(buffer, 0, read - difference); - partChecksum = sha256Part.digest(); - sha256ChecksumOfChecksums.update(partChecksum); - sha256Part.reset(); - sha256Part.update(buffer, read - difference, difference); - } else { - sha256Part.update(buffer, 0, read); - partChecksum = sha256Part.digest(); - sha256ChecksumOfChecksums.update(partChecksum); - sha256Part.reset(); - } - String base64PartChecksum = Base64.getEncoder().encodeToString(partChecksum); - if (!base64PartChecksum.equals(objectAttributes.objectParts().parts() - .get(currentPart).checksumSHA256())) { - throw new IOException( - "Part checksum didn't match what persisted in S3."); - } - currentPart++; - System.out.println(currentPart + " " + base64PartChecksum); - if (currentPart < objectAttributes.objectParts().totalPartsCount()) { - partBreak += objectAttributes.objectParts().parts().get(currentPart - 1) - .size(); - } - } else { - sha256Part.update(buffer, 0, read); - } - read = in.read(buffer); - } - if (currentPart != objectAttributes.objectParts().totalPartsCount()) { - currentPart++; - byte[] partChecksum = sha256Part.digest(); - sha256ChecksumOfChecksums.update(partChecksum); - String base64PartChecksum = Base64.getEncoder().encodeToString(partChecksum); - System.out.println(currentPart + " " + base64PartChecksum); - } - - String base64CalculatedChecksumOfChecksums = Base64.getEncoder() - .encodeToString(sha256ChecksumOfChecksums.digest()); - System.out.println("Calculated checksum of checksums: " + base64CalculatedChecksumOfChecksums); - System.out.println("S3 persisted checksum of checksums: " - + objectAttributes.checksum().checksumSHA256()); - if (!base64CalculatedChecksumOfChecksums.equals(objectAttributes.checksum().checksumSHA256())) { - throw new IOException("Full object checksum of checksums don't match S3"); - } - - } catch (IOException | NoSuchAlgorithmException e) { - e.printStackTrace(); - } - } -} -// snippet-end:[s3.java2.s3_object_check_integrity.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_object_check_integrity.main] +// snippet-start:[s3.java2.s3_object_check_integrity.import] +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; +import software.amazon.awssdk.services.s3.model.ChecksumMode; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; +import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; +import software.amazon.awssdk.services.s3.model.CompletedPart; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; +import software.amazon.awssdk.services.s3.model.GetObjectAttributesRequest; +import software.amazon.awssdk.services.s3.model.GetObjectAttributesResponse; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.ObjectAttributes; +import software.amazon.awssdk.services.s3.model.UploadPartRequest; +import software.amazon.awssdk.services.s3.model.UploadPartResponse; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +// snippet-end:[s3.java2.s3_object_check_integrity.import] + +/** + * To run this AWS code example, ensure that you have setup your development + * environment, including your AWS credentials. + * + * For information, see this documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CheckObjectIntegrity { + private final static int CHUNK_SIZE = 5 * 1024 * 1024; + + public static void main(String[] args) { + final String USAGE = """ + Usage: + \s + + Where: + bucketName - the Amazon S3 bucket to upload an object into. + objectKey - the object to upload (for example, book.pdf). + objectPath - the path where the file is located (for example, C:/AWS/book2.pdf).\s + """; + + if (args.length != 3) { + System.out.println(USAGE); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + String objectPath = args[2]; + System.out.println("Putting object " + objectKey + " into bucket " + bucketName + + " with checksum in algorithm sha256."); + System.out.println(" in bucket: " + bucketName); + + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + putS3MultipartObjectBracketedByChecksum(s3, bucketName, objectKey, objectPath); + downloadS3MultipartObjectBracketedByChecksum(s3, bucketName, objectKey); + validateExistingFileAgainstS3Checksum(s3, bucketName, objectKey, objectPath); + } + + public static void putS3MultipartObjectBracketedByChecksum(S3Client s3, String bucketName, String objectKey, + String objectPath) { + System.out.println("Starting uploading file with additional checksum."); + File file = new File(objectPath); + try (InputStream in = new FileInputStream(file)) { + CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest + .builder() + .bucket(bucketName) + .key(objectKey) + .checksumAlgorithm(ChecksumAlgorithm.SHA256) + .build(); + + CreateMultipartUploadResponse createdUpload = s3 + .createMultipartUpload(createMultipartUploadRequest); + List completedParts = new ArrayList<>(); + int partNumber = 1; + byte[] buffer = new byte[CHUNK_SIZE]; + int read = in.read(buffer); + + while (read != -1) { + UploadPartRequest uploadPartRequest = UploadPartRequest.builder() + .partNumber(partNumber) + .uploadId(createdUpload.uploadId()) + .bucket(bucketName) + .key(objectKey) + .checksumAlgorithm(ChecksumAlgorithm.SHA256) + .build(); + + UploadPartResponse uploadedPart = s3.uploadPart(uploadPartRequest, + RequestBody.fromByteBuffer(ByteBuffer.wrap(buffer, 0, read))); + CompletedPart part = CompletedPart.builder() + .partNumber(partNumber) + .checksumSHA256(uploadedPart.checksumSHA256()) + .eTag(uploadedPart.eTag()).build(); + completedParts.add(part); + read = in.read(buffer); + partNumber++; + } + + CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() + .parts(completedParts).build(); + CompleteMultipartUploadResponse completedUploadResponse = s3.completeMultipartUpload( + CompleteMultipartUploadRequest.builder() + .bucket(bucketName) + .key(objectKey) + .uploadId(createdUpload.uploadId()) + .multipartUpload(completedMultipartUpload).build()); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void downloadS3MultipartObjectBracketedByChecksum(S3Client s3, String bucketName, + String objectKey) { + System.out.println("Starting downloading file and doing validation"); + File file = new File("DOWNLOADED_" + objectKey); + try (OutputStream out = new FileOutputStream(file)) { + GetObjectAttributesResponse objectAttributes = s3.getObjectAttributes(GetObjectAttributesRequest + .builder().bucket(bucketName).key(objectKey) + .objectAttributes(ObjectAttributes.OBJECT_PARTS, ObjectAttributes.CHECKSUM) + .build()); + // Initialize the digester to calculate checksum of checksums. + MessageDigest sha256ChecksumOfChecksums = MessageDigest.getInstance("SHA-256"); + + // If you retrieve the object in parts, and set the ChecksumMode to enabled, the + // SDK will automatically validate the part checksum + for (int partNumber = 1; partNumber <= objectAttributes.objectParts() + .totalPartsCount(); partNumber++) { + MessageDigest sha256PartChecksum = MessageDigest.getInstance("SHA-256"); + ResponseInputStream response = s3 + .getObject(GetObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .partNumber(partNumber) + .checksumMode(ChecksumMode.ENABLED).build()); + GetObjectResponse getObjectResponse = response.response(); + byte[] buffer = new byte[CHUNK_SIZE]; + int read = response.read(buffer); + while (read != -1) { + out.write(buffer, 0, read); + sha256PartChecksum.update(buffer, 0, read); + read = response.read(buffer); + } + byte[] sha256PartBytes = sha256PartChecksum.digest(); + sha256ChecksumOfChecksums.update(sha256PartBytes); + + String base64PartChecksum = Base64.getEncoder().encodeToString(sha256PartBytes); + String base64PartChecksumFromObjectAttributes = objectAttributes.objectParts().parts() + .get(partNumber - 1).checksumSHA256(); + if (!base64PartChecksum.equals(getObjectResponse.checksumSHA256()) + || !base64PartChecksum.equals(base64PartChecksumFromObjectAttributes)) { + throw new IOException("Part checksum didn't match for the part"); + } + System.out.println(partNumber + " " + base64PartChecksum); + } + + // Before finalizing, do the final checksum validation. + String base64ChecksumOfChecksums = Base64.getEncoder() + .encodeToString(sha256ChecksumOfChecksums.digest()); + String base64ChecksumOfChecksumFromAttributes = objectAttributes.checksum().checksumSHA256(); + if (base64ChecksumOfChecksumFromAttributes != null + && !base64ChecksumOfChecksums.equals(base64ChecksumOfChecksumFromAttributes)) { + throw new IOException( + "Failed checksum validation for full object checksum of checksums"); + } + System.out.println("Checksum of checksums: " + base64ChecksumOfChecksumFromAttributes); + out.flush(); + } catch (IOException | NoSuchAlgorithmException e) { + // Cleanup bad file + file.delete(); + e.printStackTrace(); + } + } + + public static void validateExistingFileAgainstS3Checksum(S3Client s3, String bucketName, String objectKey, + String objectPath) { + System.out.println("Starting validating the locally persisted file."); + File file = new File(objectPath); + GetObjectAttributesResponse objectAttributes = s3.getObjectAttributes(GetObjectAttributesRequest + .builder().bucket(bucketName).key(objectKey) + .objectAttributes(ObjectAttributes.OBJECT_PARTS, ObjectAttributes.CHECKSUM).build()); + try (InputStream in = new FileInputStream(file)) { + MessageDigest sha256ChecksumOfChecksums = MessageDigest.getInstance("SHA-256"); + MessageDigest sha256Part = MessageDigest.getInstance("SHA-256"); + byte[] buffer = new byte[CHUNK_SIZE]; + int currentPart = 0; + int partBreak = Math.toIntExact(objectAttributes.objectParts().parts().get(currentPart).size()); + int totalRead = 0; + int read = in.read(buffer); + while (read != -1) { + totalRead += read; + if (totalRead >= partBreak) { + int difference = totalRead - partBreak; + byte[] partChecksum; + if (totalRead != partBreak) { + sha256Part.update(buffer, 0, read - difference); + partChecksum = sha256Part.digest(); + sha256ChecksumOfChecksums.update(partChecksum); + sha256Part.reset(); + sha256Part.update(buffer, read - difference, difference); + } else { + sha256Part.update(buffer, 0, read); + partChecksum = sha256Part.digest(); + sha256ChecksumOfChecksums.update(partChecksum); + sha256Part.reset(); + } + String base64PartChecksum = Base64.getEncoder().encodeToString(partChecksum); + if (!base64PartChecksum.equals(objectAttributes.objectParts().parts() + .get(currentPart).checksumSHA256())) { + throw new IOException( + "Part checksum didn't match what persisted in S3."); + } + currentPart++; + System.out.println(currentPart + " " + base64PartChecksum); + if (currentPart < objectAttributes.objectParts().totalPartsCount()) { + partBreak += objectAttributes.objectParts().parts().get(currentPart - 1) + .size(); + } + } else { + sha256Part.update(buffer, 0, read); + } + read = in.read(buffer); + } + if (currentPart != objectAttributes.objectParts().totalPartsCount()) { + currentPart++; + byte[] partChecksum = sha256Part.digest(); + sha256ChecksumOfChecksums.update(partChecksum); + String base64PartChecksum = Base64.getEncoder().encodeToString(partChecksum); + System.out.println(currentPart + " " + base64PartChecksum); + } + + String base64CalculatedChecksumOfChecksums = Base64.getEncoder() + .encodeToString(sha256ChecksumOfChecksums.digest()); + System.out.println("Calculated checksum of checksums: " + base64CalculatedChecksumOfChecksums); + System.out.println("S3 persisted checksum of checksums: " + + objectAttributes.checksum().checksumSHA256()); + if (!base64CalculatedChecksumOfChecksums.equals(objectAttributes.checksum().checksumSHA256())) { + throw new IOException("Full object checksum of checksums don't match S3"); + } + + } catch (IOException | NoSuchAlgorithmException e) { + e.printStackTrace(); + } + } +} +// snippet-end:[s3.java2.s3_object_check_integrity.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CopyObject.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObject.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/CopyObject.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObject.java index 4e50aa992c2..03dc519b032 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CopyObject.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObject.java @@ -1,74 +1,74 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.copy_object.main] -// snippet-start:[s3.java2.copy_object.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.CopyObjectRequest; -import software.amazon.awssdk.services.s3.model.CopyObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -// snippet-end:[s3.java2.copy_object.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CopyObject { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - objectKey - The name of the object (for example, book.pdf). - fromBucket - The S3 bucket name that contains the object (for example, bucket1). - toBucket - The S3 bucket to copy the object to (for example, bucket2). - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String objectKey = args[0]; - String fromBucket = args[1]; - String toBucket = args[2]; - System.out.format("Copying object %s from bucket %s to %s\n", objectKey, fromBucket, toBucket); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - copyBucketObject(s3, fromBucket, objectKey, toBucket); - s3.close(); - } - - public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { - CopyObjectRequest copyReq = CopyObjectRequest.builder() - .sourceBucket(fromBucket) - .sourceKey(objectKey) - .destinationBucket(toBucket) - .destinationKey(objectKey) - .build(); - - try { - CopyObjectResponse copyRes = s3.copyObject(copyReq); - return copyRes.copyObjectResult().toString(); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return ""; - } -} -// snippet-end:[s3.java2.copy_object.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.copy_object.main] +// snippet-start:[s3.java2.copy_object.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CopyObjectRequest; +import software.amazon.awssdk.services.s3.model.CopyObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +// snippet-end:[s3.java2.copy_object.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CopyObject { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + objectKey - The name of the object (for example, book.pdf). + fromBucket - The S3 bucket name that contains the object (for example, bucket1). + toBucket - The S3 bucket to copy the object to (for example, bucket2). + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String objectKey = args[0]; + String fromBucket = args[1]; + String toBucket = args[2]; + System.out.format("Copying object %s from bucket %s to %s\n", objectKey, fromBucket, toBucket); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + copyBucketObject(s3, fromBucket, objectKey, toBucket); + s3.close(); + } + + public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { + CopyObjectRequest copyReq = CopyObjectRequest.builder() + .sourceBucket(fromBucket) + .sourceKey(objectKey) + .destinationBucket(toBucket) + .destinationKey(objectKey) + .build(); + + try { + CopyObjectResponse copyRes = s3.copyObject(copyReq); + return copyRes.copyObjectResult().toString(); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } +} +// snippet-end:[s3.java2.copy_object.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CopyObjectStorage.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObjectStorage.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/CopyObjectStorage.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObjectStorage.java index 9f0dc0e812e..703e37e5e75 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CopyObjectStorage.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CopyObjectStorage.java @@ -1,72 +1,72 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.copy_store.main] -// snippet-start:[s3.java2.copy_store.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.CopyObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -// snippet-end:[s3.java2.copy_store.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CopyObjectStorage { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - objectKey - The name of the object (for example, book.pdf). - fromBucket - The S3 bucket name that contains the object (for example, bucket1). - toBucket - The S3 bucket to copy the object to (for example, bucket2). - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String objectKey = args[0]; - String fromBucket = args[1]; - String toBucket = args[2]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - copyBucketObject(s3, fromBucket, objectKey, toBucket); - s3.close(); - } - - public static void copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { - CopyObjectRequest copyReq = CopyObjectRequest.builder() - .sourceBucket(fromBucket) - .sourceKey(objectKey) - .storageClass("DEEP_ARCHIVE") - .destinationBucket(toBucket) - .destinationKey(objectKey) - .build(); - - try { - s3.copyObject(copyReq); - System.out.println("You have successfully stored " + objectKey + " to DEEP_ARCHIVE."); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.copy_store.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.copy_store.main] +// snippet-start:[s3.java2.copy_store.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CopyObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +// snippet-end:[s3.java2.copy_store.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CopyObjectStorage { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + objectKey - The name of the object (for example, book.pdf). + fromBucket - The S3 bucket name that contains the object (for example, bucket1). + toBucket - The S3 bucket to copy the object to (for example, bucket2). + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String objectKey = args[0]; + String fromBucket = args[1]; + String toBucket = args[2]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + copyBucketObject(s3, fromBucket, objectKey, toBucket); + s3.close(); + } + + public static void copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { + CopyObjectRequest copyReq = CopyObjectRequest.builder() + .sourceBucket(fromBucket) + .sourceKey(objectKey) + .storageClass("DEEP_ARCHIVE") + .destinationBucket(toBucket) + .destinationKey(objectKey) + .build(); + + try { + s3.copyObject(copyReq); + System.out.println("You have successfully stored " + objectKey + " to DEEP_ARCHIVE."); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.copy_store.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CreateAccessPoint.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateAccessPoint.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/CreateAccessPoint.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateAccessPoint.java index 4c76e94e8ee..18583068081 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CreateAccessPoint.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateAccessPoint.java @@ -1,91 +1,91 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.create_access_point.main] -// snippet-start:[s3.java2.create_access_point.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3control.S3ControlClient; -import software.amazon.awssdk.services.s3control.model.CreateAccessPointRequest; -import software.amazon.awssdk.services.s3control.model.S3ControlException; -import software.amazon.awssdk.services.s3control.model.DeleteAccessPointRequest; -// snippet-end:[s3.java2.create_access_point.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CreateAccessPoint { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - accountId - The account id that owns the Amazon S3 bucket.\s - bucketName - The Amazon S3 bucket name.\s - accessPointName - The access point name (for example, myaccesspoint).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String accountId = args[0]; - String bucketName = args[1]; - String accessPointName = args[2]; - Region region = Region.US_EAST_1; - S3ControlClient s3ControlClient = S3ControlClient.builder() - .region(region) - .build(); - - createSpecificAccessPoint(s3ControlClient, accountId, bucketName, accessPointName); - deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName); - s3ControlClient.close(); - } - - // This method creates an access point for the given Amazon S3 bucket. - public static void createSpecificAccessPoint(S3ControlClient s3ControlClient, String accountId, String bucketName, - String accessPointName) { - try { - CreateAccessPointRequest accessPointRequest = CreateAccessPointRequest.builder() - .accountId(accountId) - .bucket(bucketName) - .name(accessPointName) - .build(); - - s3ControlClient.createAccessPoint(accessPointRequest); - System.out.println("The access point was created"); - - } catch (S3ControlException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteSpecificAccessPoint(S3ControlClient s3ControlClient, String accountId, - String accessPointName) { - try { - DeleteAccessPointRequest deleteAccessPointRequest = DeleteAccessPointRequest.builder() - .name(accessPointName) - .accountId(accountId) - .build(); - - s3ControlClient.deleteAccessPoint(deleteAccessPointRequest); - System.out.println("The access point was deleted"); - - } catch (S3ControlException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.create_access_point.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.create_access_point.main] +// snippet-start:[s3.java2.create_access_point.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3control.S3ControlClient; +import software.amazon.awssdk.services.s3control.model.CreateAccessPointRequest; +import software.amazon.awssdk.services.s3control.model.S3ControlException; +import software.amazon.awssdk.services.s3control.model.DeleteAccessPointRequest; +// snippet-end:[s3.java2.create_access_point.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CreateAccessPoint { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + accountId - The account id that owns the Amazon S3 bucket.\s + bucketName - The Amazon S3 bucket name.\s + accessPointName - The access point name (for example, myaccesspoint).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String accountId = args[0]; + String bucketName = args[1]; + String accessPointName = args[2]; + Region region = Region.US_EAST_1; + S3ControlClient s3ControlClient = S3ControlClient.builder() + .region(region) + .build(); + + createSpecificAccessPoint(s3ControlClient, accountId, bucketName, accessPointName); + deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName); + s3ControlClient.close(); + } + + // This method creates an access point for the given Amazon S3 bucket. + public static void createSpecificAccessPoint(S3ControlClient s3ControlClient, String accountId, String bucketName, + String accessPointName) { + try { + CreateAccessPointRequest accessPointRequest = CreateAccessPointRequest.builder() + .accountId(accountId) + .bucket(bucketName) + .name(accessPointName) + .build(); + + s3ControlClient.createAccessPoint(accessPointRequest); + System.out.println("The access point was created"); + + } catch (S3ControlException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void deleteSpecificAccessPoint(S3ControlClient s3ControlClient, String accountId, + String accessPointName) { + try { + DeleteAccessPointRequest deleteAccessPointRequest = DeleteAccessPointRequest.builder() + .name(accessPointName) + .accountId(accountId) + .build(); + + s3ControlClient.deleteAccessPoint(deleteAccessPointRequest); + System.out.println("The access point was deleted"); + + } catch (S3ControlException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.create_access_point.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CreateBucket.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateBucket.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/CreateBucket.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateBucket.java index 3d585016ff1..b95f7548731 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CreateBucket.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateBucket.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.create_bucket_waiters.main] -// snippet-start:[s3.java2.create_bucket_waiters.import] -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.CreateBucketRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.waiters.S3Waiter; -import java.net.URISyntaxException; -// snippet-end:[s3.java2.create_bucket_waiters.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CreateBucket { - public static void main(String[] args) throws URISyntaxException { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - System.out.format("Creating a bucket named %s\n", bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - createBucket(s3, bucketName); - s3.close(); - } - - public static void createBucket(S3Client s3Client, String bucketName) { - try { - S3Waiter s3Waiter = s3Client.waiter(); - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); - - s3Client.createBucket(bucketRequest); - HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); - - // Wait until the bucket is created and print out the response. - WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName + " is ready"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.create_bucket_waiters.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.create_bucket_waiters.main] +// snippet-start:[s3.java2.create_bucket_waiters.import] +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.waiters.S3Waiter; +import java.net.URISyntaxException; +// snippet-end:[s3.java2.create_bucket_waiters.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CreateBucket { + public static void main(String[] args) throws URISyntaxException { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + System.out.format("Creating a bucket named %s\n", bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + createBucket(s3, bucketName); + s3.close(); + } + + public static void createBucket(S3Client s3Client, String bucketName) { + try { + S3Waiter s3Waiter = s3Client.waiter(); + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .build(); + + s3Client.createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response. + WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println(bucketName + " is ready"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.create_bucket_waiters.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/CreateJob.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateJob.java similarity index 98% rename from javav2/example_code/s3/src/main/java/com/example/s3/CreateJob.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateJob.java index 0feb71178bb..70911fe116b 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/CreateJob.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/CreateJob.java @@ -1,129 +1,129 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.create_job.main] -// snippet-start:[s3.java2.create_job.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3control.S3ControlClient; -import software.amazon.awssdk.services.s3control.model.S3Tag; -import software.amazon.awssdk.services.s3control.model.S3SetObjectTaggingOperation; -import software.amazon.awssdk.services.s3control.model.JobOperation; -import software.amazon.awssdk.services.s3control.model.JobManifestLocation; -import software.amazon.awssdk.services.s3control.model.JobManifestSpec; -import software.amazon.awssdk.services.s3control.model.JobManifest; -import software.amazon.awssdk.services.s3control.model.JobReport; -import software.amazon.awssdk.services.s3control.model.CreateJobRequest; -import software.amazon.awssdk.services.s3control.model.S3ControlException; -import java.util.ArrayList; -// snippet-end:[s3.java2.create_job.import] - -/** - * To run this code example, ensure that you have followed the documentation - * provided here: - * - * https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops-create-job.html - * - * In addition, before running this Java V2 code example, set up your - * development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class CreateJob { - public static void main(String[] args) { - final String usage = """ - - Usage: - > - - Where: - accountId - The account id value that owns the Amazon S3 bucket. - iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. - manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). - reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). - """; - - if (args.length != 4) { - System.out.println(usage); - System.exit(1); - } - - String accountId = args[0]; - String iamRoleArn = args[1]; - String manifestLocation = args[2]; - String reportBucketName = args[3]; - String uuid = java.util.UUID.randomUUID().toString(); - Region region = Region.US_EAST_1; - S3ControlClient s3ControlClient = S3ControlClient.builder() - .region(region) - .build(); - createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, uuid); - s3ControlClient.close(); - } - - public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, - String manifestLocation, String reportBucketName, String uuid) { - try { - ArrayList tagSet = new ArrayList<>(); - S3Tag s3Tag = S3Tag.builder() - .key("keyOne") - .value("ValueOne") - .build(); - - tagSet.add(s3Tag); - S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() - .tagSet(s3Tag) - .build(); - - JobOperation jobOperation = JobOperation.builder() - .s3PutObjectTagging(objectTaggingOperation) - .build(); - - JobManifestLocation jobManifestLocation = JobManifestLocation.builder() - .objectArn(manifestLocation) - .eTag("60e460c9d1046e73f7dde5043ac3ae85") - .build(); - - JobManifestSpec manifestSpec = JobManifestSpec.builder() - .fieldsWithStrings(new String[] { "Bucket", "Key" }) - .format("S3BatchOperations_CSV_20180820") - .build(); - - JobManifest jobManifest = JobManifest.builder() - .spec(manifestSpec) - .location(jobManifestLocation) - .build(); - - JobReport jobReport = JobReport.builder() - .bucket(reportBucketName) - .prefix("reports") - .format("Report_CSV_20180820") - .enabled(true) - .reportScope("AllTasks") - .build(); - - CreateJobRequest jobRequest = CreateJobRequest.builder() - .accountId(accountId) - .description("Job created using the AWS Java SDK") - .manifest(jobManifest) - .operation(jobOperation) - .report(jobReport) - .priority(42) - .roleArn(iamRoleArn) - .clientRequestToken(uuid) - .confirmationRequired(false) - .build(); - - s3ControlClient.createJob(jobRequest); - - } catch (S3ControlException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.create_job.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.create_job.main] +// snippet-start:[s3.java2.create_job.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3control.S3ControlClient; +import software.amazon.awssdk.services.s3control.model.S3Tag; +import software.amazon.awssdk.services.s3control.model.S3SetObjectTaggingOperation; +import software.amazon.awssdk.services.s3control.model.JobOperation; +import software.amazon.awssdk.services.s3control.model.JobManifestLocation; +import software.amazon.awssdk.services.s3control.model.JobManifestSpec; +import software.amazon.awssdk.services.s3control.model.JobManifest; +import software.amazon.awssdk.services.s3control.model.JobReport; +import software.amazon.awssdk.services.s3control.model.CreateJobRequest; +import software.amazon.awssdk.services.s3control.model.S3ControlException; +import java.util.ArrayList; +// snippet-end:[s3.java2.create_job.import] + +/** + * To run this code example, ensure that you have followed the documentation + * provided here: + * + * https://docs.aws.amazon.com/AmazonS3/latest/dev/batch-ops-create-job.html + * + * In addition, before running this Java V2 code example, set up your + * development environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class CreateJob { + public static void main(String[] args) { + final String usage = """ + + Usage: + > + + Where: + accountId - The account id value that owns the Amazon S3 bucket. + iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. + manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). + reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). + """; + + if (args.length != 4) { + System.out.println(usage); + System.exit(1); + } + + String accountId = args[0]; + String iamRoleArn = args[1]; + String manifestLocation = args[2]; + String reportBucketName = args[3]; + String uuid = java.util.UUID.randomUUID().toString(); + Region region = Region.US_EAST_1; + S3ControlClient s3ControlClient = S3ControlClient.builder() + .region(region) + .build(); + createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, uuid); + s3ControlClient.close(); + } + + public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, + String manifestLocation, String reportBucketName, String uuid) { + try { + ArrayList tagSet = new ArrayList<>(); + S3Tag s3Tag = S3Tag.builder() + .key("keyOne") + .value("ValueOne") + .build(); + + tagSet.add(s3Tag); + S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() + .tagSet(s3Tag) + .build(); + + JobOperation jobOperation = JobOperation.builder() + .s3PutObjectTagging(objectTaggingOperation) + .build(); + + JobManifestLocation jobManifestLocation = JobManifestLocation.builder() + .objectArn(manifestLocation) + .eTag("60e460c9d1046e73f7dde5043ac3ae85") + .build(); + + JobManifestSpec manifestSpec = JobManifestSpec.builder() + .fieldsWithStrings(new String[] { "Bucket", "Key" }) + .format("S3BatchOperations_CSV_20180820") + .build(); + + JobManifest jobManifest = JobManifest.builder() + .spec(manifestSpec) + .location(jobManifestLocation) + .build(); + + JobReport jobReport = JobReport.builder() + .bucket(reportBucketName) + .prefix("reports") + .format("Report_CSV_20180820") + .enabled(true) + .reportScope("AllTasks") + .build(); + + CreateJobRequest jobRequest = CreateJobRequest.builder() + .accountId(accountId) + .description("Job created using the AWS Java SDK") + .manifest(jobManifest) + .operation(jobOperation) + .report(jobReport) + .priority(42) + .roleArn(iamRoleArn) + .clientRequestToken(uuid) + .confirmationRequired(false) + .build(); + + s3ControlClient.createJob(jobRequest); + + } catch (S3ControlException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.create_job.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java old mode 100755 new mode 100644 similarity index 96% rename from javav2/example_code/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java index 76f8fdb9ebf..718939c5d03 --- a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteBucketPolicy.java @@ -1,66 +1,66 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.delete_bucket_policy.main] -// snippet-start:[s3.java2.delete_bucket_policy.import] -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteBucketPolicyRequest; -// snippet-end:[s3.java2.delete_bucket_policy.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class DeleteBucketPolicy { - public static void main(String[] args) { - - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket to delete the policy from (for example, bucket1)."""; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - System.out.format("Deleting policy from bucket: \"%s\"\n\n", bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - deleteS3BucketPolicy(s3, bucketName); - s3.close(); - } - - // Delete the bucket policy. - public static void deleteS3BucketPolicy(S3Client s3, String bucketName) { - DeleteBucketPolicyRequest delReq = DeleteBucketPolicyRequest.builder() - .bucket(bucketName) - .build(); - - try { - s3.deleteBucketPolicy(delReq); - System.out.println("Done!"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.delete_bucket_policy.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.delete_bucket_policy.main] +// snippet-start:[s3.java2.delete_bucket_policy.import] +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteBucketPolicyRequest; +// snippet-end:[s3.java2.delete_bucket_policy.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class DeleteBucketPolicy { + public static void main(String[] args) { + + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket to delete the policy from (for example, bucket1)."""; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + System.out.format("Deleting policy from bucket: \"%s\"\n\n", bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + deleteS3BucketPolicy(s3, bucketName); + s3.close(); + } + + // Delete the bucket policy. + public static void deleteS3BucketPolicy(S3Client s3, String bucketName) { + DeleteBucketPolicyRequest delReq = DeleteBucketPolicyRequest.builder() + .bucket(bucketName) + .build(); + + try { + s3.deleteBucketPolicy(delReq); + System.out.println("Done!"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.delete_bucket_policy.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteMultiObjects.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteMultiObjects.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/DeleteMultiObjects.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteMultiObjects.java index 1f02486d5c0..0571624e250 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteMultiObjects.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteMultiObjects.java @@ -1,96 +1,96 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.delete_many_objects.main] -// snippet-start:[s3.java2.delete_many_objects.import] -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.ObjectIdentifier; -import software.amazon.awssdk.services.s3.model.Delete; -import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.util.ArrayList; -// snippet-end:[s3.java2.delete_many_objects.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class DeleteMultiObjects { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - bucketName - the Amazon S3 bucket name. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - deleteBucketObjects(s3, bucketName); - s3.close(); - } - - public static void deleteBucketObjects(S3Client s3, String bucketName) { - // Upload three sample objects to the specfied Amazon S3 bucket. - ArrayList keys = new ArrayList<>(); - PutObjectRequest putOb; - ObjectIdentifier objectId; - - for (int i = 0; i < 3; i++) { - String keyName = "delete object example " + i; - objectId = ObjectIdentifier.builder() - .key(keyName) - .build(); - - putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); - - s3.putObject(putOb, RequestBody.fromString(keyName)); - keys.add(objectId); - } - - System.out.println(keys.size() + " objects successfully created."); - - // Delete multiple objects in one request. - Delete del = Delete.builder() - .objects(keys) - .build(); - - try { - DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder() - .bucket(bucketName) - .delete(del) - .build(); - - s3.deleteObjects(multiObjectDeleteRequest); - System.out.println("Multiple objects are deleted!"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.delete_many_objects.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.delete_many_objects.main] +// snippet-start:[s3.java2.delete_many_objects.import] +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.ObjectIdentifier; +import software.amazon.awssdk.services.s3.model.Delete; +import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.util.ArrayList; +// snippet-end:[s3.java2.delete_many_objects.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class DeleteMultiObjects { + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + bucketName - the Amazon S3 bucket name. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + deleteBucketObjects(s3, bucketName); + s3.close(); + } + + public static void deleteBucketObjects(S3Client s3, String bucketName) { + // Upload three sample objects to the specfied Amazon S3 bucket. + ArrayList keys = new ArrayList<>(); + PutObjectRequest putOb; + ObjectIdentifier objectId; + + for (int i = 0; i < 3; i++) { + String keyName = "delete object example " + i; + objectId = ObjectIdentifier.builder() + .key(keyName) + .build(); + + putOb = PutObjectRequest.builder() + .bucket(bucketName) + .key(keyName) + .build(); + + s3.putObject(putOb, RequestBody.fromString(keyName)); + keys.add(objectId); + } + + System.out.println(keys.size() + " objects successfully created."); + + // Delete multiple objects in one request. + Delete del = Delete.builder() + .objects(keys) + .build(); + + try { + DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder() + .bucket(bucketName) + .delete(del) + .build(); + + s3.deleteObjects(multiObjectDeleteRequest); + System.out.println("Multiple objects are deleted!"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.delete_many_objects.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteObjects.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteObjects.java old mode 100755 new mode 100644 similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/DeleteObjects.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteObjects.java index 3ea949735fe..e4d7c6f016b --- a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteObjects.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteObjects.java @@ -1,76 +1,76 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.delete_objects.main] -// snippet-start:[s3.java2.delete_objects.import] -import software.amazon.awssdk.services.s3.model.Delete; -import software.amazon.awssdk.services.s3.model.ObjectIdentifier; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; -import java.util.ArrayList; -// snippet-end:[s3.java2.delete_objects.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class DeleteObjects { - public static void main(String[] args) { - final String usage = """ - Usage: - - Where: - bucketName - The Amazon S3 bucket to delete the website configuration from. - objectName - The object name. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String objectName = args[1]; - System.out.println("Deleting " + objectName + " from the Amazon S3 bucket: " + bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - deleteBucketObjects(s3, bucketName, objectName); - s3.close(); - } - - public static void deleteBucketObjects(S3Client s3, String bucketName, String objectName) { - ArrayList toDelete = new ArrayList<>(); - toDelete.add(ObjectIdentifier.builder() - .key(objectName) - .build()); - - try { - DeleteObjectsRequest dor = DeleteObjectsRequest.builder() - .bucket(bucketName) - .delete(Delete.builder() - .objects(toDelete).build()) - .build(); - - s3.deleteObjects(dor); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - - System.out.println("Done!"); - } -} -// snippet-end:[s3.java2.delete_objects.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.delete_objects.main] +// snippet-start:[s3.java2.delete_objects.import] +import software.amazon.awssdk.services.s3.model.Delete; +import software.amazon.awssdk.services.s3.model.ObjectIdentifier; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; +import java.util.ArrayList; +// snippet-end:[s3.java2.delete_objects.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class DeleteObjects { + public static void main(String[] args) { + final String usage = """ + Usage: + + Where: + bucketName - The Amazon S3 bucket to delete the website configuration from. + objectName - The object name. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String objectName = args[1]; + System.out.println("Deleting " + objectName + " from the Amazon S3 bucket: " + bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + deleteBucketObjects(s3, bucketName, objectName); + s3.close(); + } + + public static void deleteBucketObjects(S3Client s3, String bucketName, String objectName) { + ArrayList toDelete = new ArrayList<>(); + toDelete.add(ObjectIdentifier.builder() + .key(objectName) + .build()); + + try { + DeleteObjectsRequest dor = DeleteObjectsRequest.builder() + .bucket(bucketName) + .delete(Delete.builder() + .objects(toDelete).build()) + .build(); + + s3.deleteObjects(dor); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + + System.out.println("Done!"); + } +} +// snippet-end:[s3.java2.delete_objects.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java index ba76d4ae0b1..a2705150778 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/DeleteWebsiteConfiguration.java @@ -1,65 +1,65 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.delete_website_configuration.main] -// snippet-start:[s3.java2.delete_website_configuration.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteBucketWebsiteRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -// snippet-end:[s3.java2.delete_website_configuration.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class DeleteWebsiteConfiguration { - public static void main(String[] args) { - final String usage = """ - - Usage: - - Where: - bucketName - The Amazon S3 bucket to delete the website configuration from. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - System.out.format("Deleting website configuration for Amazon S3 bucket: %s\n", bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - deleteBucketWebsiteConfig(s3, bucketName); - System.out.println("Done!"); - s3.close(); - } - - public static void deleteBucketWebsiteConfig(S3Client s3, String bucketName) { - DeleteBucketWebsiteRequest delReq = DeleteBucketWebsiteRequest.builder() - .bucket(bucketName) - .build(); - - try { - s3.deleteBucketWebsite(delReq); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.out.println("Failed to delete website configuration!"); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.delete_website_configuration.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.delete_website_configuration.main] +// snippet-start:[s3.java2.delete_website_configuration.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteBucketWebsiteRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +// snippet-end:[s3.java2.delete_website_configuration.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class DeleteWebsiteConfiguration { + public static void main(String[] args) { + final String usage = """ + + Usage: + + Where: + bucketName - The Amazon S3 bucket to delete the website configuration from. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + System.out.format("Deleting website configuration for Amazon S3 bucket: %s\n", bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + deleteBucketWebsiteConfig(s3, bucketName); + System.out.println("Done!"); + s3.close(); + } + + public static void deleteBucketWebsiteConfig(S3Client s3, String bucketName) { + DeleteBucketWebsiteRequest delReq = DeleteBucketWebsiteRequest.builder() + .bucket(bucketName) + .build(); + + try { + s3.deleteBucketWebsite(delReq); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.out.println("Failed to delete website configuration!"); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.delete_website_configuration.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedGetUrlAndRetrieve.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndPutFileWithMetadata.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java index 736f387cd62..9fc6d2d578d 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GeneratePresignedUrlAndUploadObject.java @@ -1,141 +1,141 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[presigned.java2.generatepresignedurl.import] - -import com.example.s3.util.PresignUrlUtils; -import org.slf4j.Logger; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.presigner.S3Presigner; -import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; -import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.UUID; -// snippet-end:[presigned.java2.generatepresignedurl.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - *

- * For more information, see the following documentation topic: - *

- * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GeneratePresignedUrlAndUploadObject { - private static final Logger logger = org.slf4j.LoggerFactory.getLogger(GeneratePresignedUrlAndUploadObject.class); - - public static void main(String[] args) { - - String bucketName = "b-" + UUID.randomUUID(); - String keyName = "k-" + UUID.randomUUID(); - - try (S3Client s3Client = S3Client.create()) { - PresignUrlUtils.createBucket(bucketName, s3Client); - GeneratePresignedUrlAndUploadObject presignAndPut = new GeneratePresignedUrlAndUploadObject(); - try { - URL presignedUrl = presignAndPut.createSignedUrlForStringPut(bucketName, keyName); - presignAndPut.useHttpUrlConnectionToPutString(presignedUrl); - presignAndPut.useHttpClientToPutString(presignedUrl); - } finally { - PresignUrlUtils.deleteObject(bucketName, keyName, s3Client); - PresignUrlUtils.deleteBucket(bucketName, s3Client); - } - } - } - - // snippet-start:[presigned.java2.generatepresignedurl.main] - /** - * Create a presigned URL for uploading a String object. - * - * @param bucketName - The name of the bucket. - * @param keyName - The name of the object. - * @return - The presigned URL for an HTTP PUT. - */ - public URL createSignedUrlForStringPut(String bucketName, String keyName) { - try (S3Presigner presigner = S3Presigner.create()) { - - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .contentType("text/plain") - .build(); - - PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder() - .signatureDuration(Duration.ofMinutes(10)) // The URL will expire in 10 minutes. - .putObjectRequest(objectRequest) - .build(); - - PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest); - String myURL = presignedRequest.url().toString(); - logger.info("Presigned URL to upload to: [{}]", myURL); - logger.info("Which HTTP method needs to be used when uploading: [{}]", - presignedRequest.httpRequest().method()); - - return presignedRequest.url(); - } - } - - /** - * Use the JDK HttpURLConnection (since v1.1) class to upload a String, but you - * can - * use any HTTP client. - * - * @param presignedUrl - The presigned URL. - */ - public void useHttpUrlConnectionToPutString(URL presignedUrl) { - try { - // Create the connection and use it to upload the new object by using the - // presigned URL. - HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection(); - connection.setDoOutput(true); - connection.setRequestProperty("Content-Type", "text/plain"); - connection.setRequestMethod("PUT"); - OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); - out.write("This text was uploaded as an object by using a presigned URL."); - out.close(); - - connection.getResponseCode(); - logger.info("HTTP response code is " + connection.getResponseCode()); - - } catch (S3Exception | IOException e) { - logger.error(e.getMessage(), e); - } - } - - /** - * Use the JDK HttpClient class (since v11) to upload a String, - * but you can use any HTTP client. - * - * @param presignedUrl - The presigned URL. - */ - public void useHttpClientToPutString(URL presignedUrl) { - HttpClient httpClient = HttpClient.newHttpClient(); - try { - final HttpResponse response = httpClient.send(HttpRequest.newBuilder() - .uri(presignedUrl.toURI()) - .header("Content-Type", "text/plain") - .PUT(HttpRequest.BodyPublishers - .ofString("This text was uploaded as an object by using a presigned URL.")) - .build(), - HttpResponse.BodyHandlers.discarding()); - logger.info("HTTP response code is " + response.statusCode()); - } catch (S3Exception | IOException | URISyntaxException | InterruptedException e) { - logger.error(e.getMessage(), e); - } - } - // snippet-end:[presigned.java2.generatepresignedurl.main] -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[presigned.java2.generatepresignedurl.import] + +import com.example.s3.util.PresignUrlUtils; +import org.slf4j.Logger; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; +import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.UUID; +// snippet-end:[presigned.java2.generatepresignedurl.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + *

+ * For more information, see the following documentation topic: + *

+ * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GeneratePresignedUrlAndUploadObject { + private static final Logger logger = org.slf4j.LoggerFactory.getLogger(GeneratePresignedUrlAndUploadObject.class); + + public static void main(String[] args) { + + String bucketName = "b-" + UUID.randomUUID(); + String keyName = "k-" + UUID.randomUUID(); + + try (S3Client s3Client = S3Client.create()) { + PresignUrlUtils.createBucket(bucketName, s3Client); + GeneratePresignedUrlAndUploadObject presignAndPut = new GeneratePresignedUrlAndUploadObject(); + try { + URL presignedUrl = presignAndPut.createSignedUrlForStringPut(bucketName, keyName); + presignAndPut.useHttpUrlConnectionToPutString(presignedUrl); + presignAndPut.useHttpClientToPutString(presignedUrl); + } finally { + PresignUrlUtils.deleteObject(bucketName, keyName, s3Client); + PresignUrlUtils.deleteBucket(bucketName, s3Client); + } + } + } + + // snippet-start:[presigned.java2.generatepresignedurl.main] + /** + * Create a presigned URL for uploading a String object. + * + * @param bucketName - The name of the bucket. + * @param keyName - The name of the object. + * @return - The presigned URL for an HTTP PUT. + */ + public URL createSignedUrlForStringPut(String bucketName, String keyName) { + try (S3Presigner presigner = S3Presigner.create()) { + + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(keyName) + .contentType("text/plain") + .build(); + + PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(10)) // The URL will expire in 10 minutes. + .putObjectRequest(objectRequest) + .build(); + + PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest); + String myURL = presignedRequest.url().toString(); + logger.info("Presigned URL to upload to: [{}]", myURL); + logger.info("Which HTTP method needs to be used when uploading: [{}]", + presignedRequest.httpRequest().method()); + + return presignedRequest.url(); + } + } + + /** + * Use the JDK HttpURLConnection (since v1.1) class to upload a String, but you + * can + * use any HTTP client. + * + * @param presignedUrl - The presigned URL. + */ + public void useHttpUrlConnectionToPutString(URL presignedUrl) { + try { + // Create the connection and use it to upload the new object by using the + // presigned URL. + HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection(); + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "text/plain"); + connection.setRequestMethod("PUT"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write("This text was uploaded as an object by using a presigned URL."); + out.close(); + + connection.getResponseCode(); + logger.info("HTTP response code is " + connection.getResponseCode()); + + } catch (S3Exception | IOException e) { + logger.error(e.getMessage(), e); + } + } + + /** + * Use the JDK HttpClient class (since v11) to upload a String, + * but you can use any HTTP client. + * + * @param presignedUrl - The presigned URL. + */ + public void useHttpClientToPutString(URL presignedUrl) { + HttpClient httpClient = HttpClient.newHttpClient(); + try { + final HttpResponse response = httpClient.send(HttpRequest.newBuilder() + .uri(presignedUrl.toURI()) + .header("Content-Type", "text/plain") + .PUT(HttpRequest.BodyPublishers + .ofString("This text was uploaded as an object by using a presigned URL.")) + .build(), + HttpResponse.BodyHandlers.discarding()); + logger.info("HTTP response code is " + response.statusCode()); + } catch (S3Exception | IOException | URISyntaxException | InterruptedException e) { + logger.error(e.getMessage(), e); + } + } + // snippet-end:[presigned.java2.generatepresignedurl.main] +} diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetAcl.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetAcl.java index 3c72a0d41f0..1cdcb6ef371 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetAcl.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetAcl.java @@ -1,81 +1,81 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.get_acl.main] -// snippet-start:[s3.java2.get_acl.import] -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetObjectAclRequest; -import software.amazon.awssdk.services.s3.model.GetObjectAclResponse; -import software.amazon.awssdk.services.s3.model.Grant; -import java.util.List; -// snippet-end:[s3.java2.get_acl.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetAcl { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket to get the access control list (ACL) for. - objectKey - The object to get the ACL for.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - System.out.println("Retrieving ACL for object: " + objectKey); - System.out.println("in bucket: " + bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - getBucketACL(s3, objectKey, bucketName); - s3.close(); - System.out.println("Done!"); - } - - public static String getBucketACL(S3Client s3, String objectKey, String bucketName) { - try { - GetObjectAclRequest aclReq = GetObjectAclRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); - - GetObjectAclResponse aclRes = s3.getObjectAcl(aclReq); - List grants = aclRes.grants(); - String grantee = ""; - for (Grant grant : grants) { - System.out.format(" %s: %s\n", grant.grantee().id(), grant.permission()); - grantee = grant.grantee().id(); - } - - return grantee; - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - - return ""; - } -} -// snippet-end:[s3.java2.get_acl.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.get_acl.main] +// snippet-start:[s3.java2.get_acl.import] +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectAclRequest; +import software.amazon.awssdk.services.s3.model.GetObjectAclResponse; +import software.amazon.awssdk.services.s3.model.Grant; +import java.util.List; +// snippet-end:[s3.java2.get_acl.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetAcl { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket to get the access control list (ACL) for. + objectKey - The object to get the ACL for.\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + System.out.println("Retrieving ACL for object: " + objectKey); + System.out.println("in bucket: " + bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + getBucketACL(s3, objectKey, bucketName); + s3.close(); + System.out.println("Done!"); + } + + public static String getBucketACL(S3Client s3, String objectKey, String bucketName) { + try { + GetObjectAclRequest aclReq = GetObjectAclRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + GetObjectAclResponse aclRes = s3.getObjectAcl(aclReq); + List grants = aclRes.grants(); + String grantee = ""; + for (Grant grant : grants) { + System.out.format(" %s: %s\n", grant.grantee().id(), grant.permission()); + grantee = grant.grantee().id(); + } + + return grantee; + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + + return ""; + } +} +// snippet-end:[s3.java2.get_acl.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetBucketPolicy.java old mode 100755 new mode 100644 similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetBucketPolicy.java index 74a4118449c..9dc285f1b25 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetBucketPolicy.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetBucketPolicy.java @@ -1,72 +1,72 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.get_bucket_policy.main] -// snippet-start:[s3.java2.get_bucket_policy.import] -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest; -import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse; -// snippet-end:[s3.java2.get_bucket_policy.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetBucketPolicy { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket to get the policy from. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - String polText = getPolicy(s3, bucketName); - System.out.println("Policy Text: " + polText); - s3.close(); - } - - public static String getPolicy(S3Client s3, String bucketName) { - String policyText; - System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); - GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder() - .bucket(bucketName) - .build(); - - try { - GetBucketPolicyResponse policyRes = s3.getBucketPolicy(policyReq); - policyText = policyRes.policy(); - return policyText; - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - - return ""; - } -} -// snippet-end:[s3.java2.get_bucket_policy.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.get_bucket_policy.main] +// snippet-start:[s3.java2.get_bucket_policy.import] +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest; +import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse; +// snippet-end:[s3.java2.get_bucket_policy.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetBucketPolicy { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket to get the policy from. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + String polText = getPolicy(s3, bucketName); + System.out.println("Policy Text: " + polText); + s3.close(); + } + + public static String getPolicy(S3Client s3, String bucketName) { + String policyText; + System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName); + GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder() + .bucket(bucketName) + .build(); + + try { + GetBucketPolicyResponse policyRes = s3.getBucketPolicy(policyReq); + policyText = policyRes.policy(); + return policyText; + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + + return ""; + } +} +// snippet-end:[s3.java2.get_bucket_policy.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetDataResponseTransformer.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectContentType.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectContentType.java index d01c8f9620d..00d0ccfd8fe 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectContentType.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectContentType.java @@ -1,68 +1,68 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.getobjectcontenttype.main] -// snippet-start:[s3.java2.getobjectcontenttype.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.HeadObjectRequest; -import software.amazon.awssdk.services.s3.model.HeadObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -// snippet-end:[s3.java2.getobjectcontenttype.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class GetObjectContentType { - public static void main(String[] args) { - final String usage = """ - - Usage: - > - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - getContentType(s3, bucketName, keyName); - s3.close(); - } - - public static void getContentType(S3Client s3, String bucketName, String keyName) { - try { - HeadObjectRequest objectRequest = HeadObjectRequest.builder() - .key(keyName) - .bucket(bucketName) - .build(); - - HeadObjectResponse objectHead = s3.headObject(objectRequest); - String type = objectHead.contentType(); - System.out.println("The object content type is " + type); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.getobjectcontenttype.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.getobjectcontenttype.main] +// snippet-start:[s3.java2.getobjectcontenttype.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +// snippet-end:[s3.java2.getobjectcontenttype.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class GetObjectContentType { + public static void main(String[] args) { + final String usage = """ + + Usage: + > + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + getContentType(s3, bucketName, keyName); + s3.close(); + } + + public static void getContentType(S3Client s3, String bucketName, String keyName) { + try { + HeadObjectRequest objectRequest = HeadObjectRequest.builder() + .key(keyName) + .bucket(bucketName) + .build(); + + HeadObjectResponse objectHead = s3.headObject(objectRequest); + String type = objectHead.contentType(); + System.out.println("The object content type is " + type); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.getobjectcontenttype.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectData.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectData.java index 510dd8539e7..609c3a65f61 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectData.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectData.java @@ -1,84 +1,84 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.getobjectdata.main] -// snippet-start:[s3.java2.getobjectdata.import] -import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -// snippet-end:[s3.java2.getobjectdata.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetObjectData { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - path - The path where the file is written to.\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - String path = args[2]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - getObjectBytes(s3, bucketName, keyName, path); - } - - public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { - try { - GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); - - ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); - byte[] data = objectBytes.asByteArray(); - - // Write the data to a local file. - File myFile = new File(path); - OutputStream os = new FileOutputStream(myFile); - os.write(data); - System.out.println("Successfully obtained bytes from an S3 object"); - os.close(); - - } catch (IOException ex) { - ex.printStackTrace(); - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.getobjectdata.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.getobjectdata.main] +// snippet-start:[s3.java2.getobjectdata.import] +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +// snippet-end:[s3.java2.getobjectdata.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetObjectData { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + path - The path where the file is written to.\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + String path = args[2]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + getObjectBytes(s3, bucketName, keyName, path); + } + + public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { + try { + GetObjectRequest objectRequest = GetObjectRequest + .builder() + .key(keyName) + .bucket(bucketName) + .build(); + + ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); + byte[] data = objectBytes.asByteArray(); + + // Write the data to a local file. + File myFile = new File(path); + OutputStream os = new FileOutputStream(myFile); + os.write(data); + System.out.println("Successfully obtained bytes from an S3 object"); + os.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.getobjectdata.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java index 4ea26af1182..23749c856e2 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectPresignedUrl.java @@ -1,102 +1,102 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[presigned.java2.getobjectpresigned.main] -// snippet-start:[presigned.java2.getobjectpresigned.import] -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.time.Duration; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; -import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; -import software.amazon.awssdk.services.s3.presigner.S3Presigner; -import software.amazon.awssdk.utils.IoUtils; -// snippet-end:[presigned.java2.getobjectpresigned.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class GetObjectPresignedUrl { - public static void main(String[] args) { - final String USAGE = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - A key name that represents a text file.\s - """; - - if (args.length != 2) { - System.out.println(USAGE); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - Region region = Region.US_EAST_1; - S3Presigner presigner = S3Presigner.builder() - .region(region) - .build(); - - getPresignedUrl(presigner, bucketName, keyName); - presigner.close(); - } - - public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName) { - try { - GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(keyName) - .build(); - - GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() - .signatureDuration(Duration.ofMinutes(60)) - .getObjectRequest(getObjectRequest) - .build(); - - PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest); - String theUrl = presignedGetObjectRequest.url().toString(); - System.out.println("Presigned URL: " + theUrl); - HttpURLConnection connection = (HttpURLConnection) presignedGetObjectRequest.url().openConnection(); - presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> { - values.forEach(value -> { - connection.addRequestProperty(header, value); - }); - }); - - // Send any request payload that the service needs (not needed when - // isBrowserExecutable is true). - if (presignedGetObjectRequest.signedPayload().isPresent()) { - connection.setDoOutput(true); - - try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream(); - OutputStream httpOutputStream = connection.getOutputStream()) { - IoUtils.copy(signedPayload, httpOutputStream); - } - } - - // Download the result of executing the request. - try (InputStream content = connection.getInputStream()) { - System.out.println("Service returned response: "); - IoUtils.copy(content, System.out); - } - - } catch (S3Exception | IOException e) { - e.getStackTrace(); - } - } -} -// snippet-end:[presigned.java2.getobjectpresigned.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[presigned.java2.getobjectpresigned.main] +// snippet-start:[presigned.java2.getobjectpresigned.import] +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.time.Duration; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; +import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.utils.IoUtils; +// snippet-end:[presigned.java2.getobjectpresigned.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class GetObjectPresignedUrl { + public static void main(String[] args) { + final String USAGE = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - A key name that represents a text file.\s + """; + + if (args.length != 2) { + System.out.println(USAGE); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + Region region = Region.US_EAST_1; + S3Presigner presigner = S3Presigner.builder() + .region(region) + .build(); + + getPresignedUrl(presigner, bucketName, keyName); + presigner.close(); + } + + public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName) { + try { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(keyName) + .build(); + + GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(60)) + .getObjectRequest(getObjectRequest) + .build(); + + PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest); + String theUrl = presignedGetObjectRequest.url().toString(); + System.out.println("Presigned URL: " + theUrl); + HttpURLConnection connection = (HttpURLConnection) presignedGetObjectRequest.url().openConnection(); + presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> { + values.forEach(value -> { + connection.addRequestProperty(header, value); + }); + }); + + // Send any request payload that the service needs (not needed when + // isBrowserExecutable is true). + if (presignedGetObjectRequest.signedPayload().isPresent()) { + connection.setDoOutput(true); + + try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream(); + OutputStream httpOutputStream = connection.getOutputStream()) { + IoUtils.copy(signedPayload, httpOutputStream); + } + } + + // Download the result of executing the request. + try (InputStream content = connection.getInputStream()) { + System.out.println("Service returned response: "); + IoUtils.copy(content, System.out); + } + + } catch (S3Exception | IOException e) { + e.getStackTrace(); + } + } +} +// snippet-end:[presigned.java2.getobjectpresigned.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectRestoreStatus.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectTags.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectTags.java index 86a3c73b7fa..0cd7871218b 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectTags.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectTags.java @@ -1,75 +1,75 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.getobjecttags.main] -// snippet-start:[s3.java2.getobjecttags.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest; -import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.Tag; -import java.util.List; -// snippet-end:[s3.java2.getobjecttags.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetObjectTags { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - A key name that represents the object.\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - listTags(s3, bucketName, keyName); - s3.close(); - } - - public static void listTags(S3Client s3, String bucketName, String keyName) { - try { - GetObjectTaggingRequest getTaggingRequest = GetObjectTaggingRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); - - GetObjectTaggingResponse tags = s3.getObjectTagging(getTaggingRequest); - List tagSet = tags.tagSet(); - for (Tag tag : tagSet) { - System.out.println(tag.key()); - System.out.println(tag.value()); - } - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.getobjecttags.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.getobjecttags.main] +// snippet-start:[s3.java2.getobjecttags.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest; +import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.Tag; +import java.util.List; +// snippet-end:[s3.java2.getobjecttags.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetObjectTags { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - A key name that represents the object.\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + listTags(s3, bucketName, keyName); + s3.close(); + } + + public static void listTags(S3Client s3, String bucketName, String keyName) { + try { + GetObjectTaggingRequest getTaggingRequest = GetObjectTaggingRequest + .builder() + .key(keyName) + .bucket(bucketName) + .build(); + + GetObjectTaggingResponse tags = s3.getObjectTagging(getTaggingRequest); + List tagSet = tags.tagSet(); + for (Tag tag : tagSet) { + System.out.println(tag.key()); + System.out.println(tag.value()); + } + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.getobjecttags.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectUrl.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/GetObjectUrl.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/GetObjectUrl.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/HelloS3.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/HelloS3.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/HelloS3.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/KMSEncryptionExample.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/KMSEncryptionExample.java index 5b57eadebfe..217eb4f7ad4 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/KMSEncryptionExample.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/KMSEncryptionExample.java @@ -1,220 +1,220 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.kms.main] -// snippet-start:[s3.java2.kms.import] -import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.core.SdkBytes; -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.kms.KmsClient; -import software.amazon.awssdk.services.kms.model.DecryptRequest; -import software.amazon.awssdk.services.kms.model.EncryptRequest; -import software.amazon.awssdk.services.kms.model.EncryptResponse; -import software.amazon.awssdk.services.kms.model.KmsException; -import software.amazon.awssdk.services.kms.model.DecryptResponse; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.io.IOException; -import java.io.FileInputStream; -// snippet-end:[s3.java2.kms.import] - -/** - * Before running this code example, you need to create a key by using the AWS - * Key Management Service. - * For information, see "Creating keys" in the AWS Key Management Service - * Developer Guide. - * - * In addition, before running this Java V2 code example, set up your - * development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - */ - -public class KMSEncryptionExample { - - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - objectName - The name of the object.\s - bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s - objectPath - The path to a TXT file to encrypt and place into a Amazon S3 bucket (for example, C:/AWS/test.txt). - outPath - The path where a text file is written to after it's decrypted (for example, C:/AWS/testPlain.txt). - keyId - The id of the AWS KMS key to use to encrpt/decrypt the data. You can obtain the key ID value from the AWS Management Console. - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String objectName = args[0]; - String bucketName = args[1]; - String objectPath = args[2]; - String outPath = args[3]; - String keyId = args[4]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - putEncryptData(s3, objectName, bucketName, objectPath, keyId); - getEncryptedData(s3, bucketName, objectName, outPath, keyId); - s3.close(); - } - - // Encrypt data and place the encrypted data into an Amazon S3 bucket. - public static void putEncryptData(S3Client s3, String objectName, String bucketName, String objectPath, - String keyId) { - try { - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectName) - .build(); - - byte[] myData = getObjectFile(objectPath); - - // Encrypt the data by using the AWS Key Management Service. - byte[] encryptData = encryptData(keyId, myData); - s3.putObject(objectRequest, RequestBody.fromBytes(encryptData)); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - // Obtain the encrypted data, decrypt it, and write the data to a text file. - public static void getEncryptedData(S3Client s3, String bucketName, String objectName, String path, String keyId) { - try { - GetObjectRequest objectRequest = GetObjectRequest.builder() - .key(objectName) - .bucket(bucketName) - .build(); - - // Get the byte[] from the Amazon S3 bucket. - ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); - byte[] data = objectBytes.asByteArray(); - - // Decrypt the data by using the AWS Key Management Service. - byte[] unEncryptedData = decryptData(data, keyId); - - // Write the data to a local file. - File myFile = new File(path); - OutputStream os = new FileOutputStream(myFile); - os.write(unEncryptedData); - System.out.println("Successfully obtained and decrypted bytes from the Amazon S3 bucket"); - os.close(); - - } catch (IOException ex) { - ex.printStackTrace(); - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // Encrypt the data passed as a byte array. - private static byte[] encryptData(String keyId, byte[] data) { - try { - KmsClient kmsClient = getKMSClient(); - SdkBytes myBytes = SdkBytes.fromByteArray(data); - - EncryptRequest encryptRequest = EncryptRequest.builder() - .keyId(keyId) - .plaintext(myBytes) - .build(); - - EncryptResponse response = kmsClient.encrypt(encryptRequest); - String algorithm = response.encryptionAlgorithm().toString(); - System.out.println("The encryption algorithm is " + algorithm); - - // Return the encrypted data. - SdkBytes encryptedData = response.ciphertextBlob(); - return encryptedData.asByteArray(); - - } catch (KmsException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - - return null; - } - - // Decrypt the data passed as a byte array. - private static byte[] decryptData(byte[] data, String keyId) { - - try { - KmsClient kmsClient = getKMSClient(); - SdkBytes encryptedData = SdkBytes.fromByteArray(data); - - DecryptRequest decryptRequest = DecryptRequest.builder() - .ciphertextBlob(encryptedData) - .keyId(keyId) - .build(); - - DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest); - SdkBytes plainText = decryptResponse.plaintext(); - return plainText.asByteArray(); - - } catch (KmsException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - - return null; - } - - // Return a byte array. - private static byte[] getObjectFile(String filePath) { - - FileInputStream fileInputStream = null; - byte[] bytesArray = null; - - try { - File file = new File(filePath); - bytesArray = new byte[(int) file.length()]; - - fileInputStream = new FileInputStream(file); - fileInputStream.read(bytesArray); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return bytesArray; - } - - // Return a KmsClient object. - private static KmsClient getKMSClient() { - - Region region = Region.US_EAST_1; - return KmsClient.builder() - .region(region) - .build(); - } -} -// snippet-end:[s3.java2.kms.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.kms.main] +// snippet-start:[s3.java2.kms.import] +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.kms.KmsClient; +import software.amazon.awssdk.services.kms.model.DecryptRequest; +import software.amazon.awssdk.services.kms.model.EncryptRequest; +import software.amazon.awssdk.services.kms.model.EncryptResponse; +import software.amazon.awssdk.services.kms.model.KmsException; +import software.amazon.awssdk.services.kms.model.DecryptResponse; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.io.IOException; +import java.io.FileInputStream; +// snippet-end:[s3.java2.kms.import] + +/** + * Before running this code example, you need to create a key by using the AWS + * Key Management Service. + * For information, see "Creating keys" in the AWS Key Management Service + * Developer Guide. + * + * In addition, before running this Java V2 code example, set up your + * development environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + */ + +public class KMSEncryptionExample { + + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + objectName - The name of the object.\s + bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s + objectPath - The path to a TXT file to encrypt and place into a Amazon S3 bucket (for example, C:/AWS/test.txt). + outPath - The path where a text file is written to after it's decrypted (for example, C:/AWS/testPlain.txt). + keyId - The id of the AWS KMS key to use to encrpt/decrypt the data. You can obtain the key ID value from the AWS Management Console. + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String objectName = args[0]; + String bucketName = args[1]; + String objectPath = args[2]; + String outPath = args[3]; + String keyId = args[4]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + putEncryptData(s3, objectName, bucketName, objectPath, keyId); + getEncryptedData(s3, bucketName, objectName, outPath, keyId); + s3.close(); + } + + // Encrypt data and place the encrypted data into an Amazon S3 bucket. + public static void putEncryptData(S3Client s3, String objectName, String bucketName, String objectPath, + String keyId) { + try { + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(objectName) + .build(); + + byte[] myData = getObjectFile(objectPath); + + // Encrypt the data by using the AWS Key Management Service. + byte[] encryptData = encryptData(keyId, myData); + s3.putObject(objectRequest, RequestBody.fromBytes(encryptData)); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + // Obtain the encrypted data, decrypt it, and write the data to a text file. + public static void getEncryptedData(S3Client s3, String bucketName, String objectName, String path, String keyId) { + try { + GetObjectRequest objectRequest = GetObjectRequest.builder() + .key(objectName) + .bucket(bucketName) + .build(); + + // Get the byte[] from the Amazon S3 bucket. + ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); + byte[] data = objectBytes.asByteArray(); + + // Decrypt the data by using the AWS Key Management Service. + byte[] unEncryptedData = decryptData(data, keyId); + + // Write the data to a local file. + File myFile = new File(path); + OutputStream os = new FileOutputStream(myFile); + os.write(unEncryptedData); + System.out.println("Successfully obtained and decrypted bytes from the Amazon S3 bucket"); + os.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // Encrypt the data passed as a byte array. + private static byte[] encryptData(String keyId, byte[] data) { + try { + KmsClient kmsClient = getKMSClient(); + SdkBytes myBytes = SdkBytes.fromByteArray(data); + + EncryptRequest encryptRequest = EncryptRequest.builder() + .keyId(keyId) + .plaintext(myBytes) + .build(); + + EncryptResponse response = kmsClient.encrypt(encryptRequest); + String algorithm = response.encryptionAlgorithm().toString(); + System.out.println("The encryption algorithm is " + algorithm); + + // Return the encrypted data. + SdkBytes encryptedData = response.ciphertextBlob(); + return encryptedData.asByteArray(); + + } catch (KmsException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + return null; + } + + // Decrypt the data passed as a byte array. + private static byte[] decryptData(byte[] data, String keyId) { + + try { + KmsClient kmsClient = getKMSClient(); + SdkBytes encryptedData = SdkBytes.fromByteArray(data); + + DecryptRequest decryptRequest = DecryptRequest.builder() + .ciphertextBlob(encryptedData) + .keyId(keyId) + .build(); + + DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest); + SdkBytes plainText = decryptResponse.plaintext(); + return plainText.asByteArray(); + + } catch (KmsException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + return null; + } + + // Return a byte array. + private static byte[] getObjectFile(String filePath) { + + FileInputStream fileInputStream = null; + byte[] bytesArray = null; + + try { + File file = new File(filePath); + bytesArray = new byte[(int) file.length()]; + + fileInputStream = new FileInputStream(file); + fileInputStream.read(bytesArray); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return bytesArray; + } + + // Return a KmsClient object. + private static KmsClient getKMSClient() { + + Region region = Region.US_EAST_1; + return KmsClient.builder() + .region(region) + .build(); + } +} +// snippet-end:[s3.java2.kms.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/LifecycleConfiguration.java similarity index 98% rename from javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/LifecycleConfiguration.java index 023923e4d84..65664c27839 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/LifecycleConfiguration.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/LifecycleConfiguration.java @@ -1,201 +1,201 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.manage_lifecycle.main] -// snippet-start:[s3.java2.manage_lifecycle.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter; -import software.amazon.awssdk.services.s3.model.Transition; -import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationRequest; -import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse; -import software.amazon.awssdk.services.s3.model.DeleteBucketLifecycleRequest; -import software.amazon.awssdk.services.s3.model.TransitionStorageClass; -import software.amazon.awssdk.services.s3.model.LifecycleRule; -import software.amazon.awssdk.services.s3.model.ExpirationStatus; -import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration; -import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.util.ArrayList; -import java.util.List; -// snippet-end:[s3.java2.manage_lifecycle.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class LifecycleConfiguration { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into. - accountId - The id of the account that owns the Amazon S3 bucket. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String accountId = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setLifecycleConfig(s3, bucketName, accountId); - getLifecycleConfig(s3, bucketName, accountId); - deleteLifecycleConfig(s3, bucketName, accountId); - System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration"); - s3.close(); - } - - public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - // Create a rule to archive objects with the "glacierobjects/" prefix to Amazon - // S3 Glacier. - LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() - .prefix("glacierobjects/") - .build(); - - Transition transition = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(0) - .build(); - - LifecycleRule rule1 = LifecycleRule.builder() - .id("Archive immediately rule") - .filter(ruleFilter) - .transitions(transition) - .status(ExpirationStatus.ENABLED) - .build(); - - // Create a second rule. - Transition transition2 = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(0) - .build(); - - List transitionList = new ArrayList<>(); - transitionList.add(transition2); - - LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder() - .prefix("glacierobjects/") - .build(); - - LifecycleRule rule2 = LifecycleRule.builder() - .id("Archive and then delete rule") - .filter(ruleFilter2) - .transitions(transitionList) - .status(ExpirationStatus.ENABLED) - .build(); - - // Add the LifecycleRule objects to an ArrayList. - ArrayList ruleList = new ArrayList<>(); - ruleList.add(rule1); - ruleList.add(rule2); - - BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() - .rules(ruleList) - .build(); - - PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest - .builder() - .bucket(bucketName) - .lifecycleConfiguration(lifecycleConfiguration) - .expectedBucketOwner(accountId) - .build(); - - s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // Retrieve the configuration and add a new rule. - public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest - .builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - - GetBucketLifecycleConfigurationResponse response = s3 - .getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest); - List newList = new ArrayList<>(); - List rules = response.rules(); - for (LifecycleRule rule : rules) { - newList.add(rule); - } - - // Add a new rule with both a prefix predicate and a tag predicate. - LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() - .prefix("YearlyDocuments/") - .build(); - - Transition transition = Transition.builder() - .storageClass(TransitionStorageClass.GLACIER) - .days(3650) - .build(); - - LifecycleRule rule1 = LifecycleRule.builder() - .id("NewRule") - .filter(ruleFilter) - .transitions(transition) - .status(ExpirationStatus.ENABLED) - .build(); - - // Add the new rule to the list. - newList.add(rule1); - BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() - .rules(newList) - .build(); - - PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest - .builder() - .bucket(bucketName) - .lifecycleConfiguration(lifecycleConfiguration) - .expectedBucketOwner(accountId) - .build(); - - s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // Delete the configuration from the Amazon S3 bucket. - public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) { - try { - DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest - .builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - - s3.deleteBucketLifecycle(deleteBucketLifecycleRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.manage_lifecycle.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.manage_lifecycle.main] +// snippet-start:[s3.java2.manage_lifecycle.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter; +import software.amazon.awssdk.services.s3.model.Transition; +import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationRequest; +import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse; +import software.amazon.awssdk.services.s3.model.DeleteBucketLifecycleRequest; +import software.amazon.awssdk.services.s3.model.TransitionStorageClass; +import software.amazon.awssdk.services.s3.model.LifecycleRule; +import software.amazon.awssdk.services.s3.model.ExpirationStatus; +import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration; +import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.util.ArrayList; +import java.util.List; +// snippet-end:[s3.java2.manage_lifecycle.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class LifecycleConfiguration { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into. + accountId - The id of the account that owns the Amazon S3 bucket. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String accountId = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setLifecycleConfig(s3, bucketName, accountId); + getLifecycleConfig(s3, bucketName, accountId); + deleteLifecycleConfig(s3, bucketName, accountId); + System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration"); + s3.close(); + } + + public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + // Create a rule to archive objects with the "glacierobjects/" prefix to Amazon + // S3 Glacier. + LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() + .prefix("glacierobjects/") + .build(); + + Transition transition = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(0) + .build(); + + LifecycleRule rule1 = LifecycleRule.builder() + .id("Archive immediately rule") + .filter(ruleFilter) + .transitions(transition) + .status(ExpirationStatus.ENABLED) + .build(); + + // Create a second rule. + Transition transition2 = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(0) + .build(); + + List transitionList = new ArrayList<>(); + transitionList.add(transition2); + + LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder() + .prefix("glacierobjects/") + .build(); + + LifecycleRule rule2 = LifecycleRule.builder() + .id("Archive and then delete rule") + .filter(ruleFilter2) + .transitions(transitionList) + .status(ExpirationStatus.ENABLED) + .build(); + + // Add the LifecycleRule objects to an ArrayList. + ArrayList ruleList = new ArrayList<>(); + ruleList.add(rule1); + ruleList.add(rule2); + + BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() + .rules(ruleList) + .build(); + + PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .lifecycleConfiguration(lifecycleConfiguration) + .expectedBucketOwner(accountId) + .build(); + + s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // Retrieve the configuration and add a new rule. + public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + GetBucketLifecycleConfigurationResponse response = s3 + .getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest); + List newList = new ArrayList<>(); + List rules = response.rules(); + for (LifecycleRule rule : rules) { + newList.add(rule); + } + + // Add a new rule with both a prefix predicate and a tag predicate. + LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder() + .prefix("YearlyDocuments/") + .build(); + + Transition transition = Transition.builder() + .storageClass(TransitionStorageClass.GLACIER) + .days(3650) + .build(); + + LifecycleRule rule1 = LifecycleRule.builder() + .id("NewRule") + .filter(ruleFilter) + .transitions(transition) + .status(ExpirationStatus.ENABLED) + .build(); + + // Add the new rule to the list. + newList.add(rule1); + BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder() + .rules(newList) + .build(); + + PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest + .builder() + .bucket(bucketName) + .lifecycleConfiguration(lifecycleConfiguration) + .expectedBucketOwner(accountId) + .build(); + + s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // Delete the configuration from the Amazon S3 bucket. + public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) { + try { + DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest + .builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + s3.deleteBucketLifecycle(deleteBucketLifecycleRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.manage_lifecycle.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListBuckets.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListBuckets.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/ListBuckets.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ListBuckets.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListMultipartUploads.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ListMultipartUploads.java index b6b84cc3342..0ca810ad817 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListMultipartUploads.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListMultipartUploads.java @@ -1,69 +1,69 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.list_multi_uploads.main] -// snippet-start:[s3.java2.list_multi_uploads.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest; -import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse; -import software.amazon.awssdk.services.s3.model.MultipartUpload; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.util.List; -// snippet-end:[s3.java2.list_multi_uploads.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class ListMultipartUploads { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The name of the Amazon S3 bucket where an in-progress multipart upload is occurring. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - listUploads(s3, bucketName); - s3.close(); - } - - public static void listUploads(S3Client s3, String bucketName) { - try { - ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder() - .bucket(bucketName) - .build(); - - ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest); - List uploads = response.uploads(); - for (MultipartUpload upload : uploads) { - System.out.println("Upload in progress: Key = \"" + upload.key() + "\", id = " + upload.uploadId()); - } - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.list_multi_uploads.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.list_multi_uploads.main] +// snippet-start:[s3.java2.list_multi_uploads.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest; +import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse; +import software.amazon.awssdk.services.s3.model.MultipartUpload; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.util.List; +// snippet-end:[s3.java2.list_multi_uploads.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class ListMultipartUploads { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The name of the Amazon S3 bucket where an in-progress multipart upload is occurring. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + listUploads(s3, bucketName); + s3.close(); + } + + public static void listUploads(S3Client s3, String bucketName) { + try { + ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder() + .bucket(bucketName) + .build(); + + ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest); + List uploads = response.uploads(); + for (MultipartUpload upload : uploads) { + System.out.println("Upload in progress: Key = \"" + upload.key() + "\", id = " + upload.uploadId()); + } + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.list_multi_uploads.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjects.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjects.java index b43802fada4..dcff1f915f9 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjects.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjects.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.list_objects.main] -// snippet-start:[s3.java2.list_objects.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListObjectsRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.S3Object; -import java.util.List; -// snippet-end:[s3.java2.list_objects.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class ListObjects { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - listBucketObjects(s3, bucketName); - s3.close(); - } - - public static void listBucketObjects(S3Client s3, String bucketName) { - try { - ListObjectsRequest listObjects = ListObjectsRequest - .builder() - .bucket(bucketName) - .build(); - - ListObjectsResponse res = s3.listObjects(listObjects); - List objects = res.contents(); - for (S3Object myValue : objects) { - System.out.print("\n The name of the key is " + myValue.key()); - System.out.print("\n The object is " + calKb(myValue.size()) + " KBs"); - System.out.print("\n The owner is " + myValue.owner()); - } - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // convert bytes to kbs. - private static long calKb(Long val) { - return val / 1024; - } -} -// snippet-end:[s3.java2.list_objects.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.list_objects.main] +// snippet-start:[s3.java2.list_objects.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListObjectsRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.S3Object; +import java.util.List; +// snippet-end:[s3.java2.list_objects.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class ListObjects { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + listBucketObjects(s3, bucketName); + s3.close(); + } + + public static void listBucketObjects(S3Client s3, String bucketName) { + try { + ListObjectsRequest listObjects = ListObjectsRequest + .builder() + .bucket(bucketName) + .build(); + + ListObjectsResponse res = s3.listObjects(listObjects); + List objects = res.contents(); + for (S3Object myValue : objects) { + System.out.print("\n The name of the key is " + myValue.key()); + System.out.print("\n The object is " + calKb(myValue.size()) + " KBs"); + System.out.print("\n The owner is " + myValue.owner()); + } + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // convert bytes to kbs. + private static long calKb(Long val) { + return val / 1024; + } +} +// snippet-end:[s3.java2.list_objects.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjectsPaginated.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjectsPaginated.java index a967fbf0076..77f181e44e8 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ListObjectsPaginated.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ListObjectsPaginated.java @@ -1,57 +1,57 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.list_objects.pag.main] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; - -public class ListObjectsPaginated { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - listBucketObjects(s3, bucketName); - s3.close(); - } - - public static void listBucketObjects(S3Client s3, String bucketName) { - try { - ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); - listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.list_objects.pag.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.list_objects.pag.main] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; + +public class ListObjectsPaginated { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + listBucketObjects(s3, bucketName); + s3.close(); + } + + public static void listBucketObjects(S3Client s3, String bucketName) { + try { + ListObjectsV2Request listReq = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); + listRes.stream() + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.list_objects.pag.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ManagingObjectTags.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ManagingObjectTags.java index 2977b43d359..31c90f2cde6 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/ManagingObjectTags.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ManagingObjectTags.java @@ -1,179 +1,179 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_object_manage_tags.import] -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.Tag; -import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest; -import software.amazon.awssdk.services.s3.model.Tagging; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest; -import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -// snippet-end:[s3.java2.s3_object_manage_tags.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class ManagingObjectTags { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket. - objectKey - The object that a tag is applied (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - String objectPath = args[2]; - System.out.println("Putting object " + objectKey + " into bucket " + bucketName); - System.out.println(" in bucket: " + bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - putS3ObjectTags(s3, bucketName, objectKey, objectPath); - updateObjectTags(s3, bucketName, objectKey); - s3.close(); - } - - // snippet-start:[s3.java2.s3_object_manage_tags.main] - public static void putS3ObjectTags(S3Client s3, String bucketName, String objectKey, String objectPath) { - try { - Tag tag1 = Tag.builder() - .key("Tag 1") - .value("This is tag 1") - .build(); - - Tag tag2 = Tag.builder() - .key("Tag 2") - .value("This is tag 2") - .build(); - - List tags = new ArrayList<>(); - tags.add(tag1); - tags.add(tag2); - - Tagging allTags = Tagging.builder() - .tagSet(tags) - .build(); - - PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .tagging(allTags) - .build(); - - s3.putObject(putOb, RequestBody.fromBytes(getObjectFile(objectPath))); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void updateObjectTags(S3Client s3, String bucketName, String objectKey) { - try { - GetObjectTaggingRequest taggingRequest = GetObjectTaggingRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); - - GetObjectTaggingResponse getTaggingRes = s3.getObjectTagging(taggingRequest); - List obTags = getTaggingRes.tagSet(); - for (Tag sinTag : obTags) { - System.out.println("The tag key is: " + sinTag.key()); - System.out.println("The tag value is: " + sinTag.value()); - } - - // Replace the object's tags with two new tags. - Tag tag3 = Tag.builder() - .key("Tag 3") - .value("This is tag 3") - .build(); - - Tag tag4 = Tag.builder() - .key("Tag 4") - .value("This is tag 4") - .build(); - - List tags = new ArrayList<>(); - tags.add(tag3); - tags.add(tag4); - - Tagging updatedTags = Tagging.builder() - .tagSet(tags) - .build(); - - PutObjectTaggingRequest taggingRequest1 = PutObjectTaggingRequest.builder() - .bucket(bucketName) - .key(objectKey) - .tagging(updatedTags) - .build(); - - s3.putObjectTagging(taggingRequest1); - GetObjectTaggingResponse getTaggingRes2 = s3.getObjectTagging(taggingRequest); - List modTags = getTaggingRes2.tagSet(); - for (Tag sinTag : modTags) { - System.out.println("The tag key is: " + sinTag.key()); - System.out.println("The tag value is: " + sinTag.value()); - } - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - // Return a byte array. - private static byte[] getObjectFile(String filePath) { - FileInputStream fileInputStream = null; - byte[] bytesArray = null; - - try { - File file = new File(filePath); - bytesArray = new byte[(int) file.length()]; - fileInputStream = new FileInputStream(file); - fileInputStream.read(bytesArray); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fileInputStream != null) { - try { - fileInputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return bytesArray; - } -} -// snippet-end:[s3.java2.s3_object_manage_tags.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_object_manage_tags.import] +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.Tag; +import software.amazon.awssdk.services.s3.model.PutObjectTaggingRequest; +import software.amazon.awssdk.services.s3.model.Tagging; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest; +import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +// snippet-end:[s3.java2.s3_object_manage_tags.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class ManagingObjectTags { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket. + objectKey - The object that a tag is applied (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + String objectPath = args[2]; + System.out.println("Putting object " + objectKey + " into bucket " + bucketName); + System.out.println(" in bucket: " + bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + putS3ObjectTags(s3, bucketName, objectKey, objectPath); + updateObjectTags(s3, bucketName, objectKey); + s3.close(); + } + + // snippet-start:[s3.java2.s3_object_manage_tags.main] + public static void putS3ObjectTags(S3Client s3, String bucketName, String objectKey, String objectPath) { + try { + Tag tag1 = Tag.builder() + .key("Tag 1") + .value("This is tag 1") + .build(); + + Tag tag2 = Tag.builder() + .key("Tag 2") + .value("This is tag 2") + .build(); + + List tags = new ArrayList<>(); + tags.add(tag1); + tags.add(tag2); + + Tagging allTags = Tagging.builder() + .tagSet(tags) + .build(); + + PutObjectRequest putOb = PutObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .tagging(allTags) + .build(); + + s3.putObject(putOb, RequestBody.fromBytes(getObjectFile(objectPath))); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void updateObjectTags(S3Client s3, String bucketName, String objectKey) { + try { + GetObjectTaggingRequest taggingRequest = GetObjectTaggingRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + GetObjectTaggingResponse getTaggingRes = s3.getObjectTagging(taggingRequest); + List obTags = getTaggingRes.tagSet(); + for (Tag sinTag : obTags) { + System.out.println("The tag key is: " + sinTag.key()); + System.out.println("The tag value is: " + sinTag.value()); + } + + // Replace the object's tags with two new tags. + Tag tag3 = Tag.builder() + .key("Tag 3") + .value("This is tag 3") + .build(); + + Tag tag4 = Tag.builder() + .key("Tag 4") + .value("This is tag 4") + .build(); + + List tags = new ArrayList<>(); + tags.add(tag3); + tags.add(tag4); + + Tagging updatedTags = Tagging.builder() + .tagSet(tags) + .build(); + + PutObjectTaggingRequest taggingRequest1 = PutObjectTaggingRequest.builder() + .bucket(bucketName) + .key(objectKey) + .tagging(updatedTags) + .build(); + + s3.putObjectTagging(taggingRequest1); + GetObjectTaggingResponse getTaggingRes2 = s3.getObjectTagging(taggingRequest); + List modTags = getTaggingRes2.tagSet(); + for (Tag sinTag : modTags) { + System.out.println("The tag key is: " + sinTag.key()); + System.out.println("The tag value is: " + sinTag.value()); + } + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + // Return a byte array. + private static byte[] getObjectFile(String filePath) { + FileInputStream fileInputStream = null; + byte[] bytesArray = null; + + try { + File file = new File(filePath); + bytesArray = new byte[(int) file.length()]; + fileInputStream = new FileInputStream(file); + fileInputStream.read(bytesArray); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return bytesArray; + } +} +// snippet-end:[s3.java2.s3_object_manage_tags.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/ParseUri.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/ParseUri.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/ParseUri.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PerformMultiPartUpload.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PresignedSwing.java similarity index 96% rename from javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PresignedSwing.java index 65b2a2642e0..fc1635a3daa 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PresignedSwing.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PresignedSwing.java @@ -1,65 +1,65 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -import javax.swing.JFrame; -import javax.swing.JButton; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -class Swing implements ActionListener { - JFrame frame = new JFrame(); - JButton button = new JButton("Get Presigned Amazon S3 Object"); - - Swing() { - prepareGUI(); - buttonProperties(); - } - - public void prepareGUI() { - frame.setTitle("My Window"); - frame.getContentPane().setLayout(null); - frame.setVisible(true); - frame.setBounds(200, 200, 400, 400); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - } - - public void buttonProperties() { - button.setBounds(130, 200, 200, 100); - frame.add(button); - button.addActionListener(this); - } - - @Override - public void actionPerformed(ActionEvent e) { - // Get a presigned PDF from an Amazon S3 bucket. - try { - URL url = new URL(""); - InputStream in; - in = url.openStream(); - FileOutputStream fos = new FileOutputStream("C:\\AWS\\allpeople.png"); - System.out.println("reading from resource and writing to file..."); - int length; - byte[] buffer = new byte[1024];// buffer for portion of data from connection - while ((length = in.read(buffer)) > -1) { - fos.write(buffer, 0, length); - } - fos.close(); - in.close(); - System.out.println("File downloaded"); - } catch (IOException ex) { - ex.printStackTrace(); - } - } -} - -public class PresignedSwing { - public static void main(String[] args) { - new Swing(); - } +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +import javax.swing.JFrame; +import javax.swing.JButton; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +class Swing implements ActionListener { + JFrame frame = new JFrame(); + JButton button = new JButton("Get Presigned Amazon S3 Object"); + + Swing() { + prepareGUI(); + buttonProperties(); + } + + public void prepareGUI() { + frame.setTitle("My Window"); + frame.getContentPane().setLayout(null); + frame.setVisible(true); + frame.setBounds(200, 200, 400, 400); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + + public void buttonProperties() { + button.setBounds(130, 200, 200, 100); + frame.add(button); + button.addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + // Get a presigned PDF from an Amazon S3 bucket. + try { + URL url = new URL(""); + InputStream in; + in = url.openStream(); + FileOutputStream fos = new FileOutputStream("C:\\AWS\\allpeople.png"); + System.out.println("reading from resource and writing to file..."); + int length; + byte[] buffer = new byte[1024];// buffer for portion of data from connection + while ((length = in.read(buffer)) > -1) { + fos.write(buffer, 0, length); + } + fos.close(); + in.close(); + System.out.println("File downloaded"); + } catch (IOException ex) { + ex.printStackTrace(); + } + } +} + +public class PresignedSwing { + public static void main(String[] args) { + new Swing(); + } } \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutBucketLogging.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PutBucketLogging.java index d52fcf1e4bf..54fa452e874 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketLogging.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutBucketLogging.java @@ -1,103 +1,103 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_put_log.main] -// snippet-start:[s3.java2.s3_put_log.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.GetBucketAclRequest; -import software.amazon.awssdk.services.s3.model.BucketLogsPermission; -import software.amazon.awssdk.services.s3.model.Grantee; -import software.amazon.awssdk.services.s3.model.LoggingEnabled; -import software.amazon.awssdk.services.s3.model.Type; -import software.amazon.awssdk.services.s3.model.BucketLoggingStatus; -import software.amazon.awssdk.services.s3.model.PutBucketLoggingRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.TargetGrant; -import java.util.ArrayList; -import java.util.List; -// snippet-end:[s3.java2.s3_put_log.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class PutBucketLogging { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to upload an object into. - targetBucket - The target bucket . - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String targetBucket = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setlogRequest(s3, bucketName, targetBucket); - s3.close(); - } - - public static void setlogRequest(S3Client s3, String bucketName, String targetBucket) { - try { - GetBucketAclRequest aclRequest = GetBucketAclRequest.builder() - .bucket(targetBucket) - .build(); - - s3.getBucketAcl(aclRequest); - Grantee grantee = Grantee.builder() - .type(Type.GROUP) - .uri("http://acs.amazonaws.com/groups/s3/LogDelivery") - .build(); - - TargetGrant targetGrant = TargetGrant.builder() - .grantee(grantee) - .permission(BucketLogsPermission.FULL_CONTROL) - .build(); - - List granteeList = new ArrayList<>(); - granteeList.add(targetGrant); - - LoggingEnabled loggingEnabled = LoggingEnabled.builder() - .targetBucket(targetBucket) - .targetGrants(granteeList) - .build(); - - BucketLoggingStatus loggingStatus = BucketLoggingStatus.builder() - .loggingEnabled(loggingEnabled) - .build(); - - PutBucketLoggingRequest loggingRequest = PutBucketLoggingRequest.builder() - .bucket(bucketName) - .expectedBucketOwner("814548047983") - .bucketLoggingStatus(loggingStatus) - .build(); - - s3.putBucketLogging(loggingRequest); - System.out.println("Enabling logging for the target bucket " + targetBucket); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.s3_put_log.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_put_log.main] +// snippet-start:[s3.java2.s3_put_log.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetBucketAclRequest; +import software.amazon.awssdk.services.s3.model.BucketLogsPermission; +import software.amazon.awssdk.services.s3.model.Grantee; +import software.amazon.awssdk.services.s3.model.LoggingEnabled; +import software.amazon.awssdk.services.s3.model.Type; +import software.amazon.awssdk.services.s3.model.BucketLoggingStatus; +import software.amazon.awssdk.services.s3.model.PutBucketLoggingRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.TargetGrant; +import java.util.ArrayList; +import java.util.List; +// snippet-end:[s3.java2.s3_put_log.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class PutBucketLogging { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to upload an object into. + targetBucket - The target bucket . + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String targetBucket = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setlogRequest(s3, bucketName, targetBucket); + s3.close(); + } + + public static void setlogRequest(S3Client s3, String bucketName, String targetBucket) { + try { + GetBucketAclRequest aclRequest = GetBucketAclRequest.builder() + .bucket(targetBucket) + .build(); + + s3.getBucketAcl(aclRequest); + Grantee grantee = Grantee.builder() + .type(Type.GROUP) + .uri("http://acs.amazonaws.com/groups/s3/LogDelivery") + .build(); + + TargetGrant targetGrant = TargetGrant.builder() + .grantee(grantee) + .permission(BucketLogsPermission.FULL_CONTROL) + .build(); + + List granteeList = new ArrayList<>(); + granteeList.add(targetGrant); + + LoggingEnabled loggingEnabled = LoggingEnabled.builder() + .targetBucket(targetBucket) + .targetGrants(granteeList) + .build(); + + BucketLoggingStatus loggingStatus = BucketLoggingStatus.builder() + .loggingEnabled(loggingEnabled) + .build(); + + PutBucketLoggingRequest loggingRequest = PutBucketLoggingRequest.builder() + .bucket(bucketName) + .expectedBucketOwner("814548047983") + .bucketLoggingStatus(loggingStatus) + .build(); + + s3.putBucketLogging(loggingRequest); + System.out.println("Enabling logging for the target bucket " + targetBucket); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.s3_put_log.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObject.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObject.java index a55e81965c1..c226f5fa677 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObject.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObject.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_object_upload.main] -// snippet-start:[s3.java2.s3_object_upload.import] -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.io.File; -import java.util.HashMap; -import java.util.Map; -// snippet-end:[s3.java2.s3_object_upload.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class PutObject { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to upload an object into. - objectKey - The object to upload (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - String objectPath = args[2]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - putS3Object(s3, bucketName, objectKey, objectPath); - s3.close(); - } - - // This example uses RequestBody.fromFile to avoid loading the whole file into - // memory. - public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { - try { - Map metadata = new HashMap<>(); - metadata.put("x-amz-meta-myVal", "test"); - PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .metadata(metadata) - .build(); - - s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); - System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_object_upload.main] +// snippet-start:[s3.java2.s3_object_upload.import] +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +// snippet-end:[s3.java2.s3_object_upload.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class PutObject { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to upload an object into. + objectKey - The object to upload (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + String objectPath = args[2]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + putS3Object(s3, bucketName, objectKey, objectPath); + s3.close(); + } + + // This example uses RequestBody.fromFile to avoid loading the whole file into + // memory. + public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { + try { + Map metadata = new HashMap<>(); + metadata.put("x-amz-meta-myVal", "test"); + PutObjectRequest putOb = PutObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .metadata(metadata) + .build(); + + s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); + System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} // snippet-end:[s3.java2.s3_object_upload.main] \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectMetadata.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectMetadata.java index 9b7de61188d..231d51e9693 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectMetadata.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectMetadata.java @@ -1,81 +1,81 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_object_upload.metadata.main] -// snippet-start:[s3.java2.s3_object_upload.metadata.import] -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.io.File; -import java.util.HashMap; -import java.util.Map; -// snippet-end:[s3.java2.s3_object_upload.metadata.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class PutObjectMetadata { - public static void main(String[] args) { - final String USAGE = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to upload an object into. - objectKey - The object to upload (for example, book.pdf). - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s - """; - - if (args.length != 3) { - System.out.println(USAGE); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - String objectPath = args[2]; - System.out.println("Putting object " + objectKey + " into bucket " + bucketName); - System.out.println(" in bucket: " + bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - putS3Object(s3, bucketName, objectKey, objectPath); - s3.close(); - } - - // This example uses RequestBody.fromFile to avoid loading the whole file into - // memory. - public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { - try { - Map metadata = new HashMap<>(); - metadata.put("author", "Mary Doe"); - metadata.put("version", "1.0.0.0"); - - PutObjectRequest putOb = PutObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .metadata(metadata) - .build(); - - s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); - System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); - - } catch (S3Exception e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_object_upload.metadata.main] +// snippet-start:[s3.java2.s3_object_upload.metadata.import] +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +// snippet-end:[s3.java2.s3_object_upload.metadata.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class PutObjectMetadata { + public static void main(String[] args) { + final String USAGE = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to upload an object into. + objectKey - The object to upload (for example, book.pdf). + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s + """; + + if (args.length != 3) { + System.out.println(USAGE); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + String objectPath = args[2]; + System.out.println("Putting object " + objectKey + " into bucket " + bucketName); + System.out.println(" in bucket: " + bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + putS3Object(s3, bucketName, objectKey, objectPath); + s3.close(); + } + + // This example uses RequestBody.fromFile to avoid loading the whole file into + // memory. + public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) { + try { + Map metadata = new HashMap<>(); + metadata.put("author", "Mary Doe"); + metadata.put("version", "1.0.0.0"); + + PutObjectRequest putOb = PutObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .metadata(metadata) + .build(); + + s3.putObject(putOb, RequestBody.fromFile(new File(objectPath))); + System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName); + + } catch (S3Exception e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } +} // snippet-end:[s3.java2.s3_object_upload.metadata.main] \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectRetention.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectRetention.java index 9ddfc8e0cac..36e4cfd7210 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/PutObjectRetention.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/PutObjectRetention.java @@ -1,85 +1,85 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.retention_object.main] -// snippet-start:[s3.java2.retention_object.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest; -import software.amazon.awssdk.services.s3.model.ObjectLockRetention; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneOffset; -// snippet-end:[s3.java2.retention_object.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class PutObjectRetention { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - key - The name of the object (for example, book.pdf).\s - bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String key = args[0]; - String bucketName = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setRentionPeriod(s3, key, bucketName); - s3.close(); - } - - public static void setRentionPeriod(S3Client s3, String key, String bucket) { - try { - LocalDate localDate = LocalDate.parse("2020-07-17"); - LocalDateTime localDateTime = localDate.atStartOfDay(); - Instant instant = localDateTime.toInstant(ZoneOffset.UTC); - - ObjectLockRetention lockRetention = ObjectLockRetention.builder() - .mode("COMPLIANCE") - .retainUntilDate(instant) - .build(); - - PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() - .bucket(bucket) - .key(key) - .bypassGovernanceRetention(true) - .retention(lockRetention) - .build(); - - // To set Retention on an object, the Amazon S3 bucket must support object - // locking, otherwise an exception is thrown. - s3.putObjectRetention(retentionRequest); - System.out.print("An object retention configuration was successfully placed on the object"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.retention_object.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.retention_object.main] +// snippet-start:[s3.java2.retention_object.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest; +import software.amazon.awssdk.services.s3.model.ObjectLockRetention; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +// snippet-end:[s3.java2.retention_object.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class PutObjectRetention { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + key - The name of the object (for example, book.pdf).\s + bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String key = args[0]; + String bucketName = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setRentionPeriod(s3, key, bucketName); + s3.close(); + } + + public static void setRentionPeriod(S3Client s3, String key, String bucket) { + try { + LocalDate localDate = LocalDate.parse("2020-07-17"); + LocalDateTime localDateTime = localDate.atStartOfDay(); + Instant instant = localDateTime.toInstant(ZoneOffset.UTC); + + ObjectLockRetention lockRetention = ObjectLockRetention.builder() + .mode("COMPLIANCE") + .retainUntilDate(instant) + .build(); + + PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() + .bucket(bucket) + .key(key) + .bypassGovernanceRetention(true) + .retention(lockRetention) + .build(); + + // To set Retention on an object, the Amazon S3 bucket must support object + // locking, otherwise an exception is thrown. + s3.putObjectRetention(retentionRequest); + System.out.print("An object retention configuration was successfully placed on the object"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.retention_object.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/RestoreObject.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/RestoreObject.java index 2116d2d0cea..56c02bc09b7 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/RestoreObject.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/RestoreObject.java @@ -1,79 +1,79 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.restore_object.main] -// snippet-start:[s3.java2.restore_object.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.RestoreRequest; -import software.amazon.awssdk.services.s3.model.GlacierJobParameters; -import software.amazon.awssdk.services.s3.model.RestoreObjectRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.Tier; -// snippet-end:[s3.java2.restore_object.import] - -/* - * For more information about restoring an object, see "Restoring an archived object" at - * https://docs.aws.amazon.com/AmazonS3/latest/userguide/restoring-objects.html - * - * Before running this Java V2 code example, set up your development environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class RestoreObject { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name of an object with a Storage class value of Glacier.\s - expectedBucketOwner - The account that owns the bucket (you can obtain this value from the AWS Management Console).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String keyName = args[1]; - String expectedBucketOwner = args[2]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - restoreS3Object(s3, bucketName, keyName, expectedBucketOwner); - s3.close(); - } - - public static void restoreS3Object(S3Client s3, String bucketName, String keyName, String expectedBucketOwner) { - try { - RestoreRequest restoreRequest = RestoreRequest.builder() - .days(10) - .glacierJobParameters(GlacierJobParameters.builder().tier(Tier.STANDARD).build()) - .build(); - - RestoreObjectRequest objectRequest = RestoreObjectRequest.builder() - .expectedBucketOwner(expectedBucketOwner) - .bucket(bucketName) - .key(keyName) - .restoreRequest(restoreRequest) - .build(); - - s3.restoreObject(objectRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.restore_object.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.restore_object.main] +// snippet-start:[s3.java2.restore_object.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.RestoreRequest; +import software.amazon.awssdk.services.s3.model.GlacierJobParameters; +import software.amazon.awssdk.services.s3.model.RestoreObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.Tier; +// snippet-end:[s3.java2.restore_object.import] + +/* + * For more information about restoring an object, see "Restoring an archived object" at + * https://docs.aws.amazon.com/AmazonS3/latest/userguide/restoring-objects.html + * + * Before running this Java V2 code example, set up your development environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class RestoreObject { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name of an object with a Storage class value of Glacier.\s + expectedBucketOwner - The account that owns the bucket (you can obtain this value from the AWS Management Console).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String keyName = args[1]; + String expectedBucketOwner = args[2]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + restoreS3Object(s3, bucketName, keyName, expectedBucketOwner); + s3.close(); + } + + public static void restoreS3Object(S3Client s3, String bucketName, String keyName, String expectedBucketOwner) { + try { + RestoreRequest restoreRequest = RestoreRequest.builder() + .days(10) + .glacierJobParameters(GlacierJobParameters.builder().tier(Tier.STANDARD).build()) + .build(); + + RestoreObjectRequest objectRequest = RestoreObjectRequest.builder() + .expectedBucketOwner(expectedBucketOwner) + .bucket(bucketName) + .key(keyName) + .restoreRequest(restoreRequest) + .build(); + + s3.restoreObject(objectRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.restore_object.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketDeletion.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketDeletion.java index 2b81958bdd1..430b47a906e 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketDeletion.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketDeletion.java @@ -1,83 +1,83 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.bucket_deletion.main] -// snippet-start:[s3.java2.s3_bucket_deletion.delete_objects] -// snippet-start:[s3.java2.bucket_deletion.import] -// snippet-start:[s3.java2.s3_bucket_ops.delete_bucket.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; -import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.S3Object; -// snippet-end:[s3.java2.s3_bucket_ops.delete_bucket.import] -// snippet-end:[s3.java2.bucket_deletion.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class S3BucketDeletion { - public static void main(String[] args) throws Exception { - final String usage = """ - - Usage: - - - Where: - bucket - The bucket to delete (for example, bucket1).\s - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucket = args[0]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - deleteObjectsInBucket(s3, bucket); - s3.close(); - } - - public static void deleteObjectsInBucket(S3Client s3, String bucket) { - try { - // To delete a bucket, all the objects in the bucket must be deleted first. - ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder() - .bucket(bucket) - .build(); - ListObjectsV2Response listObjectsV2Response; - - do { - listObjectsV2Response = s3.listObjectsV2(listObjectsV2Request); - for (S3Object s3Object : listObjectsV2Response.contents()) { - DeleteObjectRequest request = DeleteObjectRequest.builder() - .bucket(bucket) - .key(s3Object.key()) - .build(); - s3.deleteObject(request); - } - } while (listObjectsV2Response.isTruncated()); - DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucket).build(); - s3.deleteBucket(deleteBucketRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.s3_bucket_deletion.delete_objects] -// snippet-end:[s3.java2.bucket_deletion.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.bucket_deletion.main] +// snippet-start:[s3.java2.s3_bucket_deletion.delete_objects] +// snippet-start:[s3.java2.bucket_deletion.import] +// snippet-start:[s3.java2.s3_bucket_ops.delete_bucket.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.S3Object; +// snippet-end:[s3.java2.s3_bucket_ops.delete_bucket.import] +// snippet-end:[s3.java2.bucket_deletion.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class S3BucketDeletion { + public static void main(String[] args) throws Exception { + final String usage = """ + + Usage: + + + Where: + bucket - The bucket to delete (for example, bucket1).\s + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucket = args[0]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + deleteObjectsInBucket(s3, bucket); + s3.close(); + } + + public static void deleteObjectsInBucket(S3Client s3, String bucket) { + try { + // To delete a bucket, all the objects in the bucket must be deleted first. + ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder() + .bucket(bucket) + .build(); + ListObjectsV2Response listObjectsV2Response; + + do { + listObjectsV2Response = s3.listObjectsV2(listObjectsV2Request); + for (S3Object s3Object : listObjectsV2Response.contents()) { + DeleteObjectRequest request = DeleteObjectRequest.builder() + .bucket(bucket) + .key(s3Object.key()) + .build(); + s3.deleteObject(request); + } + } while (listObjectsV2Response.isTruncated()); + DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucket).build(); + s3.deleteBucket(deleteBucketRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.s3_bucket_deletion.delete_objects] +// snippet-end:[s3.java2.bucket_deletion.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketOps.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketOps.java index 637dfe93ff7..ef50f72ec4c 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3BucketOps.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3BucketOps.java @@ -1,89 +1,89 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_bucket_ops.create_bucket] -// snippet-start:[s3.java2.s3_bucket_ops.import] -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.CreateBucketRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.HeadBucketRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketResponse; -import software.amazon.awssdk.services.s3.model.ListBucketsRequest; -import software.amazon.awssdk.services.s3.model.ListBucketsResponse; -import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; -import software.amazon.awssdk.services.s3.waiters.S3Waiter; -// snippet-end:[s3.java2.s3_bucket_ops.import] -// snippet-start:[s3.java2.s3_bucket_ops.main] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class S3BucketOps { - public static void main(String[] args) { - // snippet-start:[s3.java2.s3_bucket_ops.region] - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - // snippet-end:[s3.java2.s3_bucket_ops.region] - String bucket = "bucket" + System.currentTimeMillis(); - System.out.println(bucket); - createBucket(s3, bucket); - performOperations(s3, bucket); - } - - // Create a bucket by using a S3Waiter object - public static void createBucket(S3Client s3Client, String bucketName) { - try { - S3Waiter s3Waiter = s3Client.waiter(); - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); - - s3Client.createBucket(bucketRequest); - HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); - - // Wait until the bucket is created and print out the response. - WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName + " is ready"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - // snippet-end:[s3.java2.s3_bucket_ops.create_bucket] - - public static void performOperations(S3Client s3, String bucket) { - // snippet-start:[s3.java2.s3_bucket_ops.list_bucket] - // List buckets - ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build(); - ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest); - listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name())); - // snippet-end:[s3.java2.s3_bucket_ops.list_bucket] - - // Delete empty bucket. - // snippet-start:[s3.java2.s3_bucket_ops.delete_bucket] - DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); - - s3.deleteBucket(deleteBucketRequest); - s3.close(); - // snippet-end:[s3.java2.s3_bucket_ops.delete_bucket] - } -} -// snippet-end:[s3.java2.s3_bucket_ops.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_bucket_ops.create_bucket] +// snippet-start:[s3.java2.s3_bucket_ops.import] +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketResponse; +import software.amazon.awssdk.services.s3.model.ListBucketsRequest; +import software.amazon.awssdk.services.s3.model.ListBucketsResponse; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.waiters.S3Waiter; +// snippet-end:[s3.java2.s3_bucket_ops.import] +// snippet-start:[s3.java2.s3_bucket_ops.main] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class S3BucketOps { + public static void main(String[] args) { + // snippet-start:[s3.java2.s3_bucket_ops.region] + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + // snippet-end:[s3.java2.s3_bucket_ops.region] + String bucket = "bucket" + System.currentTimeMillis(); + System.out.println(bucket); + createBucket(s3, bucket); + performOperations(s3, bucket); + } + + // Create a bucket by using a S3Waiter object + public static void createBucket(S3Client s3Client, String bucketName) { + try { + S3Waiter s3Waiter = s3Client.waiter(); + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .build(); + + s3Client.createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response. + WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println(bucketName + " is ready"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + // snippet-end:[s3.java2.s3_bucket_ops.create_bucket] + + public static void performOperations(S3Client s3, String bucket) { + // snippet-start:[s3.java2.s3_bucket_ops.list_bucket] + // List buckets + ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build(); + ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest); + listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name())); + // snippet-end:[s3.java2.s3_bucket_ops.list_bucket] + + // Delete empty bucket. + // snippet-start:[s3.java2.s3_bucket_ops.delete_bucket] + DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() + .bucket(bucket) + .build(); + + s3.deleteBucket(deleteBucketRequest); + s3.close(); + // snippet-end:[s3.java2.s3_bucket_ops.delete_bucket] + } +} +// snippet-end:[s3.java2.s3_bucket_ops.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Cors.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Cors.java index a88e1229f6e..43fd689d70e 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Cors.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Cors.java @@ -1,130 +1,130 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.cors.main] -// snippet-start:[s3.java2.cors.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import java.util.ArrayList; -import java.util.List; -import software.amazon.awssdk.services.s3.model.GetBucketCorsRequest; -import software.amazon.awssdk.services.s3.model.GetBucketCorsResponse; -import software.amazon.awssdk.services.s3.model.DeleteBucketCorsRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.CORSRule; -import software.amazon.awssdk.services.s3.model.CORSConfiguration; -import software.amazon.awssdk.services.s3.model.PutBucketCorsRequest; -// snippet-end:[s3.java2.cors.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class S3Cors { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to upload an object into. - accountId - The id of the account that owns the Amazon S3 bucket. - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String accountId = args[1]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setCorsInformation(s3, bucketName, accountId); - getBucketCorsInformation(s3, bucketName, accountId); - deleteBucketCorsInformation(s3, bucketName, accountId); - s3.close(); - } - - public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) { - try { - DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - - s3.deleteBucketCors(bucketCorsRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) { - try { - GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder() - .bucket(bucketName) - .expectedBucketOwner(accountId) - .build(); - - GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest); - List corsRules = corsResponse.corsRules(); - for (CORSRule rule : corsRules) { - System.out.println("allowOrigins: " + rule.allowedOrigins()); - System.out.println("AllowedMethod: " + rule.allowedMethods()); - } - - } catch (S3Exception e) { - - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void setCorsInformation(S3Client s3, String bucketName, String accountId) { - List allowMethods = new ArrayList<>(); - allowMethods.add("PUT"); - allowMethods.add("POST"); - allowMethods.add("DELETE"); - - List allowOrigins = new ArrayList<>(); - allowOrigins.add("http://example.com"); - try { - // Define CORS rules. - CORSRule corsRule = CORSRule.builder() - .allowedMethods(allowMethods) - .allowedOrigins(allowOrigins) - .build(); - - List corsRules = new ArrayList<>(); - corsRules.add(corsRule); - CORSConfiguration configuration = CORSConfiguration.builder() - .corsRules(corsRules) - .build(); - - PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder() - .bucket(bucketName) - .corsConfiguration(configuration) - .expectedBucketOwner(accountId) - .build(); - - s3.putBucketCors(putBucketCorsRequest); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.cors.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.cors.main] +// snippet-start:[s3.java2.cors.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import java.util.ArrayList; +import java.util.List; +import software.amazon.awssdk.services.s3.model.GetBucketCorsRequest; +import software.amazon.awssdk.services.s3.model.GetBucketCorsResponse; +import software.amazon.awssdk.services.s3.model.DeleteBucketCorsRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.CORSRule; +import software.amazon.awssdk.services.s3.model.CORSConfiguration; +import software.amazon.awssdk.services.s3.model.PutBucketCorsRequest; +// snippet-end:[s3.java2.cors.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class S3Cors { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to upload an object into. + accountId - The id of the account that owns the Amazon S3 bucket. + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String accountId = args[1]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setCorsInformation(s3, bucketName, accountId); + getBucketCorsInformation(s3, bucketName, accountId); + deleteBucketCorsInformation(s3, bucketName, accountId); + s3.close(); + } + + public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) { + try { + DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + s3.deleteBucketCors(bucketCorsRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) { + try { + GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder() + .bucket(bucketName) + .expectedBucketOwner(accountId) + .build(); + + GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest); + List corsRules = corsResponse.corsRules(); + for (CORSRule rule : corsRules) { + System.out.println("allowOrigins: " + rule.allowedOrigins()); + System.out.println("AllowedMethod: " + rule.allowedMethods()); + } + + } catch (S3Exception e) { + + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void setCorsInformation(S3Client s3, String bucketName, String accountId) { + List allowMethods = new ArrayList<>(); + allowMethods.add("PUT"); + allowMethods.add("POST"); + allowMethods.add("DELETE"); + + List allowOrigins = new ArrayList<>(); + allowOrigins.add("http://example.com"); + try { + // Define CORS rules. + CORSRule corsRule = CORSRule.builder() + .allowedMethods(allowMethods) + .allowedOrigins(allowOrigins) + .build(); + + List corsRules = new ArrayList<>(); + corsRules.add(corsRule); + CORSConfiguration configuration = CORSConfiguration.builder() + .corsRules(corsRules) + .build(); + + PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder() + .bucket(bucketName) + .corsConfiguration(configuration) + .expectedBucketOwner(accountId) + .build(); + + s3.putBucketCors(putBucketCorsRequest); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.cors.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Log.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Log.java index e45c7a79a67..e5531dbda11 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Log.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Log.java @@ -1,48 +1,48 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.logging.complete] -// snippet-start:[s3.java2.logging.import] -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListBucketsRequest; -import software.amazon.awssdk.services.s3.model.ListBucketsResponse; -// snippet-end:[s3.java2.logging.import] - -// snippet-start:[s3.java2.logging.main] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class S3Log { - private static final Logger logger = LogManager.getLogger(S3Log.class); - - public static void main(String[] args) { - System.out.println("testing logging setup for " + S3Log.class); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build(); - ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest); - listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name())); - - logger.info("logging level info"); - logger.debug("logging debug stuff"); - logger.warn("logging warning"); - logger.error("logging error"); - logger.fatal("logging fatal"); - } -} -// snippet-end:[s3.java2.logging.main] -// snippet-end:[s3.java2.logging.complete] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.logging.complete] +// snippet-start:[s3.java2.logging.import] +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.LogManager; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListBucketsRequest; +import software.amazon.awssdk.services.s3.model.ListBucketsResponse; +// snippet-end:[s3.java2.logging.import] + +// snippet-start:[s3.java2.logging.main] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class S3Log { + private static final Logger logger = LogManager.getLogger(S3Log.class); + + public static void main(String[] args) { + System.out.println("testing logging setup for " + S3Log.class); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build(); + ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest); + listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name())); + + logger.info("logging level info"); + logger.debug("logging debug stuff"); + logger.warn("logging warning"); + logger.error("logging error"); + logger.fatal("logging fatal"); + } +} +// snippet-end:[s3.java2.logging.main] +// snippet-end:[s3.java2.logging.complete] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3ObjectOperations.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3ObjectOperations.java index f0aef8893ed..d877463a5b6 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3ObjectOperations.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3ObjectOperations.java @@ -1,269 +1,269 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; -// snippet-start:[s3.java2.s3_object_operations.complete] - -// snippet-start:[s3.java2.s3_object_operations.import] -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.Random; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; -import software.amazon.awssdk.services.s3.model.S3Object; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; -import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; -import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; -import software.amazon.awssdk.services.s3.model.CreateBucketRequest; -import software.amazon.awssdk.services.s3.model.CompletedPart; -import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; -import software.amazon.awssdk.services.s3.model.UploadPartRequest; -import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; -import software.amazon.awssdk.services.s3.waiters.S3Waiter; -import software.amazon.awssdk.services.s3.model.HeadBucketRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketResponse; -// snippet-end:[s3.java2.s3_object_operations.import] - -// snippet-start:[s3.java2.s3_object_operations.main] - -/** - * To run this AWS code example, ensure that you have setup your development - * environment, including your AWS credentials. - * - * For information, see this documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class S3ObjectOperations { - private static S3Client s3; - - public static void main(String[] args) throws IOException { - final String USAGE = """ - - Usage: - - - Where: - bucketName - the Amazon S3 bucket to create. - key - the key to use. - """; - - if (args.length != 2) { - System.out.println(USAGE); - System.exit(1); - } - - String bucketName = args[0]; - String key = args[1]; - - // snippet-start:[s3.java2.s3_object_operations.upload] - Region region = Region.US_WEST_2; - s3 = S3Client.builder() - .region(region) - .build(); - - createBucket(s3, bucketName, region); - - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000))); - // snippet-end:[s3.java2.s3_object_operations.upload] - - // Multipart upload example - String multipartKey = "multiPartKey"; - multipartUpload(bucketName, multipartKey); - - // snippet-start:[s3.java2.s3_object_operations.pagination] - ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - boolean done = false; - while (!done) { - ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); - for (S3Object content : listObjResponse.contents()) { - System.out.println(content.key()); - } - - if (listObjResponse.nextContinuationToken() == null) { - done = true; - } - - listObjectsReqManual = listObjectsReqManual.toBuilder() - .continuationToken(listObjResponse.nextContinuationToken()) - .build(); - } - // snippet-end:[s3.java2.s3_object_operations.pagination] - // snippet-start:[s3.java2.s3_object_operations.iterative] - ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); - // Process response pages - listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out - .println(" Key: " + content.key() + " size = " + content.size())); - - // snippet-end:[s3.java2.s3_object_operations.iterative] - // snippet-start:[s3.java2.s3_object_operations.stream] - // Helper method to work with paginated collection of items directly. - listRes.contents().stream() - .forEach(content -> System.out - .println(" Key: " + content.key() + " size = " + content.size())); - - // snippet-end:[s3.java2.s3_object_operations.stream] - // snippet-start:[s3.java2.s3_object_operations.forloop] - for (S3Object content : listRes.contents()) { - System.out.println(" Key: " + content.key() + " size = " + content.size()); - } - // snippet-end:[s3.java2.s3_object_operations.forloop] - - // snippet-start:[s3.java2.s3_object_operations.download] - GetObjectRequest getObjectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.getObject(getObjectRequest); - // snippet-end:[s3.java2.s3_object_operations.download] - - // snippet-start:[s3.java2.s3_object_operations.delete] - DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.deleteObject(deleteObjectRequest); - // snippet-end:[s3.java2.s3_object_operations.delete] - - // Delete an object - deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(multipartKey) - .build(); - - s3.deleteObject(deleteObjectRequest); - deleteBucket(s3, bucketName); - System.out.println("Done"); - } - - // Create a bucket by using a S3Waiter object - public static void createBucket(S3Client s3Client, String bucketName, Region region) { - - S3Waiter s3Waiter = s3Client.waiter(); - - try { - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .createBucketConfiguration( - CreateBucketConfiguration.builder() - .locationConstraint(region.id()) - .build()) - .build(); - - s3Client.createBucket(bucketRequest); - HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); - - // Wait until the bucket is created and print out the response - WaiterResponse waiterResponse = s3Waiter - .waitUntilBucketExists(bucketRequestWait); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName + " is ready"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteBucket(S3Client client, String bucket) { - DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); - client.deleteBucket(deleteBucketRequest); - } - - /** - * Upload an object in parts - */ - private static void multipartUpload(String bucketName, String key) throws IOException { - - int mB = 1024 * 1024; - // snippet-start:[s3.java2.s3_object_operations.upload_multi_part] - // First create a multipart upload and get the upload id - CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); - String uploadId = response.uploadId(); - System.out.println(uploadId); - - // Upload all the different parts of the object - UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .partNumber(1).build(); - - String etag1 = s3 - .uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) - .eTag(); - - CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); - - UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) - .uploadId(uploadId) - .partNumber(2).build(); - String etag2 = s3 - .uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) - .eTag(); - CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); - - // Finally call completeMultipartUpload operation to tell S3 to merge all - // uploaded - // parts and finish the multipart operation. - CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() - .parts(part1, part2) - .build(); - - CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .multipartUpload(completedMultipartUpload) - .build(); - - s3.completeMultipartUpload(completeMultipartUploadRequest); - // snippet-end:[s3.java2.s3_object_operations.upload_multi_part] - } - - private static ByteBuffer getRandomByteBuffer(int size) throws IOException { - byte[] b = new byte[size]; - new Random().nextBytes(b); - return ByteBuffer.wrap(b); - } -} - -// snippet-end:[s3.java2.s3_object_operations.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; +// snippet-start:[s3.java2.s3_object_operations.complete] + +// snippet-start:[s3.java2.s3_object_operations.import] +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.Random; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; +import software.amazon.awssdk.services.s3.model.S3Object; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; +import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.CompletedPart; +import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; +import software.amazon.awssdk.services.s3.model.UploadPartRequest; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; +import software.amazon.awssdk.services.s3.waiters.S3Waiter; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketResponse; +// snippet-end:[s3.java2.s3_object_operations.import] + +// snippet-start:[s3.java2.s3_object_operations.main] + +/** + * To run this AWS code example, ensure that you have setup your development + * environment, including your AWS credentials. + * + * For information, see this documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class S3ObjectOperations { + private static S3Client s3; + + public static void main(String[] args) throws IOException { + final String USAGE = """ + + Usage: + + + Where: + bucketName - the Amazon S3 bucket to create. + key - the key to use. + """; + + if (args.length != 2) { + System.out.println(USAGE); + System.exit(1); + } + + String bucketName = args[0]; + String key = args[1]; + + // snippet-start:[s3.java2.s3_object_operations.upload] + Region region = Region.US_WEST_2; + s3 = S3Client.builder() + .region(region) + .build(); + + createBucket(s3, bucketName, region); + + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000))); + // snippet-end:[s3.java2.s3_object_operations.upload] + + // Multipart upload example + String multipartKey = "multiPartKey"; + multipartUpload(bucketName, multipartKey); + + // snippet-start:[s3.java2.s3_object_operations.pagination] + ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + boolean done = false; + while (!done) { + ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); + for (S3Object content : listObjResponse.contents()) { + System.out.println(content.key()); + } + + if (listObjResponse.nextContinuationToken() == null) { + done = true; + } + + listObjectsReqManual = listObjectsReqManual.toBuilder() + .continuationToken(listObjResponse.nextContinuationToken()) + .build(); + } + // snippet-end:[s3.java2.s3_object_operations.pagination] + // snippet-start:[s3.java2.s3_object_operations.iterative] + ListObjectsV2Request listReq = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); + // Process response pages + listRes.stream() + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out + .println(" Key: " + content.key() + " size = " + content.size())); + + // snippet-end:[s3.java2.s3_object_operations.iterative] + // snippet-start:[s3.java2.s3_object_operations.stream] + // Helper method to work with paginated collection of items directly. + listRes.contents().stream() + .forEach(content -> System.out + .println(" Key: " + content.key() + " size = " + content.size())); + + // snippet-end:[s3.java2.s3_object_operations.stream] + // snippet-start:[s3.java2.s3_object_operations.forloop] + for (S3Object content : listRes.contents()) { + System.out.println(" Key: " + content.key() + " size = " + content.size()); + } + // snippet-end:[s3.java2.s3_object_operations.forloop] + + // snippet-start:[s3.java2.s3_object_operations.download] + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.getObject(getObjectRequest); + // snippet-end:[s3.java2.s3_object_operations.download] + + // snippet-start:[s3.java2.s3_object_operations.delete] + DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.deleteObject(deleteObjectRequest); + // snippet-end:[s3.java2.s3_object_operations.delete] + + // Delete an object + deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(multipartKey) + .build(); + + s3.deleteObject(deleteObjectRequest); + deleteBucket(s3, bucketName); + System.out.println("Done"); + } + + // Create a bucket by using a S3Waiter object + public static void createBucket(S3Client s3Client, String bucketName, Region region) { + + S3Waiter s3Waiter = s3Client.waiter(); + + try { + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .createBucketConfiguration( + CreateBucketConfiguration.builder() + .locationConstraint(region.id()) + .build()) + .build(); + + s3Client.createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response + WaiterResponse waiterResponse = s3Waiter + .waitUntilBucketExists(bucketRequestWait); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println(bucketName + " is ready"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void deleteBucket(S3Client client, String bucket) { + DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() + .bucket(bucket) + .build(); + client.deleteBucket(deleteBucketRequest); + } + + /** + * Upload an object in parts + */ + private static void multipartUpload(String bucketName, String key) throws IOException { + + int mB = 1024 * 1024; + // snippet-start:[s3.java2.s3_object_operations.upload_multi_part] + // First create a multipart upload and get the upload id + CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); + String uploadId = response.uploadId(); + System.out.println(uploadId); + + // Upload all the different parts of the object + UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .partNumber(1).build(); + + String etag1 = s3 + .uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) + .eTag(); + + CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); + + UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) + .uploadId(uploadId) + .partNumber(2).build(); + String etag2 = s3 + .uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) + .eTag(); + CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); + + // Finally call completeMultipartUpload operation to tell S3 to merge all + // uploaded + // parts and finish the multipart operation. + CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() + .parts(part1, part2) + .build(); + + CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .multipartUpload(completedMultipartUpload) + .build(); + + s3.completeMultipartUpload(completeMultipartUploadRequest); + // snippet-end:[s3.java2.s3_object_operations.upload_multi_part] + } + + private static ByteBuffer getRandomByteBuffer(int size) throws IOException { + byte[] b = new byte[size]; + new Random().nextBytes(b); + return ByteBuffer.wrap(b); + } +} + +// snippet-end:[s3.java2.s3_object_operations.main] // snippet-end:[s3.java2.s3_object_operations.complete] \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Scenario.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Scenario.java index f6b3654d885..e4d2d327d07 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/S3Scenario.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3Scenario.java @@ -1,353 +1,353 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.s3_scenario.import] -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.net.URLEncoder; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Random; -import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.CreateBucketRequest; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; -import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; -import software.amazon.awssdk.core.sync.RequestBody; -import software.amazon.awssdk.services.s3.waiters.S3Waiter; -import software.amazon.awssdk.services.s3.model.UploadPartRequest; -import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketResponse; -import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; -import software.amazon.awssdk.services.s3.model.HeadBucketRequest; -import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; -import software.amazon.awssdk.services.s3.model.CompletedPart; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; -import software.amazon.awssdk.services.s3.model.S3Object; -import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; -import software.amazon.awssdk.services.s3.model.CopyObjectRequest; -import software.amazon.awssdk.services.s3.model.CopyObjectResponse; -// snippet-end:[s3.java2.s3_scenario.import] - -// snippet-start:[s3.java2.s3_scenario.main] -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - * This Java code example performs the following tasks: - * - * 1. Creates an Amazon S3 bucket. - * 2. Uploads an object to the bucket. - * 3. Downloads the object to another local file. - * 4. Uploads an object using multipart upload. - * 5. List all objects located in the Amazon S3 bucket. - * 6. Copies the object to another Amazon S3 bucket. - * 7. Deletes the object from the Amazon S3 bucket. - * 8. Deletes the Amazon S3 bucket. - */ - -public class S3Scenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - - public static void main(String[] args) throws IOException { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket to create. - key - The key to use. - objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). - savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf). - toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf).\s - """; - - if (args.length != 5) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String key = args[1]; - String objectPath = args[2]; - String savePath = args[3]; - String toBucket = args[4]; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - System.out.println(DASHES); - System.out.println("Welcome to the Amazon S3 example scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("1. Create an Amazon S3 bucket."); - createBucket(s3, bucketName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("2. Update a local file to the Amazon S3 bucket."); - uploadLocalFile(s3, bucketName, key, objectPath); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. Download the object to another local file."); - getObjectBytes(s3, bucketName, key, savePath); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Perform a multipart upload."); - String multipartKey = "multiPartKey"; - multipartUpload(s3, toBucket, multipartKey); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("5. List all objects located in the Amazon S3 bucket."); - listAllObjects(s3, bucketName); - anotherListExample(s3, bucketName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("6. Copy the object to another Amazon S3 bucket."); - copyBucketObject(s3, bucketName, key, toBucket); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("7. Delete the object from the Amazon S3 bucket."); - deleteObjectFromBucket(s3, bucketName, key); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("8. Delete the Amazon S3 bucket."); - deleteBucket(s3, bucketName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("All Amazon S3 operations were successfully performed"); - System.out.println(DASHES); - s3.close(); - } - - // Create a bucket by using a S3Waiter object. - public static void createBucket(S3Client s3Client, String bucketName) { - try { - S3Waiter s3Waiter = s3Client.waiter(); - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); - - s3Client.createBucket(bucketRequest); - HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() - .bucket(bucketName) - .build(); - - // Wait until the bucket is created and print out the response. - WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); - waiterResponse.matched().response().ifPresent(System.out::println); - System.out.println(bucketName + " is ready"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void deleteBucket(S3Client client, String bucket) { - DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() - .bucket(bucket) - .build(); - - client.deleteBucket(deleteBucketRequest); - System.out.println(bucket + " was deleted."); - } - - /** - * Upload an object in parts. - */ - public static void multipartUpload(S3Client s3, String bucketName, String key) { - int mB = 1024 * 1024; - // First create a multipart upload and get the upload id. - CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); - String uploadId = response.uploadId(); - System.out.println(uploadId); - - // Upload all the different parts of the object. - UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .partNumber(1).build(); - - String etag1 = s3.uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) - .eTag(); - CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); - - UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) - .uploadId(uploadId) - .partNumber(2).build(); - String etag2 = s3.uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) - .eTag(); - CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); - - // Call completeMultipartUpload operation to tell S3 to merge all uploaded - // parts and finish the multipart operation. - CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() - .parts(part1, part2) - .build(); - - CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() - .bucket(bucketName) - .key(key) - .uploadId(uploadId) - .multipartUpload(completedMultipartUpload) - .build(); - - s3.completeMultipartUpload(completeMultipartUploadRequest); - } - - private static ByteBuffer getRandomByteBuffer(int size) { - byte[] b = new byte[size]; - new Random().nextBytes(b); - return ByteBuffer.wrap(b); - } - - public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { - try { - GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); - - ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); - byte[] data = objectBytes.asByteArray(); - - // Write the data to a local file. - File myFile = new File(path); - OutputStream os = new FileOutputStream(myFile); - os.write(data); - System.out.println("Successfully obtained bytes from an S3 object"); - os.close(); - - } catch (IOException ex) { - ex.printStackTrace(); - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - public static void uploadLocalFile(S3Client s3, String bucketName, String key, String objectPath) { - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.putObject(objectRequest, RequestBody.fromFile(new File(objectPath))); - } - - public static void listAllObjects(S3Client s3, String bucketName) { - ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - boolean done = false; - while (!done) { - ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); - for (S3Object content : listObjResponse.contents()) { - System.out.println(content.key()); - } - - if (listObjResponse.nextContinuationToken() == null) { - done = true; - } - - listObjectsReqManual = listObjectsReqManual.toBuilder() - .continuationToken(listObjResponse.nextContinuationToken()) - .build(); - } - } - - public static void anotherListExample(S3Client s3, String bucketName) { - ListObjectsV2Request listReq = ListObjectsV2Request.builder() - .bucket(bucketName) - .maxKeys(1) - .build(); - - ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); - - // Process response pages. - listRes.stream() - .flatMap(r -> r.contents().stream()) - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); - - // Helper method to work with paginated collection of items directly. - listRes.contents().stream() - .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); - - for (S3Object content : listRes.contents()) { - System.out.println(" Key: " + content.key() + " size = " + content.size()); - } - } - - public static void deleteObjectFromBucket(S3Client s3, String bucketName, String key) { - DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - s3.deleteObject(deleteObjectRequest); - System.out.println(key + " was deleted"); - } - - public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { - String encodedUrl = null; - try { - encodedUrl = URLEncoder.encode(fromBucket + "/" + objectKey, StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - System.out.println("URL could not be encoded: " + e.getMessage()); - } - CopyObjectRequest copyReq = CopyObjectRequest.builder() - .copySource(encodedUrl) - .destinationBucket(toBucket) - .destinationKey(objectKey) - .build(); - - try { - CopyObjectResponse copyRes = s3.copyObject(copyReq); - System.out.println("The " + objectKey + " was copied to " + toBucket); - return copyRes.copyObjectResult().toString(); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - return ""; - } -} -// snippet-end:[s3.java2.s3_scenario.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.s3_scenario.import] +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.net.URLEncoder; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Random; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; +import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.waiters.S3Waiter; +import software.amazon.awssdk.services.s3.model.UploadPartRequest; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketResponse; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CompletedPart; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; +import software.amazon.awssdk.services.s3.model.S3Object; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.CopyObjectRequest; +import software.amazon.awssdk.services.s3.model.CopyObjectResponse; +// snippet-end:[s3.java2.s3_scenario.import] + +// snippet-start:[s3.java2.s3_scenario.main] +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * This Java code example performs the following tasks: + * + * 1. Creates an Amazon S3 bucket. + * 2. Uploads an object to the bucket. + * 3. Downloads the object to another local file. + * 4. Uploads an object using multipart upload. + * 5. List all objects located in the Amazon S3 bucket. + * 6. Copies the object to another Amazon S3 bucket. + * 7. Deletes the object from the Amazon S3 bucket. + * 8. Deletes the Amazon S3 bucket. + */ + +public class S3Scenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + public static void main(String[] args) throws IOException { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket to create. + key - The key to use. + objectPath - The path where the file is located (for example, C:/AWS/book2.pdf). + savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf). + toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf).\s + """; + + if (args.length != 5) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String key = args[1]; + String objectPath = args[2]; + String savePath = args[3]; + String toBucket = args[4]; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + System.out.println(DASHES); + System.out.println("Welcome to the Amazon S3 example scenario."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("1. Create an Amazon S3 bucket."); + createBucket(s3, bucketName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("2. Update a local file to the Amazon S3 bucket."); + uploadLocalFile(s3, bucketName, key, objectPath); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. Download the object to another local file."); + getObjectBytes(s3, bucketName, key, savePath); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Perform a multipart upload."); + String multipartKey = "multiPartKey"; + multipartUpload(s3, toBucket, multipartKey); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("5. List all objects located in the Amazon S3 bucket."); + listAllObjects(s3, bucketName); + anotherListExample(s3, bucketName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("6. Copy the object to another Amazon S3 bucket."); + copyBucketObject(s3, bucketName, key, toBucket); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("7. Delete the object from the Amazon S3 bucket."); + deleteObjectFromBucket(s3, bucketName, key); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("8. Delete the Amazon S3 bucket."); + deleteBucket(s3, bucketName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("All Amazon S3 operations were successfully performed"); + System.out.println(DASHES); + s3.close(); + } + + // Create a bucket by using a S3Waiter object. + public static void createBucket(S3Client s3Client, String bucketName) { + try { + S3Waiter s3Waiter = s3Client.waiter(); + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .build(); + + s3Client.createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response. + WaiterResponse waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); + waiterResponse.matched().response().ifPresent(System.out::println); + System.out.println(bucketName + " is ready"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void deleteBucket(S3Client client, String bucket) { + DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() + .bucket(bucket) + .build(); + + client.deleteBucket(deleteBucketRequest); + System.out.println(bucket + " was deleted."); + } + + /** + * Upload an object in parts. + */ + public static void multipartUpload(S3Client s3, String bucketName, String key) { + int mB = 1024 * 1024; + // First create a multipart upload and get the upload id. + CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + CreateMultipartUploadResponse response = s3.createMultipartUpload(createMultipartUploadRequest); + String uploadId = response.uploadId(); + System.out.println(uploadId); + + // Upload all the different parts of the object. + UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .partNumber(1).build(); + + String etag1 = s3.uploadPart(uploadPartRequest1, RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))) + .eTag(); + CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build(); + + UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder().bucket(bucketName).key(key) + .uploadId(uploadId) + .partNumber(2).build(); + String etag2 = s3.uploadPart(uploadPartRequest2, RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))) + .eTag(); + CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build(); + + // Call completeMultipartUpload operation to tell S3 to merge all uploaded + // parts and finish the multipart operation. + CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder() + .parts(part1, part2) + .build(); + + CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() + .bucket(bucketName) + .key(key) + .uploadId(uploadId) + .multipartUpload(completedMultipartUpload) + .build(); + + s3.completeMultipartUpload(completeMultipartUploadRequest); + } + + private static ByteBuffer getRandomByteBuffer(int size) { + byte[] b = new byte[size]; + new Random().nextBytes(b); + return ByteBuffer.wrap(b); + } + + public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { + try { + GetObjectRequest objectRequest = GetObjectRequest + .builder() + .key(keyName) + .bucket(bucketName) + .build(); + + ResponseBytes objectBytes = s3.getObjectAsBytes(objectRequest); + byte[] data = objectBytes.asByteArray(); + + // Write the data to a local file. + File myFile = new File(path); + OutputStream os = new FileOutputStream(myFile); + os.write(data); + System.out.println("Successfully obtained bytes from an S3 object"); + os.close(); + + } catch (IOException ex) { + ex.printStackTrace(); + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + public static void uploadLocalFile(S3Client s3, String bucketName, String key, String objectPath) { + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.putObject(objectRequest, RequestBody.fromFile(new File(objectPath))); + } + + public static void listAllObjects(S3Client s3, String bucketName) { + ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + boolean done = false; + while (!done) { + ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual); + for (S3Object content : listObjResponse.contents()) { + System.out.println(content.key()); + } + + if (listObjResponse.nextContinuationToken() == null) { + done = true; + } + + listObjectsReqManual = listObjectsReqManual.toBuilder() + .continuationToken(listObjResponse.nextContinuationToken()) + .build(); + } + } + + public static void anotherListExample(S3Client s3, String bucketName) { + ListObjectsV2Request listReq = ListObjectsV2Request.builder() + .bucket(bucketName) + .maxKeys(1) + .build(); + + ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq); + + // Process response pages. + listRes.stream() + .flatMap(r -> r.contents().stream()) + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + + // Helper method to work with paginated collection of items directly. + listRes.contents().stream() + .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size())); + + for (S3Object content : listRes.contents()) { + System.out.println(" Key: " + content.key() + " size = " + content.size()); + } + } + + public static void deleteObjectFromBucket(S3Client s3, String bucketName, String key) { + DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + s3.deleteObject(deleteObjectRequest); + System.out.println(key + " was deleted"); + } + + public static String copyBucketObject(S3Client s3, String fromBucket, String objectKey, String toBucket) { + String encodedUrl = null; + try { + encodedUrl = URLEncoder.encode(fromBucket + "/" + objectKey, StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + System.out.println("URL could not be encoded: " + e.getMessage()); + } + CopyObjectRequest copyReq = CopyObjectRequest.builder() + .copySource(encodedUrl) + .destinationBucket(toBucket) + .destinationKey(objectKey) + .build(); + + try { + CopyObjectResponse copyRes = s3.copyObject(copyReq); + System.out.println("The " + objectKey + " was copied to " + toBucket); + return copyRes.copyObjectResult().toString(); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + return ""; + } +} +// snippet-end:[s3.java2.s3_scenario.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/S3ZipExample.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/S3ZipExample.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/S3ZipExample.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetAcl.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/SetAcl.java index 4852b92ef3a..a847979b974 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetAcl.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetAcl.java @@ -1,89 +1,89 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.set_acl.main] -// snippet-start:[s3.java2.set_acl.import] -import java.util.ArrayList; -import java.util.List; -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.services.s3.model.Permission; -import software.amazon.awssdk.services.s3.model.Grant; -import software.amazon.awssdk.services.s3.model.AccessControlPolicy; -import software.amazon.awssdk.services.s3.model.Type; -import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -// snippet-end:[s3.java2.set_acl.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class SetAcl { - public static void main(String[] args) { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket to grant permissions on.\s - id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String id = args[1]; - System.out.format("Setting access \n"); - System.out.println(" in bucket: " + bucketName); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setBucketAcl(s3, bucketName, id); - System.out.println("Done!"); - s3.close(); - } - - public static void setBucketAcl(S3Client s3, String bucketName, String id) { - try { - Grant ownerGrant = Grant.builder() - .grantee(builder -> builder.id(id) - .type(Type.CANONICAL_USER)) - .permission(Permission.FULL_CONTROL) - .build(); - - List grantList2 = new ArrayList<>(); - grantList2.add(ownerGrant); - - AccessControlPolicy acl = AccessControlPolicy.builder() - .owner(builder -> builder.id(id)) - .grants(grantList2) - .build(); - - PutBucketAclRequest putAclReq = PutBucketAclRequest.builder() - .bucket(bucketName) - .accessControlPolicy(acl) - .build(); - - s3.putBucketAcl(putAclReq); - - } catch (S3Exception e) { - e.printStackTrace(); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.set_acl.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.set_acl.main] +// snippet-start:[s3.java2.set_acl.import] +import java.util.ArrayList; +import java.util.List; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.services.s3.model.Permission; +import software.amazon.awssdk.services.s3.model.Grant; +import software.amazon.awssdk.services.s3.model.AccessControlPolicy; +import software.amazon.awssdk.services.s3.model.Type; +import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +// snippet-end:[s3.java2.set_acl.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class SetAcl { + public static void main(String[] args) { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket to grant permissions on.\s + id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String id = args[1]; + System.out.format("Setting access \n"); + System.out.println(" in bucket: " + bucketName); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setBucketAcl(s3, bucketName, id); + System.out.println("Done!"); + s3.close(); + } + + public static void setBucketAcl(S3Client s3, String bucketName, String id) { + try { + Grant ownerGrant = Grant.builder() + .grantee(builder -> builder.id(id) + .type(Type.CANONICAL_USER)) + .permission(Permission.FULL_CONTROL) + .build(); + + List grantList2 = new ArrayList<>(); + grantList2.add(ownerGrant); + + AccessControlPolicy acl = AccessControlPolicy.builder() + .owner(builder -> builder.id(id)) + .grants(grantList2) + .build(); + + PutBucketAclRequest putAclReq = PutBucketAclRequest.builder() + .bucket(bucketName) + .accessControlPolicy(acl) + .build(); + + s3.putBucketAcl(putAclReq); + + } catch (S3Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.set_acl.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/SetBucketEventBridgeNotification.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetBucketPolicy.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/SetBucketPolicy.java index 57b226be63f..06cecf0316b 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetBucketPolicy.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetBucketPolicy.java @@ -1,107 +1,107 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.set_bucket_policy.main] -// snippet-start:[s3.java2.set_bucket_policy.import] -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.ObjectMapper; -// snippet-end:[s3.java2.set_bucket_policy.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class SetBucketPolicy { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket to set the policy on. - polFile - A JSON file containing the policy (see the Amazon S3 Readme for an example).\s - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String polFile = args[1]; - String policyText = getBucketPolicyFromFile(polFile); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setPolicy(s3, bucketName, policyText); - s3.close(); - } - - public static void setPolicy(S3Client s3, String bucketName, String policyText) { - System.out.println("Setting policy:"); - System.out.println("----"); - System.out.println(policyText); - System.out.println("----"); - System.out.format("On Amazon S3 bucket: \"%s\"\n", bucketName); - - try { - PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder() - .bucket(bucketName) - .policy(policyText) - .build(); - - s3.putBucketPolicy(policyReq); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - - System.out.println("Done!"); - } - - // Loads a JSON-formatted policy from a file - public static String getBucketPolicyFromFile(String policyFile) { - - StringBuilder fileText = new StringBuilder(); - try { - List lines = Files.readAllLines(Paths.get(policyFile), StandardCharsets.UTF_8); - for (String line : lines) { - fileText.append(line); - } - - } catch (IOException e) { - System.out.format("Problem reading file: \"%s\"", policyFile); - System.out.println(e.getMessage()); - } - - try { - final JsonParser parser = new ObjectMapper().getFactory().createParser(fileText.toString()); - while (parser.nextToken() != null) { - } - - } catch (IOException jpe) { - jpe.printStackTrace(); - } - return fileText.toString(); - } -} -// snippet-end:[s3.java2.set_bucket_policy.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.set_bucket_policy.main] +// snippet-start:[s3.java2.set_bucket_policy.import] +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.ObjectMapper; +// snippet-end:[s3.java2.set_bucket_policy.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class SetBucketPolicy { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket to set the policy on. + polFile - A JSON file containing the policy (see the Amazon S3 Readme for an example).\s + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String polFile = args[1]; + String policyText = getBucketPolicyFromFile(polFile); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setPolicy(s3, bucketName, policyText); + s3.close(); + } + + public static void setPolicy(S3Client s3, String bucketName, String policyText) { + System.out.println("Setting policy:"); + System.out.println("----"); + System.out.println(policyText); + System.out.println("----"); + System.out.format("On Amazon S3 bucket: \"%s\"\n", bucketName); + + try { + PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder() + .bucket(bucketName) + .policy(policyText) + .build(); + + s3.putBucketPolicy(policyReq); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + + System.out.println("Done!"); + } + + // Loads a JSON-formatted policy from a file + public static String getBucketPolicyFromFile(String policyFile) { + + StringBuilder fileText = new StringBuilder(); + try { + List lines = Files.readAllLines(Paths.get(policyFile), StandardCharsets.UTF_8); + for (String line : lines) { + fileText.append(line); + } + + } catch (IOException e) { + System.out.format("Problem reading file: \"%s\"", policyFile); + System.out.println(e.getMessage()); + } + + try { + final JsonParser parser = new ObjectMapper().getFactory().createParser(fileText.toString()); + while (parser.nextToken() != null) { + } + + } catch (IOException jpe) { + jpe.printStackTrace(); + } + return fileText.toString(); + } +} +// snippet-end:[s3.java2.set_bucket_policy.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java index 16365530660..5513530017f 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/SetWebsiteConfiguration.java @@ -1,73 +1,73 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.set_website_configuration.main] -// snippet-start:[s3.java2.set_website_configuration.import] -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.IndexDocument; -import software.amazon.awssdk.services.s3.model.PutBucketWebsiteRequest; -import software.amazon.awssdk.services.s3.model.WebsiteConfiguration; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.regions.Region; -// snippet-end:[s3.java2.set_website_configuration.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class SetWebsiteConfiguration { - public static void main(String[] args) { - final String usage = """ - - Usage: [indexdoc]\s - - Where: - bucketName - The Amazon S3 bucket to set the website configuration on.\s - indexdoc - The index document, ex. 'index.html' - If not specified, 'index.html' will be set. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String indexDoc = "index.html"; - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .region(region) - .build(); - - setWebsiteConfig(s3, bucketName, indexDoc); - s3.close(); - } - - public static void setWebsiteConfig(S3Client s3, String bucketName, String indexDoc) { - try { - WebsiteConfiguration websiteConfig = WebsiteConfiguration.builder() - .indexDocument(IndexDocument.builder().suffix(indexDoc).build()) - .build(); - - PutBucketWebsiteRequest pubWebsiteReq = PutBucketWebsiteRequest.builder() - .bucket(bucketName) - .websiteConfiguration(websiteConfig) - .build(); - - s3.putBucketWebsite(pubWebsiteReq); - System.out.println("The call was successful"); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.set_website_configuration.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.set_website_configuration.main] +// snippet-start:[s3.java2.set_website_configuration.import] +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.IndexDocument; +import software.amazon.awssdk.services.s3.model.PutBucketWebsiteRequest; +import software.amazon.awssdk.services.s3.model.WebsiteConfiguration; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.regions.Region; +// snippet-end:[s3.java2.set_website_configuration.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class SetWebsiteConfiguration { + public static void main(String[] args) { + final String usage = """ + + Usage: [indexdoc]\s + + Where: + bucketName - The Amazon S3 bucket to set the website configuration on.\s + indexdoc - The index document, ex. 'index.html' + If not specified, 'index.html' will be set. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String indexDoc = "index.html"; + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .region(region) + .build(); + + setWebsiteConfig(s3, bucketName, indexDoc); + s3.close(); + } + + public static void setWebsiteConfig(S3Client s3, String bucketName, String indexDoc) { + try { + WebsiteConfiguration websiteConfig = WebsiteConfiguration.builder() + .indexDocument(IndexDocument.builder().suffix(indexDoc).build()) + .build(); + + PutBucketWebsiteRequest pubWebsiteReq = PutBucketWebsiteRequest.builder() + .bucket(bucketName) + .websiteConfiguration(websiteConfig) + .build(); + + s3.putBucketWebsite(pubWebsiteReq); + System.out.println("The call was successful"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.set_website_configuration.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCCreateJob.java similarity index 98% rename from javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCCreateJob.java index e7e20461fa7..2db27dd47d6 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/VPCCreateJob.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCCreateJob.java @@ -1,142 +1,142 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.create_job.vpc.main] -// snippet-start:[s3.java2.create_job.vpc.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3control.S3ControlClient; -import software.amazon.awssdk.services.s3control.model.S3SetObjectTaggingOperation; -import software.amazon.awssdk.services.s3control.model.JobOperation; -import software.amazon.awssdk.services.s3control.model.S3Tag; -import software.amazon.awssdk.services.s3control.model.JobManifestLocation; -import software.amazon.awssdk.services.s3control.model.JobManifestSpec; -import software.amazon.awssdk.services.s3control.model.JobManifest; -import software.amazon.awssdk.services.s3control.model.JobManifestFormat; -import software.amazon.awssdk.services.s3control.model.JobReport; -import software.amazon.awssdk.services.s3control.model.JobReportFormat; -import software.amazon.awssdk.services.s3control.model.CreateJobRequest; -import software.amazon.awssdk.services.s3control.model.S3ControlException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -// snippet-end:[s3.java2.create_job.vpc.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class VPCCreateJob { - public static void main(String[] args) throws URISyntaxException { - final String usage = """ - - Usage: - - - Where: - accountId - The account id value that owns the Amazon S3 bucket. - - iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. - manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). - reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). - tagKey - The key used for a tag (for example, keyOne). - tagValue - The value for the key (for example, ValueOne). - eTag - The ETag for the specified manifest object (for example, 000000c9d1046e73f7dde5043ac3ae85). - vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpce-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com) - """; - - if (args.length != 8) { - System.out.println(usage); - System.exit(1); - } - - String accountId = args[0]; - String iamRoleArn = args[1]; - String manifestLocation = args[2]; - String reportBucketName = args[3]; - String tagKey = args[4]; - String tagValue = args[5]; - String eTag = args[6]; - String vpcBucketURL = args[7]; - String uuid = java.util.UUID.randomUUID().toString(); - URI myURI = new URI(vpcBucketURL); - S3ControlClient s3ControlClient = S3ControlClient.builder() - .region(Region.US_EAST_1) - .endpointOverride(myURI) - .build(); - - createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, tagKey, - tagValue, eTag, - uuid); - s3ControlClient.close(); - } - - public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, - String manifestLocation, String reportBucketName, String tagKey, String tagValue, String eTag, - String uuid) { - try { - ArrayList tagSet = new ArrayList<>(); - S3Tag s3Tag = S3Tag.builder() - .key(tagKey) - .value(tagValue) - .build(); - - tagSet.add(s3Tag); - S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() - .tagSet(tagSet) - .build(); - - JobOperation jobOperation = JobOperation.builder() - .s3PutObjectTagging(objectTaggingOperation) - .build(); - - JobManifestLocation jobManifestLocation = JobManifestLocation.builder() - .objectArn(manifestLocation) - .eTag(eTag) - .build(); - - JobManifestSpec manifestSpec = JobManifestSpec.builder() - .fieldsWithStrings(new String[] { "Bucket", "Key" }) - .format(JobManifestFormat.S3_BATCH_OPERATIONS_CSV_20180820) - .build(); - - JobManifest jobManifest = JobManifest.builder() - .spec(manifestSpec) - .location(jobManifestLocation) - .build(); - - JobReport jobReport = JobReport.builder() - .bucket(reportBucketName) - .prefix("reports") - .format(JobReportFormat.REPORT_CSV_20180820) - .enabled(true) - .reportScope("AllTasks") - .build(); - - CreateJobRequest jobRequest = CreateJobRequest.builder() - .accountId(accountId) - .description("Job created using the AWS Java SDK") - .manifest(jobManifest) - .operation(jobOperation) - .report(jobReport) - .priority(42) - .roleArn(iamRoleArn) - .clientRequestToken(uuid) - .confirmationRequired(false) - .build(); - - s3ControlClient.createJob(jobRequest); - - } catch (S3ControlException e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} -// snippet-end:[s3.java2.create_job.vpc.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.create_job.vpc.main] +// snippet-start:[s3.java2.create_job.vpc.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3control.S3ControlClient; +import software.amazon.awssdk.services.s3control.model.S3SetObjectTaggingOperation; +import software.amazon.awssdk.services.s3control.model.JobOperation; +import software.amazon.awssdk.services.s3control.model.S3Tag; +import software.amazon.awssdk.services.s3control.model.JobManifestLocation; +import software.amazon.awssdk.services.s3control.model.JobManifestSpec; +import software.amazon.awssdk.services.s3control.model.JobManifest; +import software.amazon.awssdk.services.s3control.model.JobManifestFormat; +import software.amazon.awssdk.services.s3control.model.JobReport; +import software.amazon.awssdk.services.s3control.model.JobReportFormat; +import software.amazon.awssdk.services.s3control.model.CreateJobRequest; +import software.amazon.awssdk.services.s3control.model.S3ControlException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +// snippet-end:[s3.java2.create_job.vpc.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class VPCCreateJob { + public static void main(String[] args) throws URISyntaxException { + final String usage = """ + + Usage: + + + Where: + accountId - The account id value that owns the Amazon S3 bucket. + + iamRoleArn - The ARN of the AWS Identity and Access Management (IAM) role that has permissions to create a batch job. + manifestLocation - The location where the manaifest file required for the job (for example, arn:aws:s3:::/manifest.csv). + reportBucketName - The Amazon S3 bucket where the report is written to (for example, arn:aws:s3:::). + tagKey - The key used for a tag (for example, keyOne). + tagValue - The value for the key (for example, ValueOne). + eTag - The ETag for the specified manifest object (for example, 000000c9d1046e73f7dde5043ac3ae85). + vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpce-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com) + """; + + if (args.length != 8) { + System.out.println(usage); + System.exit(1); + } + + String accountId = args[0]; + String iamRoleArn = args[1]; + String manifestLocation = args[2]; + String reportBucketName = args[3]; + String tagKey = args[4]; + String tagValue = args[5]; + String eTag = args[6]; + String vpcBucketURL = args[7]; + String uuid = java.util.UUID.randomUUID().toString(); + URI myURI = new URI(vpcBucketURL); + S3ControlClient s3ControlClient = S3ControlClient.builder() + .region(Region.US_EAST_1) + .endpointOverride(myURI) + .build(); + + createS3Job(s3ControlClient, accountId, iamRoleArn, manifestLocation, reportBucketName, tagKey, + tagValue, eTag, + uuid); + s3ControlClient.close(); + } + + public static void createS3Job(S3ControlClient s3ControlClient, String accountId, String iamRoleArn, + String manifestLocation, String reportBucketName, String tagKey, String tagValue, String eTag, + String uuid) { + try { + ArrayList tagSet = new ArrayList<>(); + S3Tag s3Tag = S3Tag.builder() + .key(tagKey) + .value(tagValue) + .build(); + + tagSet.add(s3Tag); + S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder() + .tagSet(tagSet) + .build(); + + JobOperation jobOperation = JobOperation.builder() + .s3PutObjectTagging(objectTaggingOperation) + .build(); + + JobManifestLocation jobManifestLocation = JobManifestLocation.builder() + .objectArn(manifestLocation) + .eTag(eTag) + .build(); + + JobManifestSpec manifestSpec = JobManifestSpec.builder() + .fieldsWithStrings(new String[] { "Bucket", "Key" }) + .format(JobManifestFormat.S3_BATCH_OPERATIONS_CSV_20180820) + .build(); + + JobManifest jobManifest = JobManifest.builder() + .spec(manifestSpec) + .location(jobManifestLocation) + .build(); + + JobReport jobReport = JobReport.builder() + .bucket(reportBucketName) + .prefix("reports") + .format(JobReportFormat.REPORT_CSV_20180820) + .enabled(true) + .reportScope("AllTasks") + .build(); + + CreateJobRequest jobRequest = CreateJobRequest.builder() + .accountId(accountId) + .description("Job created using the AWS Java SDK") + .manifest(jobManifest) + .operation(jobOperation) + .report(jobReport) + .priority(42) + .roleArn(iamRoleArn) + .clientRequestToken(uuid) + .confirmationRequired(false) + .build(); + + s3ControlClient.createJob(jobRequest); + + } catch (S3ControlException e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} +// snippet-end:[s3.java2.create_job.vpc.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCS3Example.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCS3Example.java index 8237fd88817..a8eec411ef5 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/VPCS3Example.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/VPCS3Example.java @@ -1,83 +1,83 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3; - -// snippet-start:[s3.java2.vpc.example.main] -// snippet-start:[s3.java2.vpc.example.import] -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; -import software.amazon.awssdk.services.s3.model.ListObjectsRequest; -import software.amazon.awssdk.services.s3.model.ListObjectsResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import software.amazon.awssdk.services.s3.model.S3Object; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -// snippet-end:[s3.java2.vpc.example.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class VPCS3Example { - public static void main(String[] args) throws URISyntaxException { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The Amazon S3 bucket from which objects are read.\s - vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpxx-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com - """; - - if (args.length != 2) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String vpcBucketURL = args[1]; - URI myURI = new URI(vpcBucketURL); - Region region = Region.US_EAST_1; - S3Client s3 = S3Client.builder() - .endpointOverride(myURI) - .region(region) - .build(); - - listBucketObjects(s3, bucketName); - s3.close(); - } - - public static void listBucketObjects(S3Client s3, String bucketName) { - try { - ListObjectsRequest listObjects = ListObjectsRequest.builder() - .bucket(bucketName) - .build(); - - ListObjectsResponse res = s3.listObjects(listObjects); - List objects = res.contents(); - for (S3Object s3Object : objects) { - System.out.print("\n The name of the key is " + s3Object.key()); - System.out.print("\n The object is " + convertBToKb(s3Object.size()) + " KBs"); - System.out.print("\n The owner is " + s3Object.owner()); - } - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } - - // convert bytes to kbs. - private static long convertBToKb(Long val) { - return val / 1024; - } -} -// snippet-end:[s3.java2.vpc.example.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3; + +// snippet-start:[s3.java2.vpc.example.main] +// snippet-start:[s3.java2.vpc.example.import] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ListObjectsRequest; +import software.amazon.awssdk.services.s3.model.ListObjectsResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.S3Object; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +// snippet-end:[s3.java2.vpc.example.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class VPCS3Example { + public static void main(String[] args) throws URISyntaxException { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The Amazon S3 bucket from which objects are read.\s + vpcBucketURL - The URL of the bucket located in your virtual private cloud (VPC) (for example, https://bucket.vpxx-xxxxxc4d-5e6f.s3.us-east-1.vpce.amazonaws.com + """; + + if (args.length != 2) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String vpcBucketURL = args[1]; + URI myURI = new URI(vpcBucketURL); + Region region = Region.US_EAST_1; + S3Client s3 = S3Client.builder() + .endpointOverride(myURI) + .region(region) + .build(); + + listBucketObjects(s3, bucketName); + s3.close(); + } + + public static void listBucketObjects(S3Client s3, String bucketName) { + try { + ListObjectsRequest listObjects = ListObjectsRequest.builder() + .bucket(bucketName) + .build(); + + ListObjectsResponse res = s3.listObjects(listObjects); + List objects = res.contents(); + for (S3Object s3Object : objects) { + System.out.print("\n The name of the key is " + s3Object.key()); + System.out.print("\n The object is " + convertBToKb(s3Object.size()) + " KBs"); + System.out.print("\n The owner is " + s3Object.owner()); + } + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } + + // convert bytes to kbs. + private static long convertBToKb(Long val) { + return val / 1024; + } +} +// snippet-end:[s3.java2.vpc.example.main] diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java index b36305d8b4c..d60839df8e2 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/CreateBucketAsync.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3.async; - -import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3AsyncClient; -import software.amazon.awssdk.services.s3.model.CreateBucketRequest; -import software.amazon.awssdk.services.s3.model.CreateBucketResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.net.URISyntaxException; -import java.util.concurrent.CompletableFuture; - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ -public class CreateBucketAsync { - - public static void main(String[] args) throws URISyntaxException { - final String usage = """ - - Usage: - \s - - Where: - bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - System.out.format("Creating a bucket named %s\n", - bucketName); - - Region region = Region.US_EAST_1; - S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); - - createBucket(s3AsyncClient, bucketName); - } - - public static void createBucket(S3AsyncClient s3AsyncClient, String bucketName) { - try { - CreateBucketRequest bucketRequest = CreateBucketRequest.builder() - .bucket(bucketName) - .build(); - - CompletableFuture futureGet = s3AsyncClient.createBucket(bucketRequest); - futureGet.whenComplete((resp, err) -> { - try { - if (resp != null) { - System.out.println(bucketName + " is ready~"); - } else { - err.printStackTrace(); - } - } finally { - // Only close the client when you are completely done with it. - s3AsyncClient.close(); - } - }); - futureGet.join(); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.async; + +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.CreateBucketResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.net.URISyntaxException; +import java.util.concurrent.CompletableFuture; + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ +public class CreateBucketAsync { + + public static void main(String[] args) throws URISyntaxException { + final String usage = """ + + Usage: + \s + + Where: + bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + System.out.format("Creating a bucket named %s\n", + bucketName); + + Region region = Region.US_EAST_1; + S3AsyncClient s3AsyncClient = S3AsyncClient.builder() + .region(region) + .build(); + + createBucket(s3AsyncClient, bucketName); + } + + public static void createBucket(S3AsyncClient s3AsyncClient, String bucketName) { + try { + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .build(); + + CompletableFuture futureGet = s3AsyncClient.createBucket(bucketRequest); + futureGet.whenComplete((resp, err) -> { + try { + if (resp != null) { + System.out.println(bucketName + " is ready~"); + } else { + err.printStackTrace(); + } + } finally { + // Only close the client when you are completely done with it. + s3AsyncClient.close(); + } + }); + futureGet.join(); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java index c40378e5b22..602d92d0d71 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/GetObjectDataAsync.java @@ -1,83 +1,83 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3.async; - -import software.amazon.awssdk.core.async.AsyncResponseTransformer; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3AsyncClient; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; -import java.nio.file.Paths; -import java.util.concurrent.CompletableFuture; - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class GetObjectDataAsync { - public static void main(String[] args) { - final String usage = """ - - Usage: - - - Where: - bucketName - The Amazon S3 bucket name.\s - keyName - The key name.\s - path - The path where the file is written to.\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - String bucketName = args[0]; - String keyName = args[1]; - String path = args[2]; - Region region = Region.US_EAST_1; - S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); - - getObject(s3AsyncClient, bucketName, keyName, path); - s3AsyncClient.close(); - } - - public static void getObject(S3AsyncClient s3AsyncClient, String bucketName, String keyName, String path) { - try { - GetObjectRequest objectRequest = GetObjectRequest - .builder() - .key(keyName) - .bucket(bucketName) - .build(); - - CompletableFuture futureGet = s3AsyncClient.getObject(objectRequest, - AsyncResponseTransformer.toFile(Paths.get(path))); - - futureGet.whenComplete((resp, err) -> { - try { - if (resp != null) { - System.out.println("Object downloaded. Details: " + resp); - } else { - err.printStackTrace(); - } - } finally { - // Only close the client when you are completely done with it. - s3AsyncClient.close(); - } - }); - futureGet.join(); - - } catch (S3Exception e) { - System.err.println(e.awsErrorDetails().errorMessage()); - System.exit(1); - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.async; + +import software.amazon.awssdk.core.async.AsyncResponseTransformer; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import java.nio.file.Paths; +import java.util.concurrent.CompletableFuture; + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class GetObjectDataAsync { + public static void main(String[] args) { + final String usage = """ + + Usage: + + + Where: + bucketName - The Amazon S3 bucket name.\s + keyName - The key name.\s + path - The path where the file is written to.\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + String bucketName = args[0]; + String keyName = args[1]; + String path = args[2]; + Region region = Region.US_EAST_1; + S3AsyncClient s3AsyncClient = S3AsyncClient.builder() + .region(region) + .build(); + + getObject(s3AsyncClient, bucketName, keyName, path); + s3AsyncClient.close(); + } + + public static void getObject(S3AsyncClient s3AsyncClient, String bucketName, String keyName, String path) { + try { + GetObjectRequest objectRequest = GetObjectRequest + .builder() + .key(keyName) + .bucket(bucketName) + .build(); + + CompletableFuture futureGet = s3AsyncClient.getObject(objectRequest, + AsyncResponseTransformer.toFile(Paths.get(path))); + + futureGet.whenComplete((resp, err) -> { + try { + if (resp != null) { + System.out.println("Object downloaded. Details: " + resp); + } else { + err.printStackTrace(); + } + } finally { + // Only close the client when you are completely done with it. + s3AsyncClient.close(); + } + }); + futureGet.join(); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + System.exit(1); + } + } +} diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/PutObjectFromStreamAsync.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncOps.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncOps.java index 38334db8c93..8fc43b421e6 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncOps.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncOps.java @@ -1,84 +1,84 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3.async; - -// snippet-start:[s3.java2.async_ops.complete] -// snippet-start:[s3.java2.async_ops.import] -import software.amazon.awssdk.core.async.AsyncRequestBody; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3AsyncClient; -import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.PutObjectResponse; -import java.nio.file.Paths; -import java.util.concurrent.CompletableFuture; -// snippet-end:[s3.java2.async_ops.import] -// snippet-start:[s3.java2.async_ops.main] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class S3AsyncOps { - public static void main(String[] args) { - - final String usage = """ - - Usage: - - - Where: - bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s - key - The name of the object (for example, book.pdf).\s - path - The local path to the file (for example, C:/AWS/book.pdf).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String key = args[1]; - String path = args[2]; - Region region = Region.US_EAST_1; - S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); - - putObjectAsync(s3AsyncClient, bucketName, key, path); - } - - public static void putObjectAsync(S3AsyncClient client, String bucketName, String key, String path) { - PutObjectRequest objectRequest = PutObjectRequest.builder() - .bucket(bucketName) - .key(key) - .build(); - - CompletableFuture future = client.putObject(objectRequest, - AsyncRequestBody.fromFile(Paths.get(path))); - future.whenComplete((resp, err) -> { - try { - if (resp != null) { - System.out.println("Object uploaded. Details: " + resp); - } else { - // Handle error. - err.printStackTrace(); - } - } finally { - // Only close the client when you are completely done with it. - client.close(); - } - }); - - future.join(); - } -} - -// snippet-end:[s3.java2.async_ops.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.async; + +// snippet-start:[s3.java2.async_ops.complete] +// snippet-start:[s3.java2.async_ops.import] +import software.amazon.awssdk.core.async.AsyncRequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import java.nio.file.Paths; +import java.util.concurrent.CompletableFuture; +// snippet-end:[s3.java2.async_ops.import] +// snippet-start:[s3.java2.async_ops.main] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class S3AsyncOps { + public static void main(String[] args) { + + final String usage = """ + + Usage: + + + Where: + bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s + key - The name of the object (for example, book.pdf).\s + path - The local path to the file (for example, C:/AWS/book.pdf).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String key = args[1]; + String path = args[2]; + Region region = Region.US_EAST_1; + S3AsyncClient s3AsyncClient = S3AsyncClient.builder() + .region(region) + .build(); + + putObjectAsync(s3AsyncClient, bucketName, key, path); + } + + public static void putObjectAsync(S3AsyncClient client, String bucketName, String key, String path) { + PutObjectRequest objectRequest = PutObjectRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + CompletableFuture future = client.putObject(objectRequest, + AsyncRequestBody.fromFile(Paths.get(path))); + future.whenComplete((resp, err) -> { + try { + if (resp != null) { + System.out.println("Object uploaded. Details: " + resp); + } else { + // Handle error. + err.printStackTrace(); + } + } finally { + // Only close the client when you are completely done with it. + client.close(); + } + }); + + future.join(); + } +} + +// snippet-end:[s3.java2.async_ops.main] // snippet-end:[s3.java2.async_ops.complete] \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java similarity index 97% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java index 79f0eef1450..5d747dcdffa 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/S3AsyncStreamOps.java @@ -1,78 +1,78 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.s3.async; -// snippet-start:[s3.java2.async_stream_ops.complete] - -// snippet-start:[s3.java2.async_stream_ops.import] -import software.amazon.awssdk.core.async.AsyncResponseTransformer; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3AsyncClient; -import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; -import java.nio.file.Paths; -import java.util.concurrent.CompletableFuture; -// snippet-end:[s3.java2.async_stream_ops.import] - -// snippet-start:[s3.java2.async_stream_ops.main] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - */ - -public class S3AsyncStreamOps { - public static void main(String[] args) { - final String usage = """ - Usage: - - - Where: - bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s - - objectKey - The name of the object (for example, book.pdf).\s - path - The local path to the file (for example, C:/AWS/book.pdf).\s - """; - - if (args.length != 3) { - System.out.println(usage); - System.exit(1); - } - - String bucketName = args[0]; - String objectKey = args[1]; - String path = args[2]; - Region region = Region.US_EAST_1; - S3AsyncClient s3AsyncClient = S3AsyncClient.builder() - .region(region) - .build(); - - GetObjectRequest objectRequest = GetObjectRequest.builder() - .bucket(bucketName) - .key(objectKey) - .build(); - - CompletableFuture futureGet = s3AsyncClient.getObject(objectRequest, - AsyncResponseTransformer.toFile(Paths.get(path))); - - futureGet.whenComplete((resp, err) -> { - try { - if (resp != null) { - System.out.println("Object downloaded. Details: " + resp); - } else { - err.printStackTrace(); - } - } finally { - // Only close the client when you are completely done with it. - s3AsyncClient.close(); - } - }); - futureGet.join(); - } -} -// snippet-end:[s3.java2.async_stream_ops.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.async; +// snippet-start:[s3.java2.async_stream_ops.complete] + +// snippet-start:[s3.java2.async_stream_ops.import] +import software.amazon.awssdk.core.async.AsyncResponseTransformer; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import java.nio.file.Paths; +import java.util.concurrent.CompletableFuture; +// snippet-end:[s3.java2.async_stream_ops.import] + +// snippet-start:[s3.java2.async_stream_ops.main] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + +public class S3AsyncStreamOps { + public static void main(String[] args) { + final String usage = """ + Usage: + + + Where: + bucketName - The name of the Amazon S3 bucket (for example, bucket1).\s + + objectKey - The name of the object (for example, book.pdf).\s + path - The local path to the file (for example, C:/AWS/book.pdf).\s + """; + + if (args.length != 3) { + System.out.println(usage); + System.exit(1); + } + + String bucketName = args[0]; + String objectKey = args[1]; + String path = args[2]; + Region region = Region.US_EAST_1; + S3AsyncClient s3AsyncClient = S3AsyncClient.builder() + .region(region) + .build(); + + GetObjectRequest objectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + CompletableFuture futureGet = s3AsyncClient.getObject(objectRequest, + AsyncResponseTransformer.toFile(Paths.get(path))); + + futureGet.whenComplete((resp, err) -> { + try { + if (resp != null) { + System.out.println("Object downloaded. Details: " + resp); + } else { + err.printStackTrace(); + } + } finally { + // Only close the client when you are completely done with it. + s3AsyncClient.close(); + } + }); + futureGet.join(); + } +} +// snippet-end:[s3.java2.async_stream_ops.main] // snippet-end:[s3.java2.async_stream_ops.complete] \ No newline at end of file diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java similarity index 99% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java index 33bcdfcd019..27202ecacee 100644 --- a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java +++ b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java @@ -12,7 +12,6 @@ import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DirectoryDownload; import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest; - import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/S3ClientFactory.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/transfermanager/UploadStream.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/util/AsyncExampleUtils.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/util/MemoryLog4jAppender.java diff --git a/javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java b/javav2/example_code/s3/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java similarity index 100% rename from javav2/example_code/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java rename to javav2/example_code/s3/s3/src/main/java/com/example/s3/util/PresignUrlUtils.java diff --git a/javav2/example_code/s3/src/main/resources/config.properties b/javav2/example_code/s3/s3/src/main/resources/config.properties similarity index 100% rename from javav2/example_code/s3/src/main/resources/config.properties rename to javav2/example_code/s3/s3/src/main/resources/config.properties diff --git a/javav2/example_code/s3/src/main/resources/downloadDirectory/dummy.txt b/javav2/example_code/s3/s3/src/main/resources/downloadDirectory/dummy.txt similarity index 100% rename from javav2/example_code/s3/src/main/resources/downloadDirectory/dummy.txt rename to javav2/example_code/s3/s3/src/main/resources/downloadDirectory/dummy.txt diff --git a/javav2/example_code/s3/src/main/resources/image.png b/javav2/example_code/s3/s3/src/main/resources/image.png similarity index 100% rename from javav2/example_code/s3/src/main/resources/image.png rename to javav2/example_code/s3/s3/src/main/resources/image.png diff --git a/javav2/example_code/s3/src/main/resources/log4j2.xml b/javav2/example_code/s3/s3/src/main/resources/log4j2.xml similarity index 100% rename from javav2/example_code/s3/src/main/resources/log4j2.xml rename to javav2/example_code/s3/s3/src/main/resources/log4j2.xml diff --git a/javav2/example_code/s3/src/main/resources/multipartUploadFiles/java_dev_guide_v2.pdf b/javav2/example_code/s3/s3/src/main/resources/multipartUploadFiles/java_dev_guide_v2.pdf similarity index 100% rename from javav2/example_code/s3/src/main/resources/multipartUploadFiles/java_dev_guide_v2.pdf rename to javav2/example_code/s3/s3/src/main/resources/multipartUploadFiles/java_dev_guide_v2.pdf diff --git a/javav2/example_code/s3/src/main/resources/multipartUploadFiles/s3-userguide.pdf b/javav2/example_code/s3/s3/src/main/resources/multipartUploadFiles/s3-userguide.pdf similarity index 100% rename from javav2/example_code/s3/src/main/resources/multipartUploadFiles/s3-userguide.pdf rename to javav2/example_code/s3/s3/src/main/resources/multipartUploadFiles/s3-userguide.pdf diff --git a/javav2/example_code/s3/src/main/resources/uploadDirectory/file1.txt b/javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file1.txt similarity index 100% rename from javav2/example_code/s3/src/main/resources/uploadDirectory/file1.txt rename to javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file1.txt diff --git a/javav2/example_code/s3/src/main/resources/uploadDirectory/file2.txt b/javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file2.txt similarity index 100% rename from javav2/example_code/s3/src/main/resources/uploadDirectory/file2.txt rename to javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file2.txt diff --git a/javav2/example_code/s3/src/main/resources/uploadDirectory/file3.txt b/javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file3.txt similarity index 100% rename from javav2/example_code/s3/src/main/resources/uploadDirectory/file3.txt rename to javav2/example_code/s3/s3/src/main/resources/uploadDirectory/file3.txt diff --git a/javav2/example_code/s3/src/test/java/AmazonS3Test.java b/javav2/example_code/s3/s3/src/test/java/AmazonS3Test.java similarity index 97% rename from javav2/example_code/s3/src/test/java/AmazonS3Test.java rename to javav2/example_code/s3/s3/src/test/java/AmazonS3Test.java index 40635b703ad..37f2d9e7c5f 100644 --- a/javav2/example_code/s3/src/test/java/AmazonS3Test.java +++ b/javav2/example_code/s3/s3/src/test/java/AmazonS3Test.java @@ -1,555 +1,555 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import com.example.s3.CopyObject; -import com.example.s3.CopyObjectStorage; -import com.example.s3.CreateAccessPoint; -import com.example.s3.CreateBucket; -import com.example.s3.DeleteBucketPolicy; -import com.example.s3.DeleteMultiObjects; -import com.example.s3.DeleteObjects; -import com.example.s3.GetObjectData; -import com.example.s3.GetObjectPresignedUrl; -import com.example.s3.GetObjectRestoreStatus; -import com.example.s3.LifecycleConfiguration; -import com.example.s3.ListObjects; -import com.example.s3.PutObject; -import com.example.s3.RestoreObject; -import com.example.s3.S3Cors; -import com.example.s3.S3Scenario; -import com.example.s3.S3ZipExample; -import com.google.gson.Gson; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.TestMethodOrder; -import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.s3.S3Client; - -import java.io.IOException; - -import software.amazon.awssdk.services.s3.presigner.S3Presigner; -import software.amazon.awssdk.services.s3control.S3ControlClient; -import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; -import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; -import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; - -/** - * To run these integration tests, you must set the required values - * in the config.properties file or AWS Secrets Manager. - */ -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class AmazonS3Test { - private static S3Client s3; - private static S3Presigner presigner; - private static S3ControlClient s3ControlClient; - - // Define the data members required for the tests. - private static String bucketName = ""; - private static String objectKey = ""; - private static String objectPath = ""; - private static String toBucket = ""; - private static String policyText = ""; - private static String id = ""; - private static String presignKey = ""; - private static String presignBucket = ""; - private static String path = ""; - private static String bucketNamePolicy = ""; - private static String accountId = ""; - private static String accessPointName = ""; - private static String bucketNameZip = ""; - - // Used for the encryption test. - private static String encryptObjectName = ""; - private static String encryptObjectPath = ""; - private static String encryptOutPath = ""; - private static String keyId = ""; - - // Used for restore tests. - private static String restoreImagePath = ""; - private static String restoreBucket = ""; - private static String restoreImageName = ""; - - // Used for the Scenario test. - private static String bucketNameSc = ""; - private static String keySc = ""; - private static String objectPathSc = ""; - private static String savePathSc = ""; - private static String toBucketSc = ""; - private static String images = ""; - private static String[] imageKeys; - - @BeforeAll - public static void setUp() throws IOException { - s3 = S3Client.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - presigner = S3Presigner.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - s3ControlClient = S3ControlClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - - // Get the values to run these tests from AWS Secrets Manager. - Gson gson = new Gson(); - String json = getSecretValues(); - SecretValues values = gson.fromJson(json, SecretValues.class); - bucketName = values.getBucketName() + java.util.UUID.randomUUID(); - objectKey = values.getObjectKey(); - objectPath = values.getObjectPath(); - toBucket = values.getToBucket(); - policyText = values.getPolicyText(); - id = values.getId(); - presignKey = values.getPresignKey(); - presignBucket = values.getPresignBucket(); - path = values.getPath(); - bucketNamePolicy = values.getBucketNamePolicy(); - accountId = values.getAccountId(); - accessPointName = values.getAccessPointName(); - encryptObjectName = values.getEncryptObjectName(); - encryptObjectPath = values.getEncryptObjectPath(); - encryptOutPath = values.getEncryptOutPath(); - keyId = values.getKeyId(); - restoreImagePath = values.getRestoreImagePath(); - restoreBucket = values.getRestoreBucket(); - restoreImageName = values.getRestoreImageName(); - bucketNameSc = values.getBucketNameSc() + java.util.UUID.randomUUID(); - keySc = values.getKeySc(); - objectPathSc = values.getObjectPathSc(); - savePathSc = values.getSavePathSc(); - toBucketSc = values.getToBucketSc(); - bucketNameZip = values.getBucketNameZip(); - images = values.getImages(); - imageKeys = images.split("[,]", 0); - - // Uncomment this code block if you prefer using a config.properties file to - // retrieve AWS values required for these tests. - /* - * try (InputStream input = - * AmazonS3Test.class.getClassLoader().getResourceAsStream("config.properties")) - * { - * Properties prop = new Properties(); - * - * if (input == null) { - * System.out.println("Sorry, unable to find config.properties"); - * return; - * } - * prop.load(input); - * bucketName = prop.getProperty("bucketName")+ java.util.UUID.randomUUID();; - * objectKey = prop.getProperty("objectKey"); - * objectPath= prop.getProperty("objectPath"); - * toBucket = prop.getProperty("toBucket"); - * policyText = prop.getProperty("policyText"); - * id = prop.getProperty("id"); - * presignKey = prop.getProperty("presignKey"); - * presignBucket= prop.getProperty("presignBucket"); - * path = prop.getProperty("path"); - * bucketNamePolicy = prop.getProperty("bucketNamePolicy"); - * accountId = prop.getProperty("accountId"); - * accessPointName = prop.getProperty("accessPointName"); - * encryptObjectName = prop.getProperty("encryptObjectName"); - * encryptObjectPath = prop.getProperty("encryptObjectPath"); - * encryptOutPath = prop.getProperty("encryptOutPath"); - * keyId = prop.getProperty("keyId"); - * restoreImagePath = prop.getProperty("restoreImagePath"); - * restoreBucket = prop.getProperty("restoreBucket"); - * restoreImageName = prop.getProperty("restoreImageName"); - * bucketNameSc = prop.getProperty("bucketNameSc")+ - * java.util.UUID.randomUUID();; - * keySc = prop.getProperty("keySc"); - * objectPathSc = prop.getProperty("objectPathSc"); - * savePathSc = prop.getProperty("savePathSc"); - * toBucketSc = prop.getProperty("toBucketSc"); - * bucketNameZip = prop.getProperty("bucketNameZip"); - * images = prop.getProperty("images"); - * imageKeys = images.split("[,]", 0); - * - * } catch (IOException ex) { - * ex.printStackTrace(); - * } - */ - } - - @Test - @Tag("IntegrationTest") - @Order(1) - public void createBucket() { - assertDoesNotThrow(() -> CreateBucket.createBucket(s3, bucketName)); - System.out.println("Test 1 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(2) - public void putObject() { - assertDoesNotThrow(() -> PutObject.putS3Object(s3, bucketName, objectKey, objectPath)); - System.out.println("Test 2 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(3) - public void copyBucketObject() { - String result = CopyObject.copyBucketObject(s3, bucketName, objectKey, toBucket); - assertFalse(result.isEmpty()); - System.out.println("Test 3 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(6) - public void deleteBucketPolicy() { - assertDoesNotThrow(() -> DeleteBucketPolicy.deleteS3BucketPolicy(s3, bucketNamePolicy)); - System.out.println("Test 6 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(7) - public void getObjectPresignedUrl() { - assertDoesNotThrow(() -> GetObjectPresignedUrl.getPresignedUrl(presigner, presignBucket, presignKey)); - System.out.println("Test 8 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(8) - public void getObjectData() { - assertDoesNotThrow(() -> GetObjectData.getObjectBytes(s3, bucketName, objectKey, path)); - System.out.println("Test 9 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(9) - public void listObjects() { - assertDoesNotThrow(() -> ListObjects.listBucketObjects(s3, bucketName)); - System.out.println("Test 10 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(10) - public void createAccessPoint() { - assertDoesNotThrow(() -> CreateAccessPoint.createSpecificAccessPoint(s3ControlClient, accountId, bucketName, - accessPointName)); - assertDoesNotThrow( - () -> CreateAccessPoint.deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName)); - System.out.println("Test 11 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(11) - public void lifecycleConfiguration() { - assertDoesNotThrow(() -> LifecycleConfiguration.setLifecycleConfig(s3, bucketName, accountId)); - assertDoesNotThrow(() -> LifecycleConfiguration.getLifecycleConfig(s3, bucketName, accountId)); - assertDoesNotThrow(() -> LifecycleConfiguration.deleteLifecycleConfig(s3, bucketName, accountId)); - System.out.println("Test 12 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(12) - public void s3Cors() { - assertDoesNotThrow(() -> S3Cors.setCorsInformation(s3, bucketName, accountId)); - assertDoesNotThrow(() -> S3Cors.getBucketCorsInformation(s3, bucketName, accountId)); - assertDoesNotThrow(() -> S3Cors.deleteBucketCorsInformation(s3, bucketName, accountId)); - System.out.println("Test 13 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(13) - public void deleteMultiObjects() { - assertDoesNotThrow(() -> DeleteMultiObjects.deleteBucketObjects(s3, bucketName)); - System.out.println("Test 14 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(14) - public void deleteObjects() { - assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, objectKey)); - assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, encryptObjectName)); - System.out.println("Test 15 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(15) - public void copyObjectStorage() { - assertDoesNotThrow(() -> PutObject.putS3Object(s3, restoreBucket, restoreImageName, restoreImagePath)); - assertDoesNotThrow( - () -> CopyObjectStorage.copyBucketObject(s3, restoreBucket, restoreImageName, restoreBucket)); - System.out.println("Test 16 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(16) - public void restoreObject() { - assertDoesNotThrow(() -> RestoreObject.restoreS3Object(s3, restoreBucket, restoreImageName, accountId)); - System.out.println("Test 17 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(17) - public void getRestoreStatus() { - assertDoesNotThrow(() -> GetObjectRestoreStatus.checkStatus(s3, restoreBucket, restoreImageName)); - System.out.println("Test 18 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(18) - public void s3ZipExample() { - assertDoesNotThrow(() -> S3ZipExample.createZIPFile(s3, bucketNameZip, imageKeys)); - System.out.println("Test 19 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(19) - public void deleteBucket() { - assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketName)); - System.out.println("Test 19 passed"); - } - - @Test - @Tag("IntegrationTest") - @Order(20) - public void testScenario() { - System.out.println(S3Scenario.DASHES); - System.out.println("1. Create an Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.createBucket(s3, bucketNameSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("2. Update a local file to the Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.uploadLocalFile(s3, bucketNameSc, keySc, objectPathSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("3. Download the object to another local file."); - assertDoesNotThrow(() -> S3Scenario.getObjectBytes(s3, bucketNameSc, keySc, savePathSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("4. Perform a multipart upload."); - String multipartKey = "multiPartKey"; - assertDoesNotThrow(() -> S3Scenario.multipartUpload(s3, toBucketSc, multipartKey)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("5. List all objects located in the Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.listAllObjects(s3, bucketNameSc)); - assertDoesNotThrow(() -> S3Scenario.anotherListExample(s3, bucketNameSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("6. Copy the object to another Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.copyBucketObject(s3, bucketNameSc, keySc, toBucketSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("7. Delete the object from the Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.deleteObjectFromBucket(s3, bucketNameSc, keySc)); - System.out.println(S3Scenario.DASHES); - - System.out.println(S3Scenario.DASHES); - System.out.println("8. Delete the Amazon S3 bucket."); - assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketNameSc)); - System.out.println(S3Scenario.DASHES); - - System.out.println("Test 20 passed"); - } - - private static String getSecretValues() { - SecretsManagerClient secretClient = SecretsManagerClient.builder() - .region(Region.US_EAST_1) - .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) - .build(); - String secretName = "test/s3"; - - GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() - .secretId(secretName) - .build(); - - GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); - return valueResponse.secretString(); - } - - @Nested - @DisplayName("A class used to get test values from test/s3 (an AWS Secrets Manager secret)") - class SecretValues { - private String bucketName; - private String bucketNamePolicy; - private String presignBucket; - - private String objectKey; - - private String presignKey; - private String path; - - private String objectPath; - - private String toBucket; - private String policyText; - - private String id; - - private String accountId; - - private String accessPointName; - - private String encryptObjectName; - - private String encryptObjectPath; - - private String encryptOutPath; - - private String keyId; - - private String restoreImagePath; - - private String restoreBucket; - - private String restoreImageName; - - private String bucketNameSc; - - private String keySc; - - private String objectPathSc; - - private String savePathSc; - - private String toBucketSc; - - private String bucketNameZip; - - private String images; - - public String getBucketName() { - return bucketName; - } - - public String getBucketNamePolicy() { - return bucketNamePolicy; - } - - public String getPresignBucket() { - return presignBucket; - } - - public String getObjectKey() { - return objectKey; - } - - public String getPresignKey() { - return presignKey; - } - - public String getPath() { - return path; - } - - public String getObjectPath() { - return objectPath; - } - - public String getToBucket() { - return toBucket; - } - - public String getPolicyText() { - return policyText; - } - - public String getId() { - return id; - } - - public String getAccountId() { - return accountId; - } - - public String getAccessPointName() { - return accessPointName; - } - - public String getEncryptObjectName() { - return encryptObjectName; - } - - public String getEncryptObjectPath() { - return encryptObjectPath; - } - - public String getEncryptOutPath() { - return encryptOutPath; - } - - public String getKeyId() { - return keyId; - } - - public String getRestoreImagePath() { - return restoreImagePath; - } - - public String getRestoreBucket() { - return restoreBucket; - } - - public String getRestoreImageName() { - return restoreImageName; - } - - public String getBucketNameSc() { - return bucketNameSc; - } - - public String getKeySc() { - return keySc; - } - - public String getObjectPathSc() { - return objectPathSc; - } - - public String getSavePathSc() { - return savePathSc; - } - - public String getToBucketSc() { - return toBucketSc; - } - - public String getBucketNameZip() { - return bucketNameZip; - } - - public String getImages() { - return images; - } - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import com.example.s3.CopyObject; +import com.example.s3.CopyObjectStorage; +import com.example.s3.CreateAccessPoint; +import com.example.s3.CreateBucket; +import com.example.s3.DeleteBucketPolicy; +import com.example.s3.DeleteMultiObjects; +import com.example.s3.DeleteObjects; +import com.example.s3.GetObjectData; +import com.example.s3.GetObjectPresignedUrl; +import com.example.s3.GetObjectRestoreStatus; +import com.example.s3.LifecycleConfiguration; +import com.example.s3.ListObjects; +import com.example.s3.PutObject; +import com.example.s3.RestoreObject; +import com.example.s3.S3Cors; +import com.example.s3.S3Scenario; +import com.example.s3.S3ZipExample; +import com.google.gson.Gson; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; + +import java.io.IOException; + +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3control.S3ControlClient; +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; +import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; + +/** + * To run these integration tests, you must set the required values + * in the config.properties file or AWS Secrets Manager. + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class AmazonS3Test { + private static S3Client s3; + private static S3Presigner presigner; + private static S3ControlClient s3ControlClient; + + // Define the data members required for the tests. + private static String bucketName = ""; + private static String objectKey = ""; + private static String objectPath = ""; + private static String toBucket = ""; + private static String policyText = ""; + private static String id = ""; + private static String presignKey = ""; + private static String presignBucket = ""; + private static String path = ""; + private static String bucketNamePolicy = ""; + private static String accountId = ""; + private static String accessPointName = ""; + private static String bucketNameZip = ""; + + // Used for the encryption test. + private static String encryptObjectName = ""; + private static String encryptObjectPath = ""; + private static String encryptOutPath = ""; + private static String keyId = ""; + + // Used for restore tests. + private static String restoreImagePath = ""; + private static String restoreBucket = ""; + private static String restoreImageName = ""; + + // Used for the Scenario test. + private static String bucketNameSc = ""; + private static String keySc = ""; + private static String objectPathSc = ""; + private static String savePathSc = ""; + private static String toBucketSc = ""; + private static String images = ""; + private static String[] imageKeys; + + @BeforeAll + public static void setUp() throws IOException { + s3 = S3Client.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + + presigner = S3Presigner.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + + s3ControlClient = S3ControlClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + + // Get the values to run these tests from AWS Secrets Manager. + Gson gson = new Gson(); + String json = getSecretValues(); + SecretValues values = gson.fromJson(json, SecretValues.class); + bucketName = values.getBucketName() + java.util.UUID.randomUUID(); + objectKey = values.getObjectKey(); + objectPath = values.getObjectPath(); + toBucket = values.getToBucket(); + policyText = values.getPolicyText(); + id = values.getId(); + presignKey = values.getPresignKey(); + presignBucket = values.getPresignBucket(); + path = values.getPath(); + bucketNamePolicy = values.getBucketNamePolicy(); + accountId = values.getAccountId(); + accessPointName = values.getAccessPointName(); + encryptObjectName = values.getEncryptObjectName(); + encryptObjectPath = values.getEncryptObjectPath(); + encryptOutPath = values.getEncryptOutPath(); + keyId = values.getKeyId(); + restoreImagePath = values.getRestoreImagePath(); + restoreBucket = values.getRestoreBucket(); + restoreImageName = values.getRestoreImageName(); + bucketNameSc = values.getBucketNameSc() + java.util.UUID.randomUUID(); + keySc = values.getKeySc(); + objectPathSc = values.getObjectPathSc(); + savePathSc = values.getSavePathSc(); + toBucketSc = values.getToBucketSc(); + bucketNameZip = values.getBucketNameZip(); + images = values.getImages(); + imageKeys = images.split("[,]", 0); + + // Uncomment this code block if you prefer using a config.properties file to + // retrieve AWS values required for these tests. + /* + * try (InputStream input = + * AmazonS3Test.class.getClassLoader().getResourceAsStream("config.properties")) + * { + * Properties prop = new Properties(); + * + * if (input == null) { + * System.out.println("Sorry, unable to find config.properties"); + * return; + * } + * prop.load(input); + * bucketName = prop.getProperty("bucketName")+ java.util.UUID.randomUUID();; + * objectKey = prop.getProperty("objectKey"); + * objectPath= prop.getProperty("objectPath"); + * toBucket = prop.getProperty("toBucket"); + * policyText = prop.getProperty("policyText"); + * id = prop.getProperty("id"); + * presignKey = prop.getProperty("presignKey"); + * presignBucket= prop.getProperty("presignBucket"); + * path = prop.getProperty("path"); + * bucketNamePolicy = prop.getProperty("bucketNamePolicy"); + * accountId = prop.getProperty("accountId"); + * accessPointName = prop.getProperty("accessPointName"); + * encryptObjectName = prop.getProperty("encryptObjectName"); + * encryptObjectPath = prop.getProperty("encryptObjectPath"); + * encryptOutPath = prop.getProperty("encryptOutPath"); + * keyId = prop.getProperty("keyId"); + * restoreImagePath = prop.getProperty("restoreImagePath"); + * restoreBucket = prop.getProperty("restoreBucket"); + * restoreImageName = prop.getProperty("restoreImageName"); + * bucketNameSc = prop.getProperty("bucketNameSc")+ + * java.util.UUID.randomUUID();; + * keySc = prop.getProperty("keySc"); + * objectPathSc = prop.getProperty("objectPathSc"); + * savePathSc = prop.getProperty("savePathSc"); + * toBucketSc = prop.getProperty("toBucketSc"); + * bucketNameZip = prop.getProperty("bucketNameZip"); + * images = prop.getProperty("images"); + * imageKeys = images.split("[,]", 0); + * + * } catch (IOException ex) { + * ex.printStackTrace(); + * } + */ + } + + @Test + @Tag("IntegrationTest") + @Order(1) + public void createBucket() { + assertDoesNotThrow(() -> CreateBucket.createBucket(s3, bucketName)); + System.out.println("Test 1 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(2) + public void putObject() { + assertDoesNotThrow(() -> PutObject.putS3Object(s3, bucketName, objectKey, objectPath)); + System.out.println("Test 2 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(3) + public void copyBucketObject() { + String result = CopyObject.copyBucketObject(s3, bucketName, objectKey, toBucket); + assertFalse(result.isEmpty()); + System.out.println("Test 3 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(6) + public void deleteBucketPolicy() { + assertDoesNotThrow(() -> DeleteBucketPolicy.deleteS3BucketPolicy(s3, bucketNamePolicy)); + System.out.println("Test 6 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(7) + public void getObjectPresignedUrl() { + assertDoesNotThrow(() -> GetObjectPresignedUrl.getPresignedUrl(presigner, presignBucket, presignKey)); + System.out.println("Test 8 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(8) + public void getObjectData() { + assertDoesNotThrow(() -> GetObjectData.getObjectBytes(s3, bucketName, objectKey, path)); + System.out.println("Test 9 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(9) + public void listObjects() { + assertDoesNotThrow(() -> ListObjects.listBucketObjects(s3, bucketName)); + System.out.println("Test 10 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(10) + public void createAccessPoint() { + assertDoesNotThrow(() -> CreateAccessPoint.createSpecificAccessPoint(s3ControlClient, accountId, bucketName, + accessPointName)); + assertDoesNotThrow( + () -> CreateAccessPoint.deleteSpecificAccessPoint(s3ControlClient, accountId, accessPointName)); + System.out.println("Test 11 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(11) + public void lifecycleConfiguration() { + assertDoesNotThrow(() -> LifecycleConfiguration.setLifecycleConfig(s3, bucketName, accountId)); + assertDoesNotThrow(() -> LifecycleConfiguration.getLifecycleConfig(s3, bucketName, accountId)); + assertDoesNotThrow(() -> LifecycleConfiguration.deleteLifecycleConfig(s3, bucketName, accountId)); + System.out.println("Test 12 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(12) + public void s3Cors() { + assertDoesNotThrow(() -> S3Cors.setCorsInformation(s3, bucketName, accountId)); + assertDoesNotThrow(() -> S3Cors.getBucketCorsInformation(s3, bucketName, accountId)); + assertDoesNotThrow(() -> S3Cors.deleteBucketCorsInformation(s3, bucketName, accountId)); + System.out.println("Test 13 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(13) + public void deleteMultiObjects() { + assertDoesNotThrow(() -> DeleteMultiObjects.deleteBucketObjects(s3, bucketName)); + System.out.println("Test 14 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(14) + public void deleteObjects() { + assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, objectKey)); + assertDoesNotThrow(() -> DeleteObjects.deleteBucketObjects(s3, bucketName, encryptObjectName)); + System.out.println("Test 15 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(15) + public void copyObjectStorage() { + assertDoesNotThrow(() -> PutObject.putS3Object(s3, restoreBucket, restoreImageName, restoreImagePath)); + assertDoesNotThrow( + () -> CopyObjectStorage.copyBucketObject(s3, restoreBucket, restoreImageName, restoreBucket)); + System.out.println("Test 16 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(16) + public void restoreObject() { + assertDoesNotThrow(() -> RestoreObject.restoreS3Object(s3, restoreBucket, restoreImageName, accountId)); + System.out.println("Test 17 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(17) + public void getRestoreStatus() { + assertDoesNotThrow(() -> GetObjectRestoreStatus.checkStatus(s3, restoreBucket, restoreImageName)); + System.out.println("Test 18 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(18) + public void s3ZipExample() { + assertDoesNotThrow(() -> S3ZipExample.createZIPFile(s3, bucketNameZip, imageKeys)); + System.out.println("Test 19 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(19) + public void deleteBucket() { + assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketName)); + System.out.println("Test 19 passed"); + } + + @Test + @Tag("IntegrationTest") + @Order(20) + public void testScenario() { + System.out.println(S3Scenario.DASHES); + System.out.println("1. Create an Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.createBucket(s3, bucketNameSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("2. Update a local file to the Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.uploadLocalFile(s3, bucketNameSc, keySc, objectPathSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("3. Download the object to another local file."); + assertDoesNotThrow(() -> S3Scenario.getObjectBytes(s3, bucketNameSc, keySc, savePathSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("4. Perform a multipart upload."); + String multipartKey = "multiPartKey"; + assertDoesNotThrow(() -> S3Scenario.multipartUpload(s3, toBucketSc, multipartKey)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("5. List all objects located in the Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.listAllObjects(s3, bucketNameSc)); + assertDoesNotThrow(() -> S3Scenario.anotherListExample(s3, bucketNameSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("6. Copy the object to another Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.copyBucketObject(s3, bucketNameSc, keySc, toBucketSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("7. Delete the object from the Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.deleteObjectFromBucket(s3, bucketNameSc, keySc)); + System.out.println(S3Scenario.DASHES); + + System.out.println(S3Scenario.DASHES); + System.out.println("8. Delete the Amazon S3 bucket."); + assertDoesNotThrow(() -> S3Scenario.deleteBucket(s3, bucketNameSc)); + System.out.println(S3Scenario.DASHES); + + System.out.println("Test 20 passed"); + } + + private static String getSecretValues() { + SecretsManagerClient secretClient = SecretsManagerClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) + .build(); + String secretName = "test/s3"; + + GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() + .secretId(secretName) + .build(); + + GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest); + return valueResponse.secretString(); + } + + @Nested + @DisplayName("A class used to get test values from test/s3 (an AWS Secrets Manager secret)") + class SecretValues { + private String bucketName; + private String bucketNamePolicy; + private String presignBucket; + + private String objectKey; + + private String presignKey; + private String path; + + private String objectPath; + + private String toBucket; + private String policyText; + + private String id; + + private String accountId; + + private String accessPointName; + + private String encryptObjectName; + + private String encryptObjectPath; + + private String encryptOutPath; + + private String keyId; + + private String restoreImagePath; + + private String restoreBucket; + + private String restoreImageName; + + private String bucketNameSc; + + private String keySc; + + private String objectPathSc; + + private String savePathSc; + + private String toBucketSc; + + private String bucketNameZip; + + private String images; + + public String getBucketName() { + return bucketName; + } + + public String getBucketNamePolicy() { + return bucketNamePolicy; + } + + public String getPresignBucket() { + return presignBucket; + } + + public String getObjectKey() { + return objectKey; + } + + public String getPresignKey() { + return presignKey; + } + + public String getPath() { + return path; + } + + public String getObjectPath() { + return objectPath; + } + + public String getToBucket() { + return toBucket; + } + + public String getPolicyText() { + return policyText; + } + + public String getId() { + return id; + } + + public String getAccountId() { + return accountId; + } + + public String getAccessPointName() { + return accessPointName; + } + + public String getEncryptObjectName() { + return encryptObjectName; + } + + public String getEncryptObjectPath() { + return encryptObjectPath; + } + + public String getEncryptOutPath() { + return encryptOutPath; + } + + public String getKeyId() { + return keyId; + } + + public String getRestoreImagePath() { + return restoreImagePath; + } + + public String getRestoreBucket() { + return restoreBucket; + } + + public String getRestoreImageName() { + return restoreImageName; + } + + public String getBucketNameSc() { + return bucketNameSc; + } + + public String getKeySc() { + return keySc; + } + + public String getObjectPathSc() { + return objectPathSc; + } + + public String getSavePathSc() { + return savePathSc; + } + + public String getToBucketSc() { + return toBucketSc; + } + + public String getBucketNameZip() { + return bucketNameZip; + } + + public String getImages() { + return images; + } + } +} diff --git a/javav2/example_code/s3/src/test/java/S3TestWatcher.java b/javav2/example_code/s3/s3/src/test/java/S3TestWatcher.java similarity index 100% rename from javav2/example_code/s3/src/test/java/S3TestWatcher.java rename to javav2/example_code/s3/s3/src/test/java/S3TestWatcher.java diff --git a/javav2/example_code/s3/src/test/java/TransferManagerTest.java b/javav2/example_code/s3/s3/src/test/java/TransferManagerTest.java similarity index 100% rename from javav2/example_code/s3/src/test/java/TransferManagerTest.java rename to javav2/example_code/s3/s3/src/test/java/TransferManagerTest.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/BasicOpsWithChecksumsTests.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/PerformMultiPartUploadTests.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/async/AsyncTests.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/async/AsyncTests.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/async/AsyncTests.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/async/SelectObjectContentExampleTest.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/async/SelectObjectContentExampleTest.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/async/SelectObjectContentExampleTest.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/async/SelectObjectContentExampleTest.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedGetUrlTests.java diff --git a/javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java b/javav2/example_code/s3/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java similarity index 100% rename from javav2/example_code/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java rename to javav2/example_code/s3/s3/src/test/java/com/example/s3/presignurl/GeneratePresignedPutUrlTests.java diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/.gitignore b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/.gitignore new file mode 100644 index 00000000000..5ff6309b719 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/.gitignore @@ -0,0 +1,38 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/README.md b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/README.md new file mode 100644 index 00000000000..78f7f465182 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/README.md @@ -0,0 +1,52 @@ +# Amazon S3 Object Lock Workflow + +## Overview + +This example shows how to use AWS SDKs to work with Amazon Simple Storage Service (Amazon S3) object locking features. The workflow demonstrates how to create, update, view, and modify object locks, as well as how locked objects behave regarding requests to delete and overwrite. + +[Amazon S3 Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) can help prevent Amazon S3 objects from being deleted or overwritten for a fixed amount of time or indefinitely. Object Lock can help meet regulatory requirements or protect against object changes or deletion. + +![Object Lock Features](https://shorturl.at/fiwN8) + +This workflow demonstrates the following steps and tasks: +1. Add object lock settings to both new and existing S3 buckets. + 1. Add objects to buckets with optional object lock or retention period settings. +2. Attempt to delete or overwrite locked objects. +3. Retrieve and view the object lock and retention period settings of buckets and objects. +4. Delete the objects and buckets. + 1. Remove any object locks and use the BypassGovernanceRetention setting. + +## ⚠ Important + +* Running this code might result in charges to your AWS account. +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + +## Scenario + +### Prerequisites + +Before running this Java V2 code example, set up your development environment, including your credentials. + +For more information, see the following documentation [Set up the AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html) + +### Resources + +The workflow scenario steps create the required buckets and objects for the example. No additional resources are required. + +This workflow includes an optional step to add a governance mode retention period of one day to objects in an S3 bucket. In order to delete these objects, you must have the `s3:BypassGovernanceRetention` permission. If you do not have this permission, you will be unable to delete these objects until the retention period has expired. + +### Instructions + +After the example compiles, you can run it from within your IDE. + +This starts an interactive scenario that walks you through creating, exploring, and deleting S3 buckets and objects with various object lock settings. + +## Additional resources + +- [S3 Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/pom.xml b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/pom.xml new file mode 100644 index 00000000000..75717a8026c --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/pom.xml @@ -0,0 +1,165 @@ + + + 4.0.0 + + org.example + S3ObjectLockScenario + 1.0-SNAPSHOT + + + UTF-8 + 17 + 17 + 17 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + + IntegrationTest + + + + org.apache.maven.plugins + maven-resources-plugin + 3.3.1 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 17 + + + + + log4j-plugin-processor + + compile + + process-classes + + only + + org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor + + + + + + + + + + + software.amazon.awssdk + bom + 2.21.20 + pom + import + + + org.apache.logging.log4j + log4j-bom + 2.20.0 + pom + import + + + + + + org.junit.jupiter + junit-jupiter-api + 5.9.2 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.9.2 + test + + + com.fasterxml.jackson.core + jackson-databind + 2.14.2 + + + org.junit.platform + junit-platform-commons + 1.9.2 + + + software.amazon.awssdk.crt + aws-crt + 0.25.1 + + + org.junit.platform + junit-platform-launcher + 1.9.2 + test + + + software.amazon.awssdk + s3 + + + software.amazon.awssdk + apache-client + + + software.amazon.awssdk + sso + + + software.amazon.awssdk + ssooidc + + + software.amazon.awssdk + s3-transfer-manager + + + software.amazon.awssdk + kms + + + software.amazon.awssdk + secretsmanager + + + software.amazon.awssdk + s3control + + + org.apache.logging.log4j + log4j-core + + + org.apache.logging.log4j + log4j-1.2-api + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.commons + commons-lang3 + 3.12.0 + + + com.google.code.gson + gson + 2.10.1 + + + \ No newline at end of file diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3InfoObject.java b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3InfoObject.java new file mode 100644 index 00000000000..f85a6ab0292 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3InfoObject.java @@ -0,0 +1,36 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.scenario; + +public class S3InfoObject { + + private String bucketName; + private String keyName; + private String version; + + public String getBucketName() { + return bucketName; + } + + public void setBucketName(String bucketName) { + this.bucketName = bucketName; + } + + public String getKeyName() { + return keyName; + } + + public void setKeyName(String keyName) { + this.keyName = keyName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } +} + diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java new file mode 100644 index 00000000000..868d4bf3df3 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3LockActions.java @@ -0,0 +1,359 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.scenario; + +// snippet-start:[S3LockWorkflow.javav2.S3ActionsWrapper.main] +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.BucketVersioningStatus; +import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DefaultRetention; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectLegalHoldRequest; +import software.amazon.awssdk.services.s3.model.GetObjectLegalHoldResponse; +import software.amazon.awssdk.services.s3.model.GetObjectLockConfigurationRequest; +import software.amazon.awssdk.services.s3.model.GetObjectLockConfigurationResponse; +import software.amazon.awssdk.services.s3.model.GetObjectRetentionRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRetentionResponse; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest; +import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; +import software.amazon.awssdk.services.s3.model.MFADelete; +import software.amazon.awssdk.services.s3.model.ObjectLockConfiguration; +import software.amazon.awssdk.services.s3.model.ObjectLockEnabled; +import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold; +import software.amazon.awssdk.services.s3.model.ObjectLockLegalHoldStatus; +import software.amazon.awssdk.services.s3.model.ObjectLockRetention; +import software.amazon.awssdk.services.s3.model.ObjectLockRetentionMode; +import software.amazon.awssdk.services.s3.model.ObjectLockRule; +import software.amazon.awssdk.services.s3.model.PutBucketVersioningRequest; +import software.amazon.awssdk.services.s3.model.PutObjectLegalHoldRequest; +import software.amazon.awssdk.services.s3.model.PutObjectLockConfigurationRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.VersioningConfiguration; +import software.amazon.awssdk.services.s3.waiters.S3Waiter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +// Contains application logic for the Amazon S3 operations used in this workflow. +public class S3LockActions { + + private static S3Client getClient() { + return S3Client.builder() + .region(Region.US_EAST_1) + .build(); + } + + // snippet-start:[S3LockWorkflow.javav2.ModifyObjectRetentionPeriod.main] + // Set or modify a retention period on an object in an S3 bucket. + public void modifyObjectRetentionPeriod(String bucketName, String objectKey) { + // Calculate the instant one day from now. + Instant futureInstant = Instant.now().plus(1, ChronoUnit.DAYS); + + // Convert the Instant to a ZonedDateTime object with a specific time zone. + ZonedDateTime zonedDateTime = futureInstant.atZone(ZoneId.systemDefault()); + + // Define a formatter for human-readable output. + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + // Format the ZonedDateTime object to a human-readable date string. + String humanReadableDate = formatter.format(zonedDateTime); + + // Print the formatted date string. + System.out.println("Formatted Date: " + humanReadableDate); + ObjectLockRetention retention = ObjectLockRetention.builder() + .mode(ObjectLockRetentionMode.GOVERNANCE) + .retainUntilDate(futureInstant) + .build(); + + PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder() + .bucket(bucketName) + .key(objectKey) + .retention(retention) + .build(); + + getClient().putObjectRetention(retentionRequest); + System.out.println("Set retention for "+objectKey +" in " +bucketName +" until "+ humanReadableDate +"."); + } + // snippet-end:[S3LockWorkflow.javav2.ModifyObjectRetentionPeriod.main] + + // snippet-start:[S3LockWorkflow.javav2.GetObjectLegalHold.main] + // Get the legal hold details for an S3 object. + public ObjectLockLegalHold getObjectLegalHold(String bucketName, String objectKey) { + try { + GetObjectLegalHoldRequest legalHoldRequest = GetObjectLegalHoldRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + GetObjectLegalHoldResponse response = getClient().getObjectLegalHold(legalHoldRequest); + System.out.println("Object legal hold for " + objectKey + " in " + bucketName + + ":\n\tStatus: " + response.legalHold().status()); + return response.legalHold(); + + } catch (S3Exception ex) { + System.out.println("\tUnable to fetch legal hold: '" + ex.getMessage() + "'"); + } + + return null; + } + // snippet-end:[S3LockWorkflow.javav2.GetObjectLegalHold.main] + + // snippet-start:[S3LockWorkflow.javav2.CreateBucketWithLockOptions.main] + // Create a new Amazon S3 bucket with object lock options. + public void createBucketWithLockOptions(boolean enableObjectLock, String bucketName) { + S3Waiter s3Waiter = getClient().waiter(); + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .objectLockEnabledForBucket(enableObjectLock) + .build(); + + getClient().createBucket(bucketRequest); + HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() + .bucket(bucketName) + .build(); + + // Wait until the bucket is created and print out the response. + s3Waiter.waitUntilBucketExists(bucketRequestWait); + System.out.println(bucketName + " is ready"); + } + // snippet-end:[S3LockWorkflow.javav2.CreateBucketWithLockOptions.main] + + // snippet-start:[S3LockWorkflow.javav2.ListBucketObjectsAndVersions.main] + public List listBucketsAndObjects(List bucketNames, Boolean interactive) { + AtomicInteger counter = new AtomicInteger(0); // Initialize counter. + return bucketNames.stream() + .flatMap(bucketName -> listBucketObjectsAndVersions(bucketName).versions().stream() + .map(version -> { + S3InfoObject s3InfoObject = new S3InfoObject(); + s3InfoObject.setBucketName(bucketName); + s3InfoObject.setVersion(version.versionId()); + s3InfoObject.setKeyName(version.key()); + return s3InfoObject; + })) + .peek(s3InfoObject -> { + int i = counter.incrementAndGet(); // Increment and get the updated value. + if (interactive) { + System.out.println(i + ": "+ s3InfoObject.getKeyName()); + System.out.printf("%5s Bucket name: %s\n", "", s3InfoObject.getBucketName()); + System.out.printf("%5s Version: %s\n", "", s3InfoObject.getVersion()); + } + }) + .collect(Collectors.toList()); + } + // snippet-end:[S3LockWorkflow.javav2.ListBucketObjectsAndVersions.main] + + public ListObjectVersionsResponse listBucketObjectsAndVersions(String bucketName) { + ListObjectVersionsRequest versionsRequest = ListObjectVersionsRequest.builder() + .bucket(bucketName) + .build(); + + return getClient().listObjectVersions(versionsRequest); + } + + // snippet-start:[S3LockWorkflow.javav2.ModifyBucketDefaultRetention.main] + // Set or modify a retention period on an S3 bucket. + public void modifyBucketDefaultRetention(String bucketName) { + VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder() + .mfaDelete(MFADelete.DISABLED) + .status(BucketVersioningStatus.ENABLED) + .build(); + + PutBucketVersioningRequest versioningRequest = PutBucketVersioningRequest.builder() + .bucket(bucketName) + .versioningConfiguration(versioningConfiguration) + .build(); + + getClient().putBucketVersioning(versioningRequest); + DefaultRetention rention = DefaultRetention.builder() + .days(1) + .mode(ObjectLockRetentionMode.GOVERNANCE) + .build(); + + ObjectLockRule lockRule = ObjectLockRule.builder() + .defaultRetention(rention) + .build(); + + ObjectLockConfiguration objectLockConfiguration = ObjectLockConfiguration.builder() + .objectLockEnabled(ObjectLockEnabled.ENABLED) + .rule(lockRule) + .build(); + + PutObjectLockConfigurationRequest putObjectLockConfigurationRequest = PutObjectLockConfigurationRequest.builder() + .bucket(bucketName) + .objectLockConfiguration(objectLockConfiguration) + .build(); + + getClient().putObjectLockConfiguration(putObjectLockConfigurationRequest) ; + System.out.println("Added a default retention to bucket "+bucketName +"."); + } + // snippet-end:[S3LockWorkflow.javav2.ModifyBucketDefaultRetention.main] + + // snippet-start:[S3LockWorkflow.javav2.EnableObjectLockOnBucket.main] + // Enable object lock on an existing bucket. + public void enableObjectLockOnBucket(String bucketName) { + try { + VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder() + .status(BucketVersioningStatus.ENABLED) + .build(); + + PutBucketVersioningRequest putBucketVersioningRequest = PutBucketVersioningRequest.builder() + .bucket(bucketName) + .versioningConfiguration(versioningConfiguration) + .build(); + + // Enable versioning on the bucket. + getClient().putBucketVersioning(putBucketVersioningRequest); + PutObjectLockConfigurationRequest request = PutObjectLockConfigurationRequest.builder() + .bucket(bucketName) + .objectLockConfiguration(ObjectLockConfiguration.builder() + .objectLockEnabled(ObjectLockEnabled.ENABLED) + .build()) + .build(); + + getClient().putObjectLockConfiguration(request); + System.out.println("Successfully enabled object lock on "+bucketName); + + } catch (S3Exception ex) { + System.out.println("Error modifying object lock: '" + ex.getMessage() + "'"); + } + } + // snippet-end:[S3LockWorkflow.javav2.EnableObjectLockOnBucket.main] + + // snippet-start:[S3LockWorkflow.javav2.UploadFile.main] + public void uploadFile(String bucketName, String objectName, String filePath) { + Path file = Paths.get(filePath); + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucketName) + .key(objectName) + .checksumAlgorithm(ChecksumAlgorithm.SHA256) + .build(); + + PutObjectResponse response = getClient().putObject(request, file); + if (response != null) { + System.out.println("\tSuccessfully uploaded " + objectName + " to " + bucketName + "."); + } else { + System.out.println("\tCould not upload " + objectName + " to " + bucketName + "."); + } + } + // snippet-end:[S3LockWorkflow.javav2.UploadFile.main] + + // snippet-start:[S3LockWorkflow.javav2.ModifyObjectLegalHold.main] + // Set or modify a legal hold on an object in an S3 bucket. + public void modifyObjectLegalHold(String bucketName, String objectKey, boolean legalHoldOn) { + ObjectLockLegalHold legalHold ; + if (legalHoldOn) { + legalHold = ObjectLockLegalHold.builder() + .status(ObjectLockLegalHoldStatus.ON) + .build(); + } else { + legalHold = ObjectLockLegalHold.builder() + .status(ObjectLockLegalHoldStatus.OFF) + .build(); + } + + PutObjectLegalHoldRequest legalHoldRequest = PutObjectLegalHoldRequest.builder() + .bucket(bucketName) + .key(objectKey) + .legalHold(legalHold) + .build(); + + getClient().putObjectLegalHold(legalHoldRequest) ; + System.out.println("Modified legal hold for "+ objectKey +" in "+bucketName +"."); + } + // snippet-end:[S3LockWorkflow.javav2.ModifyObjectLegalHold.main] + + // snippet-start:[S3LockWorkflow.javav2.DeleteObjectFromBucket.main] + // Delete an object from a specific bucket. + public void deleteObjectFromBucket(String bucketName, String objectKey, boolean hasRetention, String versionId) { + try { + DeleteObjectRequest objectRequest; + if (hasRetention) { + objectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .versionId(versionId) + .bypassGovernanceRetention(true) + .build(); + } else { + objectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .versionId(versionId) + .build(); + } + + getClient().deleteObject(objectRequest) ; + System.out.println("The object was successfully deleted"); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + } + } + // snippet-end:[S3LockWorkflow.javav2.DeleteObjectFromBucket.main] + + // snippet-start:[S3LockWorkflow.javav2.GetObjectRetention.main] + // Get the retention period for an S3 object. + public ObjectLockRetention getObjectRetention(String bucketName, String key){ + try { + GetObjectRetentionRequest retentionRequest = GetObjectRetentionRequest.builder() + .bucket(bucketName) + .key(key) + .build(); + + GetObjectRetentionResponse response = getClient().getObjectRetention(retentionRequest); + System.out.println("tObject retention for "+key +" in "+ bucketName +": " + response.retention().mode() +" until "+ response.retention().retainUntilDate() +"."); + return response.retention(); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + return null; + } + } + // snippet-end:[S3LockWorkflow.javav2.GetObjectRetention.main] + + // snippet-start:[S3LockWorkflow.javav2.DeleteBucketByName.main] + public void deleteBucketByName(String bucketName) { + try { + DeleteBucketRequest request = DeleteBucketRequest.builder() + .bucket(bucketName) + .build(); + + getClient().deleteBucket(request); + System.out.println(bucketName +" was deleted."); + + } catch (S3Exception e) { + System.err.println(e.awsErrorDetails().errorMessage()); + } + } + // snippet-end:[S3LockWorkflow.javav2.DeleteBucketByName.main] + + // snippet-start:[S3LockWorkflow.javav2.GetBucketObjectLockConfiguration.main] + // Get the object lock configuration details for an S3 bucket. + public void getBucketObjectLockConfiguration(String bucketName) { + GetObjectLockConfigurationRequest objectLockConfigurationRequest = GetObjectLockConfigurationRequest.builder() + .bucket(bucketName) + .build(); + + GetObjectLockConfigurationResponse response = getClient().getObjectLockConfiguration(objectLockConfigurationRequest); + System.out.println("Bucket object lock config for "+bucketName +": "); + System.out.println("\tEnabled: "+response.objectLockConfiguration().objectLockEnabled()); + System.out.println("\tRule: "+ response.objectLockConfiguration().rule().defaultRetention()); + } + // snippet-end:[S3LockWorkflow.javav2.GetBucketObjectLockConfiguration.main] +} +// snippet-end:[S3LockWorkflow.javav2.S3ActionsWrapper.main] \ No newline at end of file diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3ObjectLockWorkflow.java b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3ObjectLockWorkflow.java new file mode 100644 index 00000000000..091b75dce40 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/main/java/com/example/s3/scenario/S3ObjectLockWorkflow.java @@ -0,0 +1,359 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.s3.scenario; + +// snippet-start:[S3LockWorkflow.javav2.ObjectLockWorkflow.main] +import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold; +import software.amazon.awssdk.services.s3.model.ObjectLockRetention; +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.stream.Collectors; + +/* + Before running this Java V2 code example, set up your development + environment, including your credentials. + + For more information, see the following documentation topic: + https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html + + This Java example performs the following tasks: + 1. Create test Amazon Simple Storage Service (S3) buckets with different lock policies. + 2. Upload sample objects to each bucket. + 3. Set some Legal Hold and Retention Periods on objects and buckets. + 4. Investigate lock policies by viewing settings or attempting to delete or overwrite objects. + 5. Clean up objects and buckets. + */ +public class S3ObjectLockWorkflow { + + static String bucketName; + private static final List bucketNames = new ArrayList<>(); + private static final List fileNames = new ArrayList<>(); + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + static S3LockActions s3LockActions; + + public static void main(String[] args) { + // Get the current date and time to ensure bucket name is unique. + LocalDateTime currentTime = LocalDateTime.now(); + + // Format the date and time as a string. + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + String timeStamp = currentTime.format(formatter); + + s3LockActions = new S3LockActions(); + bucketName = "bucket"+timeStamp; + Scanner scanner = new Scanner(System.in); + + System.out.println(DASHES); + System.out.println("Welcome to the Amazon Simple Storage Service (S3) Object Locking Workflow Scenario."); + System.out.println("Press Enter to continue..."); + scanner.nextLine(); + configurationSetup(); + System.out.println(DASHES); + + System.out.println(DASHES); + setup(); + System.out.println("Setup is complete. Press Enter to continue..."); + scanner.nextLine(); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("Lets present the user with choices."); + System.out.println("Press Enter to continue..."); + scanner.nextLine(); + demoActionChoices() ; + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("Would you like to clean up the resources? (y/n)"); + String delAns = scanner.nextLine().trim(); + if (delAns.equalsIgnoreCase("y")) { + cleanup(); + System.out.println("Clean up is complete."); + } + + System.out.println("Press Enter to continue..."); + scanner.nextLine(); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("Amazon S3 Object Locking Workflow is complete."); + System.out.println(DASHES); + } + + // Present the user with the demo action choices. + public static void demoActionChoices() { + String[] choices = { + "List all files in buckets.", + "Attempt to delete a file.", + "Attempt to delete a file with retention period bypass.", + "Attempt to overwrite a file.", + "View the object and bucket retention settings for a file.", + "View the legal hold settings for a file.", + "Finish the workflow." + }; + + int choice = 0; + while (true) { + System.out.println(DASHES); + choice = getChoiceResponse("Explore the S3 locking features by selecting one of the following choices:", choices); + System.out.println(DASHES); + System.out.println("You selected "+choices[choice]); + switch (choice) { + case 0 -> { + s3LockActions.listBucketsAndObjects(bucketNames, true); + } + + case 1 -> { + System.out.println("Enter the number of the object to delete:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = getChoiceResponse(null, fileKeysArray); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + String version = allFiles.get(fileChoice).getVersion(); + s3LockActions.deleteObjectFromBucket(bucketName, objectKey, false, version); + } + + case 2 -> { + System.out.println("Enter the number of the object to delete:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = getChoiceResponse(null, fileKeysArray); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + String version = allFiles.get(fileChoice).getVersion(); + s3LockActions.deleteObjectFromBucket(bucketName, objectKey, true, version); + } + + case 3 -> { + System.out.println("Enter the number of the object to overwrite:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = getChoiceResponse(null, fileKeysArray); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + + // Attempt to overwrite the file. + try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(objectKey))) { + writer.write("This is a modified text."); + + } catch (IOException e) { + e.printStackTrace(); + } + s3LockActions.uploadFile(bucketName, objectKey, objectKey); + } + + case 4 -> { + System.out.println("Enter the number of the object to overwrite:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = getChoiceResponse(null, fileKeysArray); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + s3LockActions.getObjectRetention(bucketName, objectKey); + } + + case 5 -> { + System.out.println("Enter the number of the object to view:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = getChoiceResponse(null, fileKeysArray); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + s3LockActions.getObjectLegalHold(bucketName, objectKey); + s3LockActions.getBucketObjectLockConfiguration(bucketName); + } + + case 6 -> { + System.out.println("Exiting the workflow..."); + return; + } + + default -> { + System.out.println("Invalid choice. Please select again."); + } + } + } + } + + // Clean up the resources from the scenario. + private static void cleanup() { + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, false); + for (S3InfoObject fileInfo : allFiles) { + String bucketName = fileInfo.getBucketName(); + String key = fileInfo.getKeyName(); + String version = fileInfo.getVersion(); + if (bucketName.contains("lock-enabled") || (bucketName.contains("retention-after-creation"))) { + ObjectLockLegalHold legalHold = s3LockActions.getObjectLegalHold(bucketName, key); + if (legalHold != null) { + String holdStatus = legalHold.status().name(); + System.out.println(holdStatus); + if (holdStatus.compareTo("ON") == 0) { + s3LockActions.modifyObjectLegalHold(bucketName, key, false); + } + } + // Check for a retention period. + ObjectLockRetention retention = s3LockActions.getObjectRetention(bucketName, key); + boolean hasRetentionPeriod ; + hasRetentionPeriod = retention != null; + s3LockActions.deleteObjectFromBucket(bucketName, key,hasRetentionPeriod, version); + + } else { + System.out.println(bucketName +" objects do not have a legal lock"); + s3LockActions.deleteObjectFromBucket(bucketName, key,false, version); + } + } + + // Delete the buckets. + System.out.println("Delete "+bucketName); + for (String bucket : bucketNames){ + s3LockActions.deleteBucketByName(bucket); + } + } + + private static void setup() { + Scanner scanner = new Scanner(System.in); + System.out.println(""" + For this workflow, we will use the AWS SDK for Java to create several S3 + buckets and files to demonstrate working with S3 locking features. + """); + + System.out.println("S3 buckets can be created either with or without object lock enabled."); + System.out.println("Press Enter to continue..."); + scanner.nextLine(); + + // Create three S3 buckets. + s3LockActions.createBucketWithLockOptions(false, bucketNames.get(0)); + s3LockActions.createBucketWithLockOptions(true, bucketNames.get(1)); + s3LockActions.createBucketWithLockOptions(false, bucketNames.get(2)); + System.out.println("Press Enter to continue."); + scanner.nextLine(); + + System.out.println("Bucket "+bucketNames.get(2) +" will be configured to use object locking with a default retention period."); + s3LockActions.modifyBucketDefaultRetention(bucketNames.get(2)); + System.out.println("Press Enter to continue."); + scanner.nextLine(); + + System.out.println("Object lock policies can also be added to existing buckets. For this example, we will use "+bucketNames.get(1)); + s3LockActions.enableObjectLockOnBucket(bucketNames.get(1)); + System.out.println("Press Enter to continue."); + scanner.nextLine(); + + // Upload some files to the buckets. + System.out.println("Now let's add some test files:"); + String fileName = "exampleFile.txt"; + int fileCount = 2; + try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(fileName))) { + writer.write("This is a sample file for uploading to a bucket."); + + } catch (IOException e) { + e.printStackTrace(); + } + + for (String bucketName : bucketNames){ + for (int i = 0; i < fileCount; i++) { + // Get the file name without extension. + String fileNameWithoutExtension = java.nio.file.Paths.get(fileName).getFileName().toString(); + int extensionIndex = fileNameWithoutExtension.lastIndexOf('.'); + if (extensionIndex > 0) { + fileNameWithoutExtension = fileNameWithoutExtension.substring(0, extensionIndex); + } + + // Create the numbered file names. + String numberedFileName = fileNameWithoutExtension + i + getFileExtension(fileName); + fileNames.add(numberedFileName); + s3LockActions.uploadFile(bucketName, numberedFileName, fileName); + } + } + + String question = null; + System.out.print("Press Enter to continue..."); + scanner.nextLine(); + System.out.println("Now we can set some object lock policies on individual files:"); + for (String bucketName : bucketNames) { + for (int i = 0; i < fileNames.size(); i++){ + + // No modifications to the objects in the first bucket. + if (!bucketName.equals(bucketNames.get(0))) { + String exampleFileName = fileNames.get(i); + switch (i) { + case 0 -> { + question = "Would you like to add a legal hold to " + exampleFileName + " in " + bucketName + " (y/n)?"; + System.out.println(question); + String ans = scanner.nextLine().trim(); + if (ans.equalsIgnoreCase("y")) { + System.out.println("**** You have selected to put a legal hold " + exampleFileName); + + // Set a legal hold. + s3LockActions.modifyObjectLegalHold(bucketName, exampleFileName, true); + } + } + case 1 -> { + """ + Would you like to add a 1 day Governance retention period to %s in %s (y/n)? + Reminder: Only a user with the s3:BypassGovernanceRetention permission will be able to delete this file or its bucket until the retention period has expired. + """.formatted(exampleFileName, bucketName); + System.out.println(question); + String ans2 = scanner.nextLine().trim(); + if (ans2.equalsIgnoreCase("y")) { + s3LockActions.modifyObjectRetentionPeriod(bucketName, exampleFileName); + } + } + } + } + } + } + } + + // Get file extension. + private static String getFileExtension(String fileName) { + int dotIndex = fileName.lastIndexOf('.'); + if (dotIndex > 0) { + return fileName.substring(dotIndex); + } + return ""; + } + + public static void configurationSetup() { + String noLockBucketName = bucketName + "-no-lock"; + String lockEnabledBucketName = bucketName + "-lock-enabled"; + String retentionAfterCreationBucketName = bucketName + "-retention-after-creation"; + bucketNames.add(noLockBucketName); + bucketNames.add(lockEnabledBucketName); + bucketNames.add(retentionAfterCreationBucketName); + } + + public static int getChoiceResponse(String question, String[] choices) { + Scanner scanner = new Scanner(System.in); + if (question != null) { + System.out.println(question); + for (int i = 0; i < choices.length; i++) { + System.out.println("\t" + (i + 1) + ". " + choices[i]); + } + } + + int choiceNumber = 0; + while (choiceNumber < 1 || choiceNumber > choices.length) { + String choice = scanner.nextLine(); + try { + choiceNumber = Integer.parseInt(choice); + } catch (NumberFormatException e) { + System.out.println("Invalid choice. Please enter a valid number."); + } + } + + return choiceNumber - 1; + } +} +// snippet-end:[S3LockWorkflow.javav2.ObjectLockWorkflow.main] \ No newline at end of file diff --git a/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/test/java/S3LockTest.java b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/test/java/S3LockTest.java new file mode 100644 index 00000000000..a6e3562d933 --- /dev/null +++ b/javav2/example_code/s3/scenarios/s3_object_lock_scenario/src/test/java/S3LockTest.java @@ -0,0 +1,261 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import com.example.s3.scenario.S3InfoObject; +import com.example.s3.scenario.S3LockActions; +import com.example.s3.scenario.S3ObjectLockWorkflow; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold; +import software.amazon.awssdk.services.s3.model.ObjectLockRetention; +import java.io.BufferedWriter; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + + +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class S3LockTest { + + private static String bucketName ; + private static S3LockActions s3LockActions = null ; + + private static final List fileNames = new ArrayList<>(); + + private static final List bucketNames = new ArrayList<>(); + + @BeforeAll + public static void setUp() throws IOException { + // Get the current date and time to ensure bucket name is unique. + LocalDateTime currentTime = LocalDateTime.now(); + + // Format the date and time as a string. + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + String timeStamp = currentTime.format(formatter); + + s3LockActions = new S3LockActions(); + bucketName = "bucket"+timeStamp; + } + + @Test + @Tag("weathertop") + @Tag("IntegrationTest") + @Order(1) + public void testLockScenario() throws InterruptedException { + System.out.println("Bucket name is "+bucketName); + configurationSetup(); + + // Create three S3 buckets. + s3LockActions.createBucketWithLockOptions(false, bucketNames.get(0)); + s3LockActions.createBucketWithLockOptions(true, bucketNames.get(1)); + s3LockActions.createBucketWithLockOptions(false, bucketNames.get(2)); + TimeUnit.SECONDS.sleep(3); + System.out.println("Bucket "+bucketNames.get(2) +" will be configured to use object locking with a default retention period."); + s3LockActions.modifyBucketDefaultRetention(bucketNames.get(2)); + System.out.println("Object lock policies can also be added to existing buckets. For this example, we will use "+bucketNames.get(1)); + s3LockActions.enableObjectLockOnBucket(bucketNames.get(1)); + System.out.println("Now let's add some test files:"); + String fileName = "exampleFile.txt"; + int fileCount = 2; + try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(fileName))) { + writer.write("This is a sample file for uploading to a bucket."); + + } catch (IOException e) { + e.printStackTrace(); + } + + for (String bucketName : bucketNames){ + for (int i = 0; i < fileCount; i++) { + String fileNameWithoutExtension = java.nio.file.Paths.get(fileName).getFileName().toString(); + int extensionIndex = fileNameWithoutExtension.lastIndexOf('.'); + if (extensionIndex > 0) { + fileNameWithoutExtension = fileNameWithoutExtension.substring(0, extensionIndex); + } + + String numberedFileName = fileNameWithoutExtension + i + getFileExtension(fileName); + fileNames.add(numberedFileName); + s3LockActions.uploadFile(bucketName, numberedFileName, fileName); + } + } + + System.out.println("Now we can set some object lock policies on individual files:"); + for (String bucketName : bucketNames) { + for (int i = 0; i < fileNames.size(); i++) { + + // No modifications to the objects in the first bucket. + if (!bucketName.equals(bucketNames.get(0))) { + String exampleFileName = fileNames.get(i); + switch (i) { + case 0 -> { + // Set a legal hold. + s3LockActions.modifyObjectLegalHold(bucketName, exampleFileName, true); + } + case 1 -> { + s3LockActions.modifyObjectRetentionPeriod(bucketName, exampleFileName); + } + } + } + } + } + + System.out.println("Setup is complete."); + TimeUnit.SECONDS.sleep(3); + + // Test some options in the code. + DemoActionChoices(0); + DemoActionChoices(6); + cleanup(); + } + + private static void configurationSetup() { + String noLockBucketName = bucketName + "-no-lock"; + String lockEnabledBucketName = bucketName + "-lock-enabled"; + String retentionAfterCreationBucketName = bucketName + "-retention-after-creation"; + + bucketNames.add(noLockBucketName); + bucketNames.add(lockEnabledBucketName); + bucketNames.add(retentionAfterCreationBucketName); + } + + private static String getFileExtension(String fileName) { + int dotIndex = fileName.lastIndexOf('.'); + if (dotIndex > 0) { + return fileName.substring(dotIndex); + } + return ""; + } + + private static void cleanup() { + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, false); + for (S3InfoObject fileInfo : allFiles) { + String bucketName = fileInfo.getBucketName(); + String key = fileInfo.getKeyName(); + String version = fileInfo.getVersion(); + if (bucketName.contains("lock-enabled") || (bucketName.contains("retention-after-creation"))) { + ObjectLockLegalHold legalHold = s3LockActions.getObjectLegalHold(bucketName, key); + if (legalHold != null) { + String holdStatus = legalHold.status().name(); + System.out.println(holdStatus); + if (holdStatus.compareTo("ON") == 0) { + s3LockActions.modifyObjectLegalHold(bucketName, key, false); + } + } + // Check for a retention period. + ObjectLockRetention retention = s3LockActions.getObjectRetention(bucketName, key); + boolean hasRetentionPeriod; + hasRetentionPeriod = retention != null; + s3LockActions.deleteObjectFromBucket(bucketName, key, hasRetentionPeriod, version); + + } else { + System.out.println(bucketName + " objects do not have a legal lock"); + s3LockActions.deleteObjectFromBucket(bucketName, key, false, version); + } + } + + // Delete the buckets. + System.out.println("Delete "+bucketName); + for (String bucket : bucketNames){ + s3LockActions.deleteBucketByName(bucket); + } + } + + public static void DemoActionChoices( int choice) { + switch (choice) { + case 0 -> { + s3LockActions.listBucketsAndObjects(bucketNames, true); + } + + case 1 -> { + System.out.println("Enter the number of the object to delete:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = 2; + System.out.println("You selected " + fileChoice); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + String version = allFiles.get(fileChoice).getVersion(); + s3LockActions.deleteObjectFromBucket(bucketName, objectKey, false, version); + } + + case 2 -> { + System.out.println("Enter the number that specifies a retention period to delete:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + int fileChoice = 2; + System.out.println("You selected " + fileChoice); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + String version = allFiles.get(fileChoice).getVersion(); + s3LockActions.deleteObjectFromBucket(bucketName, objectKey, false, version); + } + + case 3 -> { + System.out.println("Enter the number of the object to overwrite:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = S3ObjectLockWorkflow.getChoiceResponse(null, fileKeysArray); + System.out.println("You selected " + fileChoice); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + + // Attempt to overwrite the file + try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(objectKey))) { + writer.write("This is a modified text."); + + } catch (IOException e) { + e.printStackTrace(); + } + s3LockActions.uploadFile(bucketName, objectKey, objectKey); + } + + case 4 -> { + System.out.println("Enter the number of the object to overwrite:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = S3ObjectLockWorkflow.getChoiceResponse(null, fileKeysArray); + System.out.println("You selected " + fileChoice); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + s3LockActions.getObjectRetention(bucketName, objectKey); + } + + case 5 -> { + System.out.println("Enter the number of the object to view:"); + List allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true); + List fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList()); + String[] fileKeysArray = fileKeys.toArray(new String[0]); + int fileChoice = S3ObjectLockWorkflow.getChoiceResponse(null, fileKeysArray); + System.out.println("You selected " + fileChoice); + String objectKey = fileKeys.get(fileChoice); + String bucketName = allFiles.get(fileChoice).getBucketName(); + s3LockActions.getObjectLegalHold(bucketName, objectKey); + s3LockActions.getBucketObjectLockConfiguration(bucketName); + } + + case 6 -> { + System.out.println("Exiting the workflow..."); + return; + } + + default -> { + System.out.println("Invalid choice. Please select again."); + } + } + } +} + + +