I am creating an application where want to upload a file to S3 bucket. I am getting an error from following code snippet:
BasicAWSCredentials awsCreds = new BasicAWSCredentials("<myKey>", "<mySecretId>");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion("<myRegion>")
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
PutObjectRequest request = new PutObjectRequest("testbucketupdate", "testFile", new File("D:\\Attachments\\LICENSE"));
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("plain/text");
metadata.addUserMetadata("x-amz-meta-title", "someTitle");
request.setMetadata(metadata);
s3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).disableChunkedEncoding().build());
s3Client.putObject(request);
I am getting an error as:
Java.lang.UnsupportedOperationException: Client is immutable when created with the builder.
at com.amazonaws.AmazonWebServiceClient.checkMutability(AmazonWebServiceClient.java:937)
at com.amazonaws.services.s3.AmazonS3Client.setS3ClientOptions(AmazonS3Client.java:716)
at com.amazonaws.lambda.demo.LambdaFunctionHandler.check(LambdaFunctionHandler.java:123)
at com.amazonaws.lambda.demo.LambdaFunctionHandler.main(LambdaFunctionHandler.java:208)
at com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:51)
at com.amazonaws.lambda.demo.LambdaFunctionHandler.handleRequest(LambdaFunctionHandler.java:1)
at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:178)
at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:888)
at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:283)
at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:64)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:94)
What changes I should make to upload a file successfully to the required bucket?
Obviously the error says that if you use the AmazonS3ClientBuilder
to build a client, it will be immutable and you can't modify it after it is built.
The solution is to remove later s3Client.setS3ClientOptions(...)
and to set required options using the AmazonS3ClientBuilder
builder. Something along the lines:
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion("<myRegion>")
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.enablePathStyleAccess()
.disableChunkedEncoding()
.build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With