|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package com.example.s3; |
| 5 | + |
| 6 | +// snippet-start:[presigned.java2.generatepresignedurlandputfilewithqueryparams.import] |
| 7 | +import com.example.s3.util.PresignUrlUtils; |
| 8 | +import org.slf4j.Logger; |
| 9 | +import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; |
| 10 | +import software.amazon.awssdk.core.internal.sync.FileContentStreamProvider; |
| 11 | +import software.amazon.awssdk.http.HttpExecuteRequest; |
| 12 | +import software.amazon.awssdk.http.HttpExecuteResponse; |
| 13 | +import software.amazon.awssdk.http.SdkHttpClient; |
| 14 | +import software.amazon.awssdk.http.SdkHttpMethod; |
| 15 | +import software.amazon.awssdk.http.SdkHttpRequest; |
| 16 | +import software.amazon.awssdk.http.apache.ApacheHttpClient; |
| 17 | +import software.amazon.awssdk.services.s3.S3Client; |
| 18 | +import software.amazon.awssdk.services.s3.model.PutObjectRequest; |
| 19 | +import software.amazon.awssdk.services.s3.presigner.S3Presigner; |
| 20 | +import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; |
| 21 | +import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; |
| 22 | + |
| 23 | +import java.io.File; |
| 24 | +import java.io.IOException; |
| 25 | +import java.net.URISyntaxException; |
| 26 | +import java.net.URL; |
| 27 | +import java.nio.file.Paths; |
| 28 | +import java.time.Duration; |
| 29 | +import java.util.Map; |
| 30 | +import java.util.UUID; |
| 31 | +// snippet-end:[presigned.java2.generatepresignedurlandputfilewithqueryparams.import] |
| 32 | + |
| 33 | +/** |
| 34 | + * Before running this Java V2 code example, set up your development environment. |
| 35 | + * <p> |
| 36 | + * For more information, see the following documentation topic: |
| 37 | + * <p> |
| 38 | + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html |
| 39 | + */ |
| 40 | + |
| 41 | +public class GeneratePresignedUrlAndPutFileWithQueryParams { |
| 42 | + private static final Logger logger = org.slf4j.LoggerFactory.getLogger(GeneratePresignedUrlAndPutFileWithQueryParams.class); |
| 43 | + private final static S3Client s3Client = S3Client.create(); |
| 44 | + |
| 45 | + public static void main(String[] args) { |
| 46 | + String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name. |
| 47 | + String keyName = "key" + UUID.randomUUID(); |
| 48 | + String resourcePath = "uploadDirectory/file1.txt"; |
| 49 | + // Uncomment the following two lines and comment out the previous two lines to use an image file instead of a PDF file. |
| 50 | + //String resourcePath = "image.png"; |
| 51 | + //String contentType = "image/png"; |
| 52 | + |
| 53 | + Map<String, String> queryParams = Map.of( |
| 54 | + "x-amz-meta-author", "Bob", |
| 55 | + "x-amz-meta-version", "1.0.0.0", |
| 56 | + "x-amz-acl", "private", |
| 57 | + "x-amz-server-side-encryption", "AES256" |
| 58 | + ); |
| 59 | + |
| 60 | + PresignUrlUtils.createBucket(bucketName, s3Client); |
| 61 | + GeneratePresignedUrlAndPutFileWithQueryParams presign = new GeneratePresignedUrlAndPutFileWithQueryParams(); |
| 62 | + try { |
| 63 | + String presignedUrlString = presign.createPresignedUrl(bucketName, keyName, queryParams); |
| 64 | + presign.useSdkHttpClientToPut(presignedUrlString, getFileForForClasspathResource(resourcePath)); |
| 65 | + |
| 66 | + } finally { |
| 67 | + PresignUrlUtils.deleteObject(bucketName, keyName, s3Client); |
| 68 | + PresignUrlUtils.deleteBucket(bucketName, s3Client); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // snippet-start:[presigned.java2.generatepresignedurlandputfilewithqueryparams.main] |
| 73 | + // snippet-start:[presigned.java2.generatepresignedurlandputfilewithqueryparams.createpresignedurl] |
| 74 | + /** |
| 75 | + * Creates a presigned URL to use in a subsequent HTTP PUT request. The code adds query parameters |
| 76 | + * to the request instead of using headers. By using query parameters, you do not need to add the |
| 77 | + * the parameters as headers when the PUT request is eventually sent. |
| 78 | + * |
| 79 | + * @param bucketName Bucket name where the object will be uploaded. |
| 80 | + * @param keyName Key name of the object that will be uploaded. |
| 81 | + * @param queryParams Query string parameters to be added to the presigned URL. |
| 82 | + * @return |
| 83 | + */ |
| 84 | + public String createPresignedUrl(String bucketName, String keyName, Map<String, String> queryParams) { |
| 85 | + try (S3Presigner presigner = S3Presigner.create()) { |
| 86 | + // Create an override configuration to store the query parameters. |
| 87 | + AwsRequestOverrideConfiguration.Builder overrideConfigurationBuilder = AwsRequestOverrideConfiguration.builder(); |
| 88 | + |
| 89 | + queryParams.forEach(overrideConfigurationBuilder::putRawQueryParameter); |
| 90 | + |
| 91 | + PutObjectRequest objectRequest = PutObjectRequest.builder() |
| 92 | + .bucket(bucketName) |
| 93 | + .key(keyName) |
| 94 | + .overrideConfiguration(overrideConfigurationBuilder.build()) // Add the override configuration. |
| 95 | + .build(); |
| 96 | + |
| 97 | + PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder() |
| 98 | + .signatureDuration(Duration.ofMinutes(10)) // The URL expires in 10 minutes. |
| 99 | + .putObjectRequest(objectRequest) |
| 100 | + .build(); |
| 101 | + |
| 102 | + |
| 103 | + PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest); |
| 104 | + String myURL = presignedRequest.url().toString(); |
| 105 | + logger.info("Presigned URL to upload a file to: [{}]", myURL); |
| 106 | + logger.info("HTTP method: [{}]", presignedRequest.httpRequest().method()); |
| 107 | + |
| 108 | + return presignedRequest.url().toExternalForm(); |
| 109 | + } |
| 110 | + } |
| 111 | + // snippet-end:[presigned.java2.generatepresignedurlandputfilewithqueryparams.createpresignedurl] |
| 112 | + |
| 113 | + // snippet-start:[presigned.java2.generatepresignedurlandputfilewithqueryparams.sdkhttpclient] |
| 114 | + /** |
| 115 | + * Use the AWS SDK for Java V2 SdkHttpClient class to execute the PUT request. Since the |
| 116 | + * URL contains the query parameters, no headers are needed for metadata, SSE settings, or ACL settings. |
| 117 | + * |
| 118 | + * @param presignedUrlString The URL for the PUT request. |
| 119 | + * @param fileToPut File to uplaod |
| 120 | + */ |
| 121 | + public void useSdkHttpClientToPut(String presignedUrlString, File fileToPut) { |
| 122 | + logger.info("Begin [{}] upload", fileToPut.toString()); |
| 123 | + |
| 124 | + try { |
| 125 | + URL presignedUrl = new URL(presignedUrlString); |
| 126 | + |
| 127 | + SdkHttpRequest.Builder requestBuilder = SdkHttpRequest.builder() |
| 128 | + .method(SdkHttpMethod.PUT) |
| 129 | + .uri(presignedUrl.toURI()); |
| 130 | + |
| 131 | + SdkHttpRequest request = requestBuilder.build(); |
| 132 | + |
| 133 | + HttpExecuteRequest executeRequest = HttpExecuteRequest.builder() |
| 134 | + .request(request) |
| 135 | + .contentStreamProvider(new FileContentStreamProvider(fileToPut.toPath())) |
| 136 | + .build(); |
| 137 | + |
| 138 | + try (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) { |
| 139 | + HttpExecuteResponse response = sdkHttpClient.prepareRequest(executeRequest).call(); |
| 140 | + logger.info("Response code: {}", response.httpResponse().statusCode()); |
| 141 | + } |
| 142 | + } catch (URISyntaxException | IOException e) { |
| 143 | + logger.error(e.getMessage(), e); |
| 144 | + } |
| 145 | + } |
| 146 | + // snippet-end:[presigned.java2.generatepresignedurlandputfilewithqueryparams.sdkhttpclient] |
| 147 | + // snippet-end:[presigned.java2.generatepresignedurlandputfilewithqueryparams.main] |
| 148 | + |
| 149 | + public static File getFileForForClasspathResource(String resourcePath) { |
| 150 | + try { |
| 151 | + URL resource = GeneratePresignedUrlAndUploadObject.class.getClassLoader().getResource(resourcePath); |
| 152 | + return Paths.get(resource.toURI()).toFile(); |
| 153 | + } catch (URISyntaxException e) { |
| 154 | + logger.error(e.getMessage(), e); |
| 155 | + } |
| 156 | + return null; |
| 157 | + } |
| 158 | +} |
0 commit comments