Closed
Description
Describe the issue
The second code snippet in the Javadoc contains an error.
// IamClient requires a dependency on software.amazon.awssdk:iam
try (IamClient iam = IamClient.builder().region(Region.AWS_GLOBAL).build()) {
String policyArn = "arn:aws:iam::123456789012:policy/AllowWriteBookMetadata";
GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn));
String policyVersion = getPolicyResponse.defaultVersionId();
GetPolicyVersionResponse getPolicyVersionResponse =
iam.getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion));
IamPolicy policy = IamPolicy.fromJson(getPolicyVersionResponse.policyVersion().document());
IamStatement newStatement = policy.statements().get(0).copy(s -> s.addAction("dynamodb:GetItem"));
IamPolicy newPolicy = policy.copy(p -> p.statements(Arrays.asList(newStatement)));
iam.createPolicy(r -> r.policyName("AllowReadWriteBookMetadata")
.policyDocument(newPolicy.toJson()));
}
The eighth line of the snippet:
IamPolicy policy = IamPolicy.fromJson(getPolicyVersionResponse.policyVersion().document());
does not work because getPolicyVersionResponse.policyVersion().document()
returns a URL-encoded string.
I needed to change it to the following for the example to work:
String decodedPolicy = URLDecoder.decode(getPolicyVersionResponse.policyVersion().document(), StandardCharsets.UTF_8);
IamPolicy policy = IamPolicy.fromJson(decodedPolicy);
Links
https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/policybuilder/iam/IamPolicy.html