index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/AwsCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.internal.DefaultAwsCredentialsIdentity;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsSessionCredentialsIdentity
*/
@SdkPublicApi
@ThreadSafe
public interface AwsCredentialsIdentity extends Identity {
/**
* Retrieve the AWS access key, used to identify the user interacting with services.
*/
String accessKeyId();
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with services.
*/
String secretAccessKey();
static Builder builder() {
return DefaultAwsCredentialsIdentity.builder();
}
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with services.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with services.
*/
static AwsCredentialsIdentity create(String accessKeyId, String secretAccessKey) {
return builder().accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.build();
}
interface Builder {
/**
* The AWS access key, used to identify the user interacting with services.
*/
Builder accessKeyId(String accessKeyId);
/**
* The AWS secret access key, used to authenticate the user interacting with services.
*/
Builder secretAccessKey(String secretAccessKey);
AwsCredentialsIdentity build();
}
}
| 2,400 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/ResolveIdentityRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.internal.DefaultResolveIdentityRequest;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A request to resolve an {@link Identity}.
* <p>
* The Identity may be determined for each request based on properties of the request (e.g. different credentials per bucket
* for S3).
*
* @see IdentityProvider
*/
@SdkPublicApi
@Immutable
@ThreadSafe
public interface ResolveIdentityRequest extends ToCopyableBuilder<ResolveIdentityRequest.Builder, ResolveIdentityRequest> {
/**
* Get a new builder for creating a {@link ResolveIdentityRequest}.
*/
static Builder builder() {
return DefaultResolveIdentityRequest.builder();
}
/**
* Returns the value of a property that the {@link IdentityProvider} can use while resolving the identity.
*/
<T> T property(IdentityProperty<T> property);
/**
* A builder for a {@link ResolveIdentityRequest}.
*/
interface Builder extends CopyableBuilder<Builder, ResolveIdentityRequest> {
/**
* Set a property that the {@link IdentityProvider} can use while resolving the identity.
*/
<T> Builder putProperty(IdentityProperty<T> key, T value);
}
}
| 2,401 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/TokenIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Provides token which is used to securely authorize requests to services that use token based auth, e.g., OAuth.
*
* <p>For more details on OAuth tokens, see:
* <a href="https://oauth.net/2/access-tokens">
* https://oauth.net/2/access-tokens</a></p>
*/
@SdkPublicApi
@ThreadSafe
public interface TokenIdentity extends Identity {
/**
* Retrieves string field representing the literal token string.
*/
String token();
/**
* Constructs a new token object, which can be used to authorize requests to services that use token based auth
*
* @param token The token used to authorize requests.
*/
static TokenIdentity create(String token) {
Validate.paramNotNull(token, "token");
return new TokenIdentity() {
@Override
public String token() {
return token;
}
@Override
public String toString() {
return ToString.builder("TokenIdentity")
.add("token", token)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TokenIdentity that = (TokenIdentity) o;
return Objects.equals(token, that.token());
}
@Override
public int hashCode() {
return Objects.hashCode(token());
}
};
}
}
| 2,402 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultResolveIdentityRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.identity.spi.IdentityProperty;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.utils.ToString;
@SdkInternalApi
@Immutable
@ThreadSafe
public final class DefaultResolveIdentityRequest implements ResolveIdentityRequest {
private final Map<IdentityProperty<?>, Object> properties;
private DefaultResolveIdentityRequest(BuilderImpl builder) {
this.properties = new HashMap<>(builder.properties);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public <T> T property(IdentityProperty<T> property) {
return (T) properties.get(property);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public String toString() {
return ToString.builder("ResolveIdentityRequest")
.add("properties", properties)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultResolveIdentityRequest that = (DefaultResolveIdentityRequest) o;
return properties.equals(that.properties);
}
@Override
public int hashCode() {
return Objects.hashCode(properties);
}
@SdkInternalApi
public static final class BuilderImpl implements Builder {
private final Map<IdentityProperty<?>, Object> properties = new HashMap<>();
private BuilderImpl() {
}
private BuilderImpl(DefaultResolveIdentityRequest resolveIdentityRequest) {
this.properties.putAll(resolveIdentityRequest.properties);
}
public <T> Builder putProperty(IdentityProperty<T> key, T value) {
this.properties.put(key, value);
return this;
}
public ResolveIdentityRequest build() {
return new DefaultResolveIdentityRequest(this);
}
}
}
| 2,403 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultAwsSessionCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultAwsSessionCredentialsIdentity implements AwsSessionCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private final String sessionToken;
private DefaultAwsSessionCredentialsIdentity(Builder builder) {
this.accessKeyId = builder.accessKeyId;
this.secretAccessKey = builder.secretAccessKey;
this.sessionToken = builder.sessionToken;
Validate.paramNotNull(accessKeyId, "accessKeyId");
Validate.paramNotNull(secretAccessKey, "secretAccessKey");
Validate.paramNotNull(sessionToken, "sessionToken");
}
public static AwsSessionCredentialsIdentity.Builder builder() {
return new Builder();
}
@Override
public String accessKeyId() {
return accessKeyId;
}
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String sessionToken() {
return sessionToken;
}
@Override
public String toString() {
return ToString.builder("AwsSessionCredentialsIdentity")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsSessionCredentialsIdentity that = (AwsSessionCredentialsIdentity) o;
return Objects.equals(accessKeyId, that.accessKeyId()) &&
Objects.equals(secretAccessKey, that.secretAccessKey()) &&
Objects.equals(sessionToken, that.sessionToken());
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId);
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey);
hashCode = 31 * hashCode + Objects.hashCode(sessionToken);
return hashCode;
}
private static final class Builder implements AwsSessionCredentialsIdentity.Builder {
private String accessKeyId;
private String secretAccessKey;
private String sessionToken;
private Builder() {
}
@Override
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
@Override
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
@Override
public Builder sessionToken(String sessionToken) {
this.sessionToken = sessionToken;
return this;
}
@Override
public AwsSessionCredentialsIdentity build() {
return new DefaultAwsSessionCredentialsIdentity(this);
}
}
}
| 2,404 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultAwsCredentialsIdentity.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultAwsCredentialsIdentity implements AwsCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private DefaultAwsCredentialsIdentity(Builder builder) {
this.accessKeyId = builder.accessKeyId;
this.secretAccessKey = builder.secretAccessKey;
Validate.paramNotNull(accessKeyId, "accessKeyId");
Validate.paramNotNull(secretAccessKey, "secretAccessKey");
}
public static AwsCredentialsIdentity.Builder builder() {
return new Builder();
}
@Override
public String accessKeyId() {
return accessKeyId;
}
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String toString() {
return ToString.builder("AwsCredentialsIdentity")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsCredentialsIdentity that = (AwsCredentialsIdentity) o;
return Objects.equals(accessKeyId, that.accessKeyId()) &&
Objects.equals(secretAccessKey, that.secretAccessKey());
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId);
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey);
return hashCode;
}
private static final class Builder implements AwsCredentialsIdentity.Builder {
private String accessKeyId;
private String secretAccessKey;
private Builder() {
}
@Override
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
@Override
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
@Override
public AwsCredentialsIdentity build() {
return new DefaultAwsCredentialsIdentity(this);
}
}
}
| 2,405 |
0 | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi | Create_ds/aws-sdk-java-v2/core/identity-spi/src/main/java/software/amazon/awssdk/identity/spi/internal/DefaultIdentityProviders.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.identity.spi.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.IdentityProviders;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A default implementation of {@link IdentityProviders}. This implementation holds a map of {@link IdentityProvider}s and
* retrieves from the collection based on identity type.
*/
@Immutable
@SdkInternalApi
public final class DefaultIdentityProviders implements IdentityProviders {
/**
* TODO(sra-identity-auth): Currently, some customers assume we won't interact with the identity providers when we create
* the client. This isn't true - we need to call identityType. To TEMPORARILY work around those customer's tests failing,
* this is marked lazy. Once we fully migrate over to the SRA as the default code path, we should remove this lazy and
* ticket everyone in live who is making those bad assumptions.
*/
private final Lazy<Map<Class<?>, IdentityProvider<?>>> identityProviders;
private final List<IdentityProvider<?>> identityProvidersList;
private DefaultIdentityProviders(BuilderImpl builder) {
this.identityProvidersList = new ArrayList<>(builder.identityProviders);
this.identityProviders = new Lazy<>(() -> {
Map<Class<?>, IdentityProvider<?>> result = new HashMap<>();
for (IdentityProvider<?> identityProvider : identityProvidersList) {
result.put(identityProvider.identityType(), identityProvider);
}
return result;
});
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public <T extends Identity> IdentityProvider<T> identityProvider(Class<T> identityType) {
return (IdentityProvider<T>) identityProviders.getValue().get(identityType);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public String toString() {
return ToString.builder("IdentityProviders")
.add("identityProviders", identityProvidersList)
.build();
}
private static final class BuilderImpl implements Builder {
private final List<IdentityProvider<?>> identityProviders = new ArrayList<>();
private BuilderImpl() {
}
private BuilderImpl(DefaultIdentityProviders identityProviders) {
this.identityProviders.addAll(identityProviders.identityProvidersList);
}
@Override
public <T extends Identity> Builder putIdentityProvider(IdentityProvider<T> identityProvider) {
Validate.paramNotNull(identityProvider, "identityProvider");
identityProviders.add(identityProvider);
return this;
}
public IdentityProviders build() {
return new DefaultIdentityProviders(this);
}
}
}
| 2,406 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk/arns/ArnTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
public class ArnTest {
@Test
public void arnWithBasicResource_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("12345678910");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
System.out.println(arn.resource());
}
@Test
public void arnWithMinimalRequirementFromString() {
Arn arn = Arn.fromString("arn:aws:foobar:::myresource");
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("foobar");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arn_ParsesBackToString() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.toString()).isEqualTo(arnString);
}
@Test
public void arnWithQualifiedResource_ParsesBackToString() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar:1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.toString()).isEqualTo(arnString);
assertThat(arn.resourceAsString()).isEqualTo("myresource:foobar:1");
}
@Test
public void arnWithResourceTypeAndResource_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket:foobar";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar");
verifyArnResource(arn.resource());
}
private void verifyArnResource(ArnResource arnResource) {
assertThat(arnResource.resource()).isEqualTo("foobar");
assertThat(arnResource.resourceType()).isPresent();
assertThat(arnResource.resourceType().get()).isEqualTo("bucket");
}
@Test
public void arnWithResourceTypeAndResourceAndQualifier_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket:foobar:1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar:1");
ArnResource arnResource = arn.resource();
verifyArnResource(arnResource);
assertThat(arnResource.qualifier()).isPresent();
assertThat(arnResource.qualifier().get()).isEqualTo("1");
}
@Test
public void arnWithResourceTypeAndResource_SlashSplitter_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket/foobar";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket/foobar");
verifyArnResource(arn.resource());
}
@Test
public void arnWithResourceTypeAndResourceAndQualifier_SlashSplitter_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:bucket/foobar/1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.resourceAsString()).isEqualTo("bucket/foobar/1");
verifyArnResource(arn.resource());
assertThat(arn.resource().qualifier().get()).isEqualTo("1");
}
@Test
public void oneArnEqualsEquivalentArn() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar";
Arn arn1 = Arn.fromString(arnString);
Arn arn2 = Arn.fromString(arnString);
assertThat(arn1).isEqualTo(arn2);
assertThat(arn1.resource()).isEqualTo(arn2.resource());
}
@Test
public void arnFromBuilder_ParsesCorrectly() {
Arn arn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo("bucket:foobar:1");
verifyArnResource(arn.resource());
assertThat(arn.resource().qualifier()).isPresent();
assertThat(arn.resource().qualifier().get()).isEqualTo("1");
}
@Test
public void arnResourceWithColonAndSlash_ParsesOnFirstSplitter() {
String resourceWithColonAndSlash = "object:foobar/myobjectname:1";
Arn arn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource(resourceWithColonAndSlash)
.build();
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo(resourceWithColonAndSlash);
assertThat(arn.resource().resource()).isEqualTo("foobar/myobjectname");
assertThat(arn.resource().qualifier()).hasValue("1");
assertThat(arn.resource().resourceType()).hasValue("object");
}
@Test
public void arnWithoutRegion_ParsesCorrectly() {
String arnString = "arn:aws:s3::123456789012:myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).isEmpty();
assertThat(arn.accountId()).hasValue("123456789012");
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arnWithoutAccountId_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1::myresource";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).isEmpty();
assertThat(arn.resourceAsString()).isEqualTo("myresource");
}
@Test
public void arnResourceContainingDots_ParsesCorrectly() {
String arnString = "arn:aws:s3:us-east-1:12345678910:myresource:foobar.1";
Arn arn = Arn.fromString(arnString);
assertThat(arn.partition()).isEqualTo("aws");
assertThat(arn.service()).isEqualTo("s3");
assertThat(arn.region()).hasValue("us-east-1");
assertThat(arn.accountId()).hasValue("12345678910");
assertThat(arn.resourceAsString()).isEqualTo("myresource:foobar.1");
}
@Test
public void toBuilder() {
Arn oneArn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
Arn anotherArn = oneArn.toBuilder().build();
assertThat(oneArn).isEqualTo(anotherArn);
assertThat(oneArn.hashCode()).isEqualTo(anotherArn.hashCode());
}
@Test
public void hashCodeEquals() {
Arn oneArn = Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket:foobar:1")
.build();
Arn anotherArn = oneArn.toBuilder().region("somethingelse").build();
assertThat(oneArn).isNotEqualTo(anotherArn);
assertThat(oneArn.hashCode()).isNotEqualTo(anotherArn.hashCode());
}
@Test
public void hashCodeEquals_minimalProperties() {
Arn arn = Arn.builder()
.partition("aws")
.service("foobar")
.resource("resource")
.build();
Arn anotherArn = arn.toBuilder().build();
assertThat(arn.hashCode()).isEqualTo(anotherArn.hashCode());
assertThat(arn.region()).isEmpty();
assertThat(arn.accountId()).isEmpty();
assertThat(arn.equals(anotherArn)).isTrue();
}
@Test
public void arnWithoutPartition_ThrowsIllegalArgumentException() {
String arnString = "arn::s3:us-east-1:12345678910:myresource";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("artition must not be blank or empty.");
}
@Test
public void arnWithoutService_ThrowsIllegalArgumentException() {
String arnString = "arn:aws::us-east-1:12345678910:myresource";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("service must not be blank or empty");
}
@Test
public void arnWithoutResource_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:us-east-1:12345678910:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArn_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void arnDoesntStartWithArn_ThrowsIllegalArgumentException() {
String arnString = "fakearn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutPartition_ThrowsIllegalArgumentException() {
String arnString = "arn:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutService_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutRegion_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
@Test
public void invalidArnWithoutAccountId_ThrowsIllegalArgumentException() {
String arnString = "arn:aws:s3:us-east-1:";
assertThatThrownBy(() -> Arn.fromString(arnString)).hasMessageContaining("Malformed ARN");
}
}
| 2,407 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/test/java/software/amazon/awssdk/arns/ArnResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class ArnResourceTest {
@Test
public void toBuilder() {
ArnResource oneResource = ArnResource.fromString("bucket:foobar:1");
ArnResource anotherResource = oneResource.toBuilder().build();
assertThat(oneResource).isEqualTo(anotherResource);
assertThat(oneResource.hashCode()).isEqualTo(anotherResource.hashCode());
}
@Test
public void hashCodeEquals() {
ArnResource oneResource = ArnResource.fromString("bucket:foobar:1");
ArnResource anotherResource = oneResource.toBuilder().qualifier("test").build();
assertThat(oneResource).isNotEqualTo(anotherResource);
assertThat(oneResource.hashCode()).isNotEqualTo(anotherResource.hashCode());
}
@Test
public void arnResource_nullResource_shouldThrowException() {
assertThatThrownBy(() -> ArnResource.builder()
.build()).hasMessageContaining("resource must not be null.");
}
@Test
public void arnResourceFromBuilder_shouldParseCorrectly() {
ArnResource arnResource = ArnResource.builder()
.resource("bucket:foobar:1")
.resourceType("foobar")
.qualifier("1").build();
assertThat(arnResource.qualifier()).isEqualTo(Optional.of("1"));
assertThat(arnResource.resourceType()).isEqualTo(Optional.of("foobar"));
assertThat(arnResource.resource()).isEqualTo("bucket:foobar:1");
}
@Test
public void hashCodeEquals_minimalProperties() {
ArnResource arnResource = ArnResource.builder().resource("resource").build();
ArnResource anotherResource = arnResource.toBuilder().build();
assertThat(arnResource.equals(anotherResource)).isTrue();
assertThat(arnResource.hashCode()).isEqualTo(anotherResource.hashCode());
}
}
| 2,408 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk/arns/Arn.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* The Arns generated and recognized by this code are the Arns described here:
*
* https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
*
* <p>
* The primary supported Arn format is:
*
* <code>
* arn:<partition>:<service>:<region>:<account>:<resource>
* </code>
*
* <p>
* {@link #resourceAsString()} returns everything after the account section of the Arn
* as a single string.
*
* <p>
* However, the following Arn formats are supported where the values are present and well
* formatted through {@link #resource()}:
*
* <pre>
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource/qualifier
* arn:<partition>:<service>:<region>:<account>:<resourcetype>/resource:qualifier
* arn:<partition>:<service>:<region>:<account>:<resourcetype>:resource
* arn:<partition>:<service>:<region>:<account>:<resourcetype>:resource:qualifier
* </pre>
*
* {@link #resource()} returns a {@link ArnResource} which has access
* to {@link ArnResource#resourceType()}, {@link ArnResource#resource()} and
* {@link ArnResource#qualifier()}.
*
* <p>
* To parse an Arn from a string use Arn.fromString(). To convert an Arn to it's
* string representation use Arn.toString().
*
* <p>
* For instance, for a string s, containing a well-formed Arn the
* following should always be true:
*
* <pre>
* Arn theArn = Arn.fromString(s);
* s.equals(theArn.toString());
* </pre>
*
* @see ArnResource
*/
@SdkPublicApi
public final class Arn implements ToCopyableBuilder<Arn.Builder, Arn> {
private final String partition;
private final String service;
private final String region;
private final String accountId;
private final String resource;
private final ArnResource arnResource;
private Arn(DefaultBuilder builder) {
this.partition = Validate.paramNotBlank(builder.partition, "partition");
this.service = Validate.paramNotBlank(builder.service, "service");
this.region = builder.region;
this.accountId = builder.accountId;
this.resource = Validate.paramNotBlank(builder.resource, "resource");
this.arnResource = ArnResource.fromString(resource);
}
/**
* @return The partition that the resource is in.
*/
public String partition() {
return partition;
}
/**
* @return The service namespace that identifies the AWS product (for example, Amazon S3, IAM, or Amazon RDS).
*/
public String service() {
return service;
}
/**
* @return The Region that the resource resides in.
*/
public Optional<String> region() {
return StringUtils.isEmpty(region) ? Optional.empty() : Optional.of(region);
}
/**
* @return The ID of the AWS account that owns the resource, without the hyphens.
*/
public Optional<String> accountId() {
return StringUtils.isEmpty(accountId) ? Optional.empty() : Optional.of(accountId);
}
/**
* @return {@link ArnResource}
*/
public ArnResource resource() {
return arnResource;
}
/**
* @return the resource as string
*/
public String resourceAsString() {
return resource;
}
/**
* @return a builder for {@link Arn}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Parses a given string into an {@link Arn}. The resource is accessible entirely as a
* string through {@link #resourceAsString()}. Where correctly formatted, a parsed
* resource containing resource type, resource and qualifier is available through
* {@link #resource()}.
*
* @param arn - A string containing an Arn.
* @return {@link Arn} - A modeled Arn.
*/
public static Arn fromString(String arn) {
int arnColonIndex = arn.indexOf(':');
if (arnColonIndex < 0 || !"arn".equals(arn.substring(0, arnColonIndex))) {
throw new IllegalArgumentException("Malformed ARN - doesn't start with 'arn:'");
}
int partitionColonIndex = arn.indexOf(':', arnColonIndex + 1);
if (partitionColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS partition specified");
}
String partition = arn.substring(arnColonIndex + 1, partitionColonIndex);
int serviceColonIndex = arn.indexOf(':', partitionColonIndex + 1);
if (serviceColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no service specified");
}
String service = arn.substring(partitionColonIndex + 1, serviceColonIndex);
int regionColonIndex = arn.indexOf(':', serviceColonIndex + 1);
if (regionColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS region partition specified");
}
String region = arn.substring(serviceColonIndex + 1, regionColonIndex);
int accountColonIndex = arn.indexOf(':', regionColonIndex + 1);
if (accountColonIndex < 0) {
throw new IllegalArgumentException("Malformed ARN - no AWS account specified");
}
String accountId = arn.substring(regionColonIndex + 1, accountColonIndex);
String resource = arn.substring(accountColonIndex + 1);
if (resource.isEmpty()) {
throw new IllegalArgumentException("Malformed ARN - no resource specified");
}
return Arn.builder()
.partition(partition)
.service(service)
.region(region)
.accountId(accountId)
.resource(resource)
.build();
}
@Override
public String toString() {
return "arn:"
+ this.partition
+ ":"
+ this.service
+ ":"
+ region
+ ":"
+ this.accountId
+ ":"
+ this.resource;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Arn arn = (Arn) o;
if (!Objects.equals(partition, arn.partition)) {
return false;
}
if (!Objects.equals(service, arn.service)) {
return false;
}
if (!Objects.equals(region, arn.region)) {
return false;
}
if (!Objects.equals(accountId, arn.accountId)) {
return false;
}
if (!Objects.equals(resource, arn.resource)) {
return false;
}
return Objects.equals(arnResource, arn.arnResource);
}
@Override
public int hashCode() {
int result = partition.hashCode();
result = 31 * result + service.hashCode();
result = 31 * result + (region != null ? region.hashCode() : 0);
result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
result = 31 * result + resource.hashCode();
return result;
}
@Override
public Builder toBuilder() {
return builder().accountId(accountId)
.partition(partition)
.region(region)
.resource(resource)
.service(service)
;
}
/**
* A builder for a {@link Arn}. See {@link #builder()}.
*/
public interface Builder extends CopyableBuilder<Builder, Arn> {
/**
* Define the partition that the resource is in.
*
* @param partition the partition that the resource is in
* @return Returns a reference to this builder
*/
Builder partition(String partition);
/**
* Define the service name that identifies the AWS product
*
* @param service The service name that identifies the AWS product
* @return Returns a reference to this builder
*/
Builder service(String service);
/**
* Define the Region that the resource resides in.
*
* @param region The Region that the resource resides in.
* @return Returns a reference to this builder
*/
Builder region(String region);
/**
* Define the ID of the AWS account that owns the resource, without the hyphens.
*
* @param accountId The ID of the AWS account that owns the resource, without the hyphens.
* @return Returns a reference to this builder
*/
Builder accountId(String accountId);
/**
* Define the resource identifier. A resource identifier can be the name or ID of the resource
* or a resource path.
*
* @param resource resource identifier
* @return Returns a reference to this builder
*/
Builder resource(String resource);
/**
* @return an instance of {@link Arn} that is created from the builder
*/
@Override
Arn build();
}
private static final class DefaultBuilder implements Builder {
private String partition;
private String service;
private String region;
private String accountId;
private String resource;
private DefaultBuilder() {
}
public void setPartition(String partition) {
this.partition = partition;
}
@Override
public Builder partition(String partition) {
setPartition(partition);
return this;
}
public void setService(String service) {
this.service = service;
}
@Override
public Builder service(String service) {
setService(service);
return this;
}
public void setRegion(String region) {
this.region = region;
}
@Override
public Builder region(String region) {
setRegion(region);
return this;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
@Override
public Builder accountId(String accountId) {
setAccountId(accountId);
return this;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Builder resource(String resource) {
setResource(resource);
return this;
}
@Override
public Arn build() {
return new Arn(this);
}
}
}
| 2,409 |
0 | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/arns/src/main/java/software/amazon/awssdk/arns/ArnResource.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.arns;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An additional model within {@link Arn} that provides the Resource Type, Resource, and
* Resource Qualifier of an AWS Arn when those values are present and correctly formatted
* within an Arn.
*
* <p>
* If {@link #resourceType} is not present, {@link #resource} will return the entire resource
* as a string the same as {@link Arn#resource()}.
*
* @see Arn
*/
@SdkPublicApi
public final class ArnResource implements ToCopyableBuilder<ArnResource.Builder, ArnResource> {
private final String resourceType;
private final String resource;
private final String qualifier;
private ArnResource(DefaultBuilder builder) {
this.resourceType = builder.resourceType;
this.resource = Validate.paramNotBlank(builder.resource, "resource");
this.qualifier = builder.qualifier;
}
/**
* @return the optional resource type
*/
public Optional<String> resourceType() {
return Optional.ofNullable(resourceType);
}
/**
* @return the entire resource as a string
*/
public String resource() {
return resource;
}
/**
* @return the optional resource qualifier
*/
public Optional<String> qualifier() {
return Optional.ofNullable(qualifier);
}
/**
* @return a builder for {@link ArnResource}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Parses a string containing either a resource, resource type and resource or
* resource type, resource and qualifier into an {@link ArnResource}.
*
* <p>
* Supports fields separated by either ":" or "/".
*
* <p>
* For legacy AWS Arns not following the resourceType:resource:qualifier pattern,
* the qualifier field will contain everything after the first two sections separated
* by either ":" or "/".
*
* @param resource - The resource string to parse.
* @return {@link ArnResource}
*/
public static ArnResource fromString(String resource) {
Character splitter = StringUtils.findFirstOccurrence(resource, ':', '/');
if (splitter == null) {
return ArnResource.builder().resource(resource).build();
}
int resourceTypeColonIndex = resource.indexOf(splitter);
ArnResource.Builder builder = ArnResource.builder().resourceType(resource.substring(0, resourceTypeColonIndex));
int resourceColonIndex = resource.indexOf(splitter, resourceTypeColonIndex);
int qualifierColonIndex = resource.indexOf(splitter, resourceColonIndex + 1);
if (qualifierColonIndex < 0) {
builder.resource(resource.substring(resourceTypeColonIndex + 1));
} else {
builder.resource(resource.substring(resourceTypeColonIndex + 1, qualifierColonIndex));
builder.qualifier(resource.substring(qualifierColonIndex + 1));
}
return builder.build();
}
@Override
public String toString() {
return this.resourceType
+ ":"
+ this.resource
+ ":"
+ this.qualifier;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArnResource that = (ArnResource) o;
if (!Objects.equals(resourceType, that.resourceType)) {
return false;
}
if (!Objects.equals(resource, that.resource)) {
return false;
}
return Objects.equals(qualifier, that.qualifier);
}
@Override
public int hashCode() {
int result = resourceType != null ? resourceType.hashCode() : 0;
result = 31 * result + (resource != null ? resource.hashCode() : 0);
result = 31 * result + (qualifier != null ? qualifier.hashCode() : 0);
return result;
}
@Override
public Builder toBuilder() {
return builder()
.resource(resource)
.resourceType(resourceType)
.qualifier(qualifier);
}
public interface Builder extends CopyableBuilder<ArnResource.Builder, ArnResource> {
/**
* Define the type of the resource.
*
* @param resourceType the partition that the resource is in
* @return Returns a reference to this builder
*/
Builder resourceType(String resourceType);
/**
* Define the entire resource.
*
* @param resource the entire resource
* @return Returns a reference to this builder
*/
Builder resource(String resource);
/**
* Define the qualifier of the resource.
*
* @param qualifier the qualifier of the resource
* @return Returns a reference to this builder
*/
Builder qualifier(String qualifier);
/**
* @return an instance of {@link ArnResource} that is created from the builder
*/
@Override
ArnResource build();
}
public static final class DefaultBuilder implements Builder {
private String resourceType;
private String resource;
private String qualifier;
private DefaultBuilder() {
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
@Override
public Builder resourceType(String resourceType) {
setResourceType(resourceType);
return this;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public Builder resource(String resource) {
setResource(resource);
return this;
}
public void setQualifier(String qualifier) {
this.qualifier = qualifier;
}
@Override
public Builder qualifier(String qualifier) {
setQualifier(qualifier);
return this;
}
@Override
public ArnResource build() {
return new ArnResource(this);
}
}
} | 2,410 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/ProfileFileSupplierTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAmount;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringInputStream;
class ProfileFileSupplierTest {
private static FileSystem jimfs;
private static Path testDirectory;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
testDirectory = jimfs.getPath("test");
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void get_profileFileFixed_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = builder()
.fixedProfileFile(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
ProfileFile file2 = supplier.get();
assertThat(file2).isSameAs(file1);
}
@Test
void get_profileModifiedWithinJitterPeriod_doesNotReloadCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
Duration durationWithinJitter = Duration.ofMillis(10);
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plus(durationWithinJitter));
clock.tickForward(durationWithinJitter);
ProfileFile file2 = supplier.get();
assertThat(file2).isSameAs(file1);
}
@Test
void get_profileModifiedOutsideJitterPeriod_reloadsCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration durationOutsideJitter = Duration.ofSeconds(1);
supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plus(durationOutsideJitter));
clock.tickForward(durationOutsideJitter);
Optional<Profile> fileOptional = supplier.get().profile("default");
assertThat(fileOptional).isPresent();
assertThat(fileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("modifiedAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("modifiedSecretAccessKey");
});
}
@Test
void get_profileModified_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration duration = Duration.ofSeconds(10);
ProfileFile file1 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file2 = supplier.get();
assertThat(file2).isNotSameAs(file1);
}
@Test
void get_profileModifiedOnceButRefreshedMultipleTimes_reloadsProfileFileOnce() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
ProfileFile file1 = supplier.get();
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file2 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file3 = supplier.get();
assertThat(file2).isSameAs(file1);
assertThat(file3).isNotSameAs(file2);
}
@Test
void get_profileModifiedMultipleTimes_reloadsProfileFileOncePerChange() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = supplier.get();
clock.tickForward(duration);
ProfileFile file2 = supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = supplier.get();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = supplier.get();
clock.tickForward(duration);
ProfileFile file5 = supplier.get();
assertThat(file2).isSameAs(file1);
assertThat(file3).isNotSameAs(file2);
assertThat(file4).isNotSameAs(file3);
assertThat(file5).isSameAs(file4);
}
@Test
void get_supplierBuiltByReloadWhenModified_loadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS);
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void get_supplierBuiltByFixedProfileFile_returnsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(credentialsFilePath)
.type(ProfileFile.Type.CREDENTIALS)
.build());
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
});
}
@Test
void get_supplierBuiltByReloadWhenModifiedAggregate_reloadsCredentials() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
Path configFilePath = generateTestConfigFile(Pair.of("region", "us-west-2"));
ProfileFileSupplier credentialsProfileFileSupplier = ProfileFileSupplier.reloadWhenModified(credentialsFilePath,
ProfileFile.Type.CREDENTIALS);
ProfileFileSupplier configProfileFileSupplier = ProfileFileSupplier.reloadWhenModified(configFilePath,
ProfileFile.Type.CONFIGURATION);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(credentialsProfileFileSupplier, configProfileFileSupplier);
Optional<Profile> fileOptional = supplier.get().profile("default");
assertThat(fileOptional).isPresent();
assertThat(fileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
Optional<String> regionOptional = profile.property("region");
assertThat(regionOptional).isPresent();
String region = regionOptional.get();
assertThat(region).isEqualTo("us-west-2");
});
}
@Test
void get_supplierBuiltByFixedProfileFileAggregate_returnsAggregateProfileFileInstance() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
Path configFilePath = generateTestConfigFile(Pair.of("region", "us-west-2"));
ProfileFileSupplier credentialsProfileFileSupplier
= ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(credentialsFilePath)
.type(ProfileFile.Type.CREDENTIALS)
.build());
ProfileFileSupplier configProfileFileSupplier
= ProfileFileSupplier.fixedProfileFile(ProfileFile.builder()
.content(configFilePath)
.type(ProfileFile.Type.CONFIGURATION)
.build());
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(credentialsProfileFileSupplier, configProfileFileSupplier);
ProfileFile file = supplier.get();
Optional<Profile> profileOptional = file.profile("default");
assertThat(profileOptional).isPresent();
assertThat(profileOptional.get()).satisfies(profile -> {
Optional<String> awsAccessKeyIdOptional = profile.property("aws_access_key_id");
assertThat(awsAccessKeyIdOptional).isPresent();
String awsAccessKeyId = awsAccessKeyIdOptional.get();
assertThat(awsAccessKeyId).isEqualTo("defaultAccessKey");
Optional<String> awsSecretAccessKeyOptional = profile.property("aws_secret_access_key");
assertThat(awsSecretAccessKeyOptional).isPresent();
String awsSecretAccessKey = awsSecretAccessKeyOptional.get();
assertThat(awsSecretAccessKey).isEqualTo("defaultSecretAccessKey");
Optional<String> regionOptional = profile.property("region");
assertThat(regionOptional).isPresent();
String region = regionOptional.get();
assertThat(region).isEqualTo("us-west-2");
});
}
@Test
void aggregate_supplierReturnsSameInstanceMultipleTimesAggregatingProfileFile_aggregatesOnlyDistinctInstances() {
ProfileFile credentialFile1 = credentialFile("test1", "key1", "secret1");
ProfileFile credentialFile2 = credentialFile("test2", "key2", "secret2");
ProfileFile credentialFile3 = credentialFile("test3", "key3", "secret3");
ProfileFile credentialFile4 = credentialFile("test4", "key4", "secret4");
ProfileFile configFile = configFile("profile test", Pair.of("region", "us-west-2"));
List<ProfileFile> orderedCredentialsFiles
= Arrays.asList(credentialFile1, credentialFile1, credentialFile2, credentialFile3, credentialFile3, credentialFile4,
credentialFile4, credentialFile4);
ProfileFile aggregateFile1 = ProfileFile.aggregator().addFile(credentialFile1).addFile(configFile).build();
ProfileFile aggregateFile2 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile).build();
ProfileFile aggregateFile3 = ProfileFile.aggregator().addFile(credentialFile3).addFile(configFile).build();
ProfileFile aggregateFile4 = ProfileFile.aggregator().addFile(credentialFile4).addFile(configFile).build();
List<ProfileFile> distinctAggregateFiles = Arrays.asList(aggregateFile1, aggregateFile2, aggregateFile3, aggregateFile4);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(supply(orderedCredentialsFiles), () -> configFile);
List<ProfileFile> suppliedProfileFiles = Stream.generate(supplier)
.limit(orderedCredentialsFiles.size())
.filter(uniqueInstances())
.collect(Collectors.toList());
assertThat(suppliedProfileFiles).isEqualTo(distinctAggregateFiles);
}
@Test
void aggregate_supplierReturnsSameInstanceMultipleTimesAggregatingProfileFileSupplier_aggregatesOnlyDistinctInstances() {
ProfileFile credentialFile1 = credentialFile("test1", "key1", "secret1");
ProfileFile credentialFile2 = credentialFile("test2", "key2", "secret2");
ProfileFile credentialFile3 = credentialFile("test3", "key3", "secret3");
ProfileFile credentialFile4 = credentialFile("test4", "key4", "secret4");
ProfileFile configFile1 = configFile("profile test", Pair.of("region", "us-west-1"));
ProfileFile configFile2 = configFile("profile test", Pair.of("region", "us-west-2"));
ProfileFile configFile3 = configFile("profile test", Pair.of("region", "us-west-3"));
List<ProfileFile> orderedCredentialsFiles
= Arrays.asList(credentialFile1, credentialFile1, credentialFile2, credentialFile2, credentialFile3,
credentialFile4, credentialFile4, credentialFile4);
List<ProfileFile> orderedConfigFiles
= Arrays.asList(configFile1, configFile1, configFile1, configFile2, configFile3, configFile3, configFile3,
configFile3);
ProfileFile aggregateFile11 = ProfileFile.aggregator().addFile(credentialFile1).addFile(configFile1).build();
ProfileFile aggregateFile21 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile1).build();
ProfileFile aggregateFile22 = ProfileFile.aggregator().addFile(credentialFile2).addFile(configFile2).build();
ProfileFile aggregateFile33 = ProfileFile.aggregator().addFile(credentialFile3).addFile(configFile3).build();
ProfileFile aggregateFile43 = ProfileFile.aggregator().addFile(credentialFile4).addFile(configFile3).build();
List<ProfileFile> aggregateProfileFiles
= Arrays.asList(aggregateFile11, aggregateFile11, aggregateFile21, aggregateFile22, aggregateFile33,
aggregateFile43, aggregateFile43, aggregateFile43);
List<ProfileFile> distinctAggregateProfileFiles
= Arrays.asList(aggregateFile11, aggregateFile21, aggregateFile22, aggregateFile33, aggregateFile43);
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(supply(orderedCredentialsFiles), supply(orderedConfigFiles));
List<ProfileFile> suppliedProfileFiles = Stream.generate(supplier)
.filter(Objects::nonNull)
.limit(aggregateProfileFiles.size())
.filter(uniqueInstances())
.collect(Collectors.toList());
assertThat(suppliedProfileFiles).isEqualTo(distinctAggregateProfileFiles);
}
@Test
void aggregate_duplicateOptionsGivenFixedProfileFirst_preservesPrecedence() {
ProfileFile configFile1 = configFile("profile default", Pair.of("aws_access_key_id", "config-key"));
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(
ProfileFileSupplier.fixedProfileFile(configFile1),
ProfileFileSupplier.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS));
ProfileFile profileFile = supplier.get();
String accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("config-key");
generateTestCredentialsFile("defaultAccessKey2", "defaultSecretAccessKey2");
profileFile = supplier.get();
accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("config-key");
}
@Test
void aggregate_duplicateOptionsGivenReloadingProfileFirst_preservesPrecedence() throws IOException {
Instant startTime = Instant.now();
AdjustableClock clock = new AdjustableClock(startTime);
ProfileFile configFile1 = configFile("profile default", Pair.of("aws_access_key_id", "config-key"));
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
ProfileFileSupplier supplier = ProfileFileSupplier.aggregate(
builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.build(),
ProfileFileSupplier.fixedProfileFile(configFile1));
ProfileFile profileFile = supplier.get();
String accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("defaultAccessKey");
generateTestCredentialsFile("defaultAccessKey2", "defaultSecretAccessKey2");
Duration tick = Duration.ofMillis(1_000);
// The refresh logic uses the last modified attribute of the profile file to determine if it's changed and should be
// reloaded; unfortunately that means that if things happen quickly enough, the last modified time of the first version
// of the file, and the new version will be the same. Ensure that there is a change in the last modified time for the
// test file.
Files.setLastModifiedTime(getTestCredentialsFilePath(), FileTime.from(startTime.plus(tick)));
clock.tickForward(tick);
profileFile = supplier.get();
accessKeyId = profileFile.profile("default").get().property("aws_access_key_id").get();
assertThat(accessKeyId).isEqualTo("defaultAccessKey2");
}
@Test
void fixedProfileFile_nullProfileFile_returnsNonNullSupplier() {
ProfileFile file = null;
ProfileFileSupplier supplier = ProfileFileSupplier.fixedProfileFile(file);
assertThat(supplier).isNotNull();
}
@Test
void get_givenOnLoadAction_callsActionOncePerNewProfileFile() {
int actualProfilesCount = 3;
AtomicInteger blockCount = new AtomicInteger();
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileSupplier supplier = builderWithClock(clock)
.reloadWhenModified(credentialsFilePath, ProfileFile.Type.CREDENTIALS)
.onProfileFileLoad(f -> blockCount.incrementAndGet())
.build();
Duration duration = Duration.ofSeconds(5);
supplier.get();
clock.tickForward(duration);
supplier.get();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
supplier.get();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
supplier.get();
clock.tickForward(duration);
supplier.get();
assertThat(blockCount.get()).isEqualTo(actualProfilesCount);
}
private Path writeTestFile(String contents, Path path) {
try {
Files.createDirectories(testDirectory);
return Files.write(path, contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) {
String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
accessKeyId, secretAccessKey);
return writeTestFile(contents, getTestCredentialsFilePath());
}
private Path getTestCredentialsFilePath() {
return testDirectory.resolve("credentials.txt");
}
private Path generateTestConfigFile(Pair<Object, Object>... pairs) {
String values = Arrays.stream(pairs)
.map(pair -> String.format("%s=%s", pair.left(), pair.right()))
.collect(Collectors.joining(System.lineSeparator()));
String contents = String.format("[default]\n%s", values);
return writeTestFile(contents, testDirectory.resolve("config.txt"));
}
private void updateModificationTime(Path path, Instant instant) {
try {
Files.setLastModifiedTime(path, FileTime.from(instant));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private ProfileFile credentialFile(String name, String accessKeyId, String secretAccessKey) {
String contents = String.format("[%s]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
name, accessKeyId, secretAccessKey);
return credentialFile(contents);
}
private ProfileFile configFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
private ProfileFile configFile(String name, Pair<?, ?>... pairs) {
String values = Arrays.stream(pairs)
.map(pair -> String.format("%s=%s", pair.left(), pair.right()))
.collect(Collectors.joining(System.lineSeparator()));
String contents = String.format("[%s]\n%s", name, values);
return configFile(contents);
}
private static <T> Predicate<T> uniqueInstances() {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return e -> {
boolean unique = seen.stream().noneMatch(o -> o == e);
if (unique) {
seen.add(e);
}
return unique;
};
}
private static ProfileFileSupplier supply(Iterable<ProfileFile> iterable) {
return iterable.iterator()::next;
}
private ProfileFileSupplierBuilder builder() {
return new ProfileFileSupplierBuilder();
}
private ProfileFileSupplierBuilder builderWithClock(Clock clock) {
return new ProfileFileSupplierBuilder().clock(clock);
}
private static final class AdjustableClock extends Clock {
private Instant time;
private AdjustableClock() {
this.time = Instant.now();
}
private AdjustableClock(Instant time) {
this.time = time;
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
public void tickForward(TemporalAmount amount) {
time = time.plus(amount);
}
public void tickBackward(TemporalAmount amount) {
time = time.minus(amount);
}
}
} | 2,411 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/ProfileFileTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.StringInputStream;
/**
* Validate the functionality of {@link ProfileFile}.
*/
public class ProfileFileTest {
@Test
public void emptyFilesHaveNoProfiles() {
assertThat(configFileProfiles("")).isEmpty();
}
@Test
public void emptyProfilesHaveNoProperties() {
assertThat(configFileProfiles("[profile foo]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void profileDefinitionsMustEndWithBrackets() {
assertThatThrownBy(() -> configFileProfiles("[profile foo"))
.hasMessageContaining("Profile definition must end with ']'");
}
@Test
public void profileNamesShouldBeTrimmed() {
assertThat(configFileProfiles("[profile \tfoo \t]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void tabsCanSeparateProfileNamesFromProfilePrefix() {
assertThat(configFileProfiles("[profile\tfoo]"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void propertiesMustBeDefinedInAProfile() {
assertThatThrownBy(() -> configFileProfiles("name = value"))
.hasMessageContaining("Expected a profile definition");
}
@Test
public void profilesCanContainProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void windowsStyleLineEndingsAreSupported() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = value"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void equalsSignsAreSupportedInPropertyNames() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = val=ue"))
.isEqualTo(profiles(profile("foo", property("name", "val=ue"))));
}
@Test
public void unicodeCharactersAreSupportedInPropertyValues() {
assertThat(configFileProfiles("[profile foo]\r\n" +
"name = \uD83D\uDE02"))
.isEqualTo(profiles(profile("foo", property("name", "\uD83D\uDE02"))));
}
@Test
public void profilesCanContainMultipleProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void propertyKeysAndValuesAreTrimmed() {
assertThat(configFileProfiles("[profile foo]\n" +
"name \t= \tvalue \t"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void propertyValuesCanBeEmpty() {
assertThat(configFileProfiles("[profile foo]\n" +
"name ="))
.isEqualTo(profiles(profile("foo", property("name", ""))));
}
@Test
public void propertyKeysCannotBeEmpty() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"= value"))
.hasMessageContaining("Property did not have a name");
}
@Test
public void propertyDefinitionsMustContainAnEqualsSign() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"key : value"))
.hasMessageContaining("Expected an '=' sign defining a property");
}
@Test
public void multipleProfilesCanBeEmpty() {
assertThat(configFileProfiles("[profile foo]\n" +
"[profile bar]"))
.isEqualTo(profiles(profile("foo"),
profile("bar")));
}
@Test
public void multipleProfilesCanHaveProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile bar]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value")),
profile("bar", property("name2", "value2"))));
}
@Test
public void blankLinesAreIgnored() {
assertThat(configFileProfiles("\t \n" +
"[profile foo]\n" +
"\t\n" +
" \n" +
"name = value\n" +
"\t \n" +
"[profile bar]\n" +
" \t"))
.isEqualTo(profiles(profile("foo", property("name", "value")),
profile("bar")));
}
@Test
public void poundSignCommentsAreIgnored() {
assertThat(configFileProfiles("# Comment\n" +
"[profile foo] # Comment\n" +
"name = value # Comment with # sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void semicolonCommentsAreIgnored() {
assertThat(configFileProfiles("; Comment\n" +
"[profile foo] ; Comment\n" +
"name = value ; Comment with ; sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentTypesCanBeUsedTogether() {
assertThat(configFileProfiles("# Comment\n" +
"[profile foo] ; Comment\n" +
"name = value # Comment with ; sign"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentsCanBeEmpty() {
assertThat(configFileProfiles(";\n" +
"[profile foo];\n" +
"name = value ;\n"))
.isEqualTo(profiles(profile("foo", property("name", "value"))));
}
@Test
public void commentsCanBeAdjacentToProfileNames() {
assertThat(configFileProfiles("[profile foo]; Adjacent semicolons\n" +
"[profile bar]# Adjacent pound signs"))
.isEqualTo(profiles(profile("foo"),
profile("bar")));
}
@Test
public void commentsAdjacentToValuesAreIncludedInTheValue() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value; Adjacent semicolons\n" +
"name2 = value# Adjacent pound signs"))
.isEqualTo(profiles(profile("foo",
property("name", "value; Adjacent semicolons"),
property("name2", "value# Adjacent pound signs"))));
}
@Test
public void propertyValuesCanBeContinuedOnTheNextLine() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued"))));
}
@Test
public void propertyValuesCanBeContinuedAcrossMultipleLines() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued\n" +
" -and-continued"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued\n-and-continued"))));
}
@Test
public void continuationValuesIncludeSemicolonComments() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
" -continued ; Comment"))
.isEqualTo(profiles(profile("foo",
property("name", "value\n-continued ; Comment"))));
}
@Test
public void continuationsCannotBeUsedOutsideOfAProfile() {
assertThatThrownBy(() -> configFileProfiles(" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void continuationsCannotBeUsedOutsideOfAProperty() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void continuationsResetWithProfileDefinition() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
" -continued"))
.hasMessageContaining("Expected a profile or property definition");
}
@Test
public void duplicateProfilesInTheSameFileMergeProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void duplicatePropertiesInAProfileUseTheLastOneDefined() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void duplicatePropertiesInDuplicateProfilesUseTheLastOneDefined() {
assertThat(configFileProfiles("[profile foo]\n" +
"name = value\n" +
"[profile foo]\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void defaultProfileWithProfilePrefixOverridesDefaultProfileWithoutPrefixWhenPrefixedIsFirst() {
assertThat(configFileProfiles("[profile default]\n" +
"name = value\n" +
"[default]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("default", property("name", "value"))));
}
@Test
public void defaultProfileWithProfilePrefixOverridesDefaultProfileWithoutPrefixWhenPrefixedIsLast() {
assertThat(configFileProfiles("[default]\n" +
"name2 = value2\n" +
"[profile default]\n" +
"name = value"))
.isEqualTo(profiles(profile("default", property("name", "value"))));
}
@Test
public void invalidProfilesNamesAreIgnored() {
assertThat(aggregateFileProfiles("[profile in valid]\n" +
"name = value\n",
"[in valid 2]\n" +
"name2 = value2"))
.isEqualTo(profiles());
}
@Test
public void invalidPropertyNamesAreIgnored() {
assertThat(configFileProfiles("[profile foo]\n" +
"in valid = value"))
.isEqualTo(profiles(profile("foo")));
}
@Test
public void allValidProfileNameCharactersAreSupported() {
assertThat(configFileProfiles("[profile ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+]"))
.isEqualTo(profiles(profile("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+")));
}
@Test
public void allValidPropertyNameCharactersAreSupported() {
assertThat(configFileProfiles("[profile foo]\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+ = value"))
.isEqualTo(profiles(profile("foo", property("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_./%@:+",
"value"))));
}
@Test
public void propertiesCanHaveSubProperties() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name = value"))
.isEqualTo(profiles(profile("foo", property("s3", "\nname = value"))));
}
@Test
public void invalidSubPropertiesCauseAnError() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" invalid"))
.hasMessageContaining("Expected an '=' sign defining a property");
}
@Test
public void subPropertiesCanHaveEmptyValues() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name ="))
.isEqualTo(profiles(profile("foo", property("s3", "\nname ="))));
}
@Test
public void invalidSubPropertiesCannotHaveEmptyNames() {
assertThatThrownBy(() -> configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" = value"))
.hasMessageContaining("Property did not have a name");
}
@Test
public void subPropertiesCanHaveInvalidNames() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" in valid = value"))
.isEqualTo(profiles(profile("foo", property("s3", "\nin valid = value"))));
}
@Test
public void subPropertiesCanHaveBlankLines() {
assertThat(configFileProfiles("[profile foo]\n" +
"s3 =\n" +
" name = value\n" +
"\t \n" +
" name2 = value2"))
.isEqualTo(profiles(profile("foo", property("s3", "\nname = value\nname2 = value2"))));
}
@Test
public void profilesDuplicatedInMultipleFilesAreMerged() {
assertThat(aggregateFileProfiles("[profile foo]\n" +
"name = value\n",
"[foo]\n" +
"name2 = value2"))
.isEqualTo(profiles(profile("foo",
property("name", "value"),
property("name2", "value2"))));
}
@Test
public void defaultProfilesWithMixedPrefixesInConfigFileIgnoreOneWithoutPrefixWhenMerging() {
assertThat(configFileProfiles("[profile default]\n" +
"name = value\n" +
"[default]\n" +
"name2 = value2\n" +
"[profile default]\n" +
"name3 = value3"))
.isEqualTo(profiles(profile("default",
property("name", "value"),
property("name3", "value3"))));
}
@Test
public void duplicatePropertiesBetweenFilesUsesCredentialsProperty() {
assertThat(aggregateFileProfiles("[profile foo]\n" +
"name = value",
"[foo]\n" +
"name = value2"))
.isEqualTo(profiles(profile("foo", property("name", "value2"))));
}
@Test
public void configProfilesWithoutPrefixAreIgnored() {
assertThat(configFileProfiles("[foo]\n" +
"name = value"))
.isEqualTo(profiles());
}
@Test
public void credentialsProfilesWithPrefixAreIgnored() {
assertThat(credentialFileProfiles("[profile foo]\n" +
"name = value"))
.isEqualTo(profiles());
}
@Test
public void sectionsInCredentialsFilesIsIgnored() {
String ASSUME_ROLE_PROFILE =
"[test]\n"
+ "region = us-west-1\n"
+ "credential_source = Environment\n"
+ "sso_session = session\n"
+ "role_arn = some_Arn\n"
+ "[sso-session session]\n"
+ "sso_region = us-west-1\n"
+ "start_url = someUrl\n";
ProfileFile profileFile = credentialFile(ASSUME_ROLE_PROFILE);
Map<String, Profile> profileMap = profileFile.profiles();
assertThat(profileMap)
.isEqualTo(profiles(profile("test", property("region", "us-west-1")
, property("credential_source", "Environment")
, property("sso_session", "session"),
property("role_arn", "some_Arn"))));
;
assertThat(profileFile.getSection("sso-session", "session")).isNotPresent();
}
@Test
public void invalidSectionNamesAreNotAddedInSectionListOfProfileFiles() {
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(credentialFile("[in valid 2]\n"
+ "name2 = value2"))
.addFile(configFile("[profile validSection]\n"
+ "sso_session = validSso\n"
+ "[sso-session validSso]\n"
+ "start_url = Valid-url\n"))
.addFile(configFile("[profile section]\n"
+ "sso_session = sso invalid\n"
+ "[sso-session sso invalid]\n"
+ "start_url = url\n"))
.build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("section", property("sso_session", "sso invalid")),
profile("validSection", property("sso_session", "validSso"))));
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso")).isNotPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso invalid")).isNotPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "validSso").get())
.isEqualTo(profile("validSso", property("start_url", "Valid-url")));
}
@Test
public void defaultSessionNameIsNotSupported_when_session_doesNot_exist() {
String nonExistentSessionName = "nonExistentSession";
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(configFile("[profile validSection]\n"
+ "sso_session = " + nonExistentSessionName + "\n"
+ "[profile " + nonExistentSessionName + "]\n"
+ "start_url = Valid-url-2\n"
+ "[sso-session default]\n"
+ "start_url = Valid-url\n"))
.build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("validSection", property("sso_session", nonExistentSessionName)),
profile(nonExistentSessionName, property("start_url", "Valid-url-2"))));
assertThat(aggregatedProfileFiles.getSection("sso-session", nonExistentSessionName)).isNotPresent();
}
@Test
public void sessionIsNotAdjacentToProfile() {
ProfileFile aggregatedProfileFiles = ProfileFile.aggregator()
.addFile(configFile("[profile profile1]\n"
+ "sso_session = sso-token1\n"
+ "[profile profile2]\n"
+ "region = us-west-2\n"
+ "[default]\n"
+ "default_property = property1\n"))
.addFile(configFile("[sso-session sso-token1]\n"
+ "start_url = startUrl1\n"
+ "[profile profile3]\n"
+ "region = us-east-1\n")
).build();
assertThat(aggregatedProfileFiles.profiles())
.isEqualTo(profiles(profile("profile1", property("sso_session", "sso-token1")),
profile("default", property("default_property", "property1")),
profile("profile2", property("region", "us-west-2")),
profile("profile3", property("region", "us-east-1"))
));
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso-token1")).isPresent();
assertThat(aggregatedProfileFiles.getSection("sso-session", "sso-token1").get()).isEqualTo(
profile("sso-token1", property("start_url", "startUrl1")) );
}
@Test
public void exceptionIsThrown_when_sectionDoesnotHaveASquareBracket() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(
() -> ProfileFile.aggregator()
.addFile(configFile("[profile profile1]\n"
+ "sso_session = sso-token1\n"
+ "[sso-session sso-token1\n"
+ "start_url = startUrl1\n")
).build()).withMessageContaining("Section definition must end with ']' on line 3");
}
@Test
public void loadingDefaultProfileFileWorks() {
ProfileFile.defaultProfileFile();
}
@Test
public void returnsEmptyMap_when_AwsFilesDoNotExist() {
ProfileFile missingProfile = ProfileFile.aggregator()
.build();
assertThat(missingProfile.profiles()).isEmpty();
assertThat(missingProfile.profiles()).isInstanceOf(Map.class);
}
private ProfileFile configFile(String configFile) {
return ProfileFile.builder()
.content(new StringInputStream(configFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
private Map<String, Profile> configFileProfiles(String configFile) {
return configFile(configFile).profiles();
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private Map<String, Profile> credentialFileProfiles(String credentialFile) {
return credentialFile(credentialFile).profiles();
}
private Map<String, Profile> aggregateFileProfiles(String configFile, String credentialFile) {
return ProfileFile.aggregator()
.addFile(credentialFile(credentialFile))
.addFile(configFile(configFile))
.build()
.profiles();
}
private Map<String, Profile> profiles(Profile... profiles) {
Map<String, Profile> result = new HashMap<>();
Stream.of(profiles).forEach(p -> result.put(p.name(), p));
return result;
}
@SafeVarargs
private final Profile profile(String name, Map.Entry<String, String>... properties) {
Map<String, String> propertiesMap = new HashMap<>();
Stream.of(properties).forEach(p -> propertiesMap.put(p.getKey(), p.getValue()));
return Profile.builder().name(name).properties(propertiesMap).build();
}
private Map.Entry<String, String> property(String name, String value) {
return new AbstractMap.SimpleImmutableEntry<>(name, value);
}
}
| 2,412 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/test/java/software/amazon/awssdk/profiles/internal/ProfileFileRefresherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAmount;
import java.util.concurrent.atomic.AtomicInteger;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileFileRefresherTest {
private static FileSystem jimfs;
private static Path testDirectory;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
testDirectory = jimfs.getPath("test");
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void refreshIfStale_profileModifiedNoPathSpecified_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.build();
Duration intervalWithinJitter = Duration.ofMillis(100);
ProfileFile file1 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(intervalWithinJitter);
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedWithinJitterPeriod_doesNotReloadProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration intervalWithinJitter = Duration.ofMillis(100);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(intervalWithinJitter);
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant());
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedOutsideJitterPeriod_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration intervalOutsideJitter = Duration.ofMillis(1_000);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(intervalOutsideJitter);
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant());
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isNotSameAs(file1);
}
@Test
void refreshIfStale_profileModified_reloadsProfileFile() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration refreshInterval = Duration.ofSeconds(15);
ProfileFile file1 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(refreshInterval.plusSeconds(10));
ProfileFile file2 = refresher.refreshIfStale();
Assertions.assertThat(file2).isNotSameAs(file1);
}
@Test
void refreshIfStale_profileModifiedOnceButRefreshedMultipleTimes_reloadsProfileFileOnce() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(Duration.ofSeconds(5));
ProfileFile file3 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
}
@Test
void refreshIfStale_profileModifiedMultipleTimes_reloadsProfileFileOncePerChange() {
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = refresher.refreshIfStale();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file5 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
Assertions.assertThat(file4).isNotSameAs(file3);
}
@Test
void refreshIfStale_givenOnReloadConsumer_callsConsumerOncePerChange() {
int actualRefreshOperations = 3;
AtomicInteger refreshOperationsCounter = new AtomicInteger();
Path credentialsFilePath = generateTestCredentialsFile("defaultAccessKey", "defaultSecretAccessKey");
AdjustableClock clock = new AdjustableClock();
ProfileFileRefresher refresher = refresherWithClock(clock)
.profileFile(() -> profileFile(credentialsFilePath))
.profileFilePath(credentialsFilePath)
.onProfileFileReload(f -> refreshOperationsCounter.incrementAndGet())
.build();
Duration duration = Duration.ofSeconds(5);
ProfileFile file1 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file2 = refresher.refreshIfStale();
generateTestCredentialsFile("modifiedAccessKey", "modifiedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file3 = refresher.refreshIfStale();
generateTestCredentialsFile("updatedAccessKey", "updatedSecretAccessKey");
updateModificationTime(credentialsFilePath, clock.instant().plusMillis(1));
clock.tickForward(duration);
ProfileFile file4 = refresher.refreshIfStale();
clock.tickForward(duration);
ProfileFile file5 = refresher.refreshIfStale();
Assertions.assertThat(file2).isSameAs(file1);
Assertions.assertThat(file3).isNotSameAs(file2);
Assertions.assertThat(file4).isNotSameAs(file3);
Assertions.assertThat(file5).isSameAs(file4);
Assertions.assertThat(refreshOperationsCounter.get()).isEqualTo(actualRefreshOperations);
}
private ProfileFile credentialFile(String credentialFile) {
return ProfileFile.builder()
.content(new StringInputStream(credentialFile))
.type(ProfileFile.Type.CREDENTIALS)
.build();
}
private Path generateTestFile(String contents, String filename) {
try {
Files.createDirectories(testDirectory);
return Files.write(testDirectory.resolve(filename), contents.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Path generateTestCredentialsFile(String accessKeyId, String secretAccessKey) {
String contents = String.format("[default]\naws_access_key_id = %s\naws_secret_access_key = %s\n",
accessKeyId, secretAccessKey);
return generateTestFile(contents, "credentials.txt");
}
private void updateModificationTime(Path path, Instant instant) {
try {
Files.setLastModifiedTime(path, FileTime.from(instant));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private ProfileFile profileFile(Path path) {
return ProfileFile.builder().content(path).type(ProfileFile.Type.CREDENTIALS).build();
}
private ProfileFileRefresher.Builder refresherWithClock(Clock clock) {
return ProfileFileRefresher.builder()
.clock(clock);
}
private static final class AdjustableClock extends Clock {
private Instant time;
private AdjustableClock() {
this.time = Instant.now();
}
@Override
public ZoneId getZone() {
return ZoneOffset.UTC;
}
@Override
public Clock withZone(ZoneId zone) {
throw new UnsupportedOperationException();
}
@Override
public Instant instant() {
return time;
}
public void tickForward(TemporalAmount amount) {
time = time.plus(amount);
}
public void tickBackward(TemporalAmount amount) {
time = time.minus(amount);
}
}
}
| 2,413 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/Profile.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A named collection of configuration stored in a {@link ProfileFile}.
* <p>
* Raw property access can be made via {@link #property(String)} and {@link #properties()}.
*
* @see ProfileFile
*/
@SdkPublicApi
public final class Profile implements ToCopyableBuilder<Profile.Builder, Profile> {
/**
* The name of this profile (minus any profile prefixes).
*/
private final String name;
/**
* The raw properties in this profile.
*/
private final Map<String, String> properties;
/**
* @see ProfileFile
* @see #builder()
*/
private Profile(BuilderImpl builder) {
this.name = Validate.paramNotNull(builder.name, "name");
this.properties = Validate.paramNotNull(builder.properties, "properties");
}
/**
* Create a builder for defining a profile with specific attributes. For reading profiles from a file, see
* {@link ProfileFile}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Retrieve the name of this profile.
*/
public String name() {
return name;
}
/**
* Retrieve a specific raw property from this profile.
*
* @param propertyKey The name of the property to retrieve.
* @return The value of the property, if configured.
*/
public Optional<String> property(String propertyKey) {
return Optional.ofNullable(properties.get(propertyKey));
}
/**
* Retrieve a specific property from this profile, and convert it to a boolean using the same algorithm as
* {@link SystemSetting#getBooleanValue()}.
*
* @param propertyKey The name of the property to retrieve.
* @return The boolean value of the property, if configured.
* @throws IllegalStateException If the property is set, but it is not boolean.
*/
public Optional<Boolean> booleanProperty(String propertyKey) {
return property(propertyKey).map(property -> parseBooleanProperty(propertyKey, property));
}
private Boolean parseBooleanProperty(String propertyKey, String property) {
if (property.equalsIgnoreCase("true")) {
return true;
} else if (property.equalsIgnoreCase("false")) {
return false;
}
throw new IllegalStateException("Profile property '" + propertyKey + "' must be set to 'true', 'false' or unset, but "
+ "was set to '" + property + "'.");
}
/**
* Retrieve an unmodifiable view of all of the properties currently in this profile.
*/
public Map<String, String> properties() {
return Collections.unmodifiableMap(properties);
}
@Override
public Builder toBuilder() {
return builder().name(name)
.properties(properties);
}
@Override
public String toString() {
return ToString.builder("Profile")
.add("name", name)
.add("properties", properties.keySet())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Profile profile = (Profile) o;
return Objects.equals(name, profile.name) &&
Objects.equals(properties, profile.properties);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(name());
hashCode = 31 * hashCode + Objects.hashCode(properties());
return hashCode;
}
/**
* A builder for a {@link Profile}. See {@link #builder()}.
*/
public interface Builder extends CopyableBuilder<Builder, Profile> {
/**
* Define the name of this profile, without the legacy "profile" prefix.
*/
Builder name(String name);
/**
* Define the properties configured in this profile.
*/
Builder properties(Map<String, String> properties);
/**
* Create a profile using the current state of this builder.
*/
@Override
Profile build();
}
private static final class BuilderImpl implements Builder {
private String name;
private Map<String, String> properties;
/**
* @see #builder()
*/
private BuilderImpl() {
}
@Override
public Builder name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
name(name);
}
@Override
public Builder properties(Map<String, String> properties) {
this.properties = Collections.unmodifiableMap(new LinkedHashMap<>(properties));
return this;
}
public void setProperties(Map<String, String> properties) {
properties(properties);
}
@Override
public Profile build() {
return new Profile(this);
}
}
}
| 2,414 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSupplierBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.nio.file.Path;
import java.time.Clock;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.profiles.internal.ProfileFileRefresher;
@SdkInternalApi
final class ProfileFileSupplierBuilder {
private boolean reloadingSupplier = false;
private Supplier<ProfileFile> profileFile;
private Path profileFilePath;
private Clock clock;
private Consumer<ProfileFile> onProfileFileLoad;
public ProfileFileSupplierBuilder reloadWhenModified(Path path, ProfileFile.Type type) {
ProfileFile.Builder builder = ProfileFile.builder()
.content(path)
.type(type);
this.profileFile = builder::build;
this.profileFilePath = path;
this.reloadingSupplier = true;
return this;
}
public ProfileFileSupplierBuilder fixedProfileFile(Path path, ProfileFile.Type type) {
return fixedProfileFile(ProfileFile.builder()
.content(path)
.type(type)
.build());
}
public ProfileFileSupplierBuilder fixedProfileFile(ProfileFile profileFile) {
this.profileFile = () -> profileFile;
this.profileFilePath = null;
this.reloadingSupplier = false;
return this;
}
public ProfileFileSupplierBuilder onProfileFileLoad(Consumer<ProfileFile> action) {
this.onProfileFileLoad = action;
return this;
}
public ProfileFileSupplierBuilder clock(Clock clock) {
this.clock = clock;
return this;
}
public ProfileFileSupplier build() {
return fromBuilder(this);
}
/**
* Completes {@link ProfileFileSupplier} build.
* @param builder Object to complete build.
* @return Implementation of {@link ProfileFileSupplier}.
*/
static ProfileFileSupplier fromBuilder(ProfileFileSupplierBuilder builder) {
if (builder.reloadingSupplier) {
ProfileFileRefresher.Builder refresherBuilder = ProfileFileRefresher.builder()
.profileFile(builder.profileFile)
.profileFilePath(builder.profileFilePath);
if (Objects.nonNull(builder.clock)) {
refresherBuilder.clock(builder.clock);
}
if (Objects.nonNull(builder.onProfileFileLoad)) {
refresherBuilder.onProfileFileReload(builder.onProfileFileLoad);
}
ProfileFileRefresher refresher = refresherBuilder.build();
return new ProfileFileSupplier() {
@Override
public ProfileFile get() {
return refresher.refreshIfStale();
}
};
}
return builder.profileFile::get;
}
}
| 2,415 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileLocation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A collection of static methods for loading the location for configuration and credentials files.
*/
@SdkPublicApi
public final class ProfileFileLocation {
private static final Pattern HOME_DIRECTORY_PATTERN =
Pattern.compile("^~(/|" + Pattern.quote(FileSystems.getDefault().getSeparator()) + ").*$");
private ProfileFileLocation() {
}
/**
* Resolve the path for the configuration file, regardless of whether it exists or not.
*
* @see #configurationFileLocation()
*/
public static Path configurationFilePath() {
return resolveProfileFilePath(
ProfileFileSystemSetting.AWS_CONFIG_FILE.getStringValue()
.orElseGet(() -> Paths.get(userHomeDirectory(),
".aws", "config").toString()));
}
/**
* Resolve the location for the credentials file, regardless of whether it exists or not.
*
* @see #credentialsFileLocation()
*/
public static Path credentialsFilePath() {
return resolveProfileFilePath(
ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE.getStringValue()
.orElseGet(() -> Paths.get(userHomeDirectory(),
".aws", "credentials").toString()));
}
/**
* Load the location for the configuration file, usually ~/.aws/config unless it's overridden using an environment variable
* or system property.
*/
public static Optional<Path> configurationFileLocation() {
return resolveIfExists(configurationFilePath());
}
/**
* Load the location for the credentials file, usually ~/.aws/credentials unless it's overridden using an environment variable
* or system property.
*/
public static Optional<Path> credentialsFileLocation() {
return resolveIfExists(credentialsFilePath());
}
private static Path resolveProfileFilePath(String path) {
// Resolve ~ using the CLI's logic, not whatever Java decides to do with it.
if (HOME_DIRECTORY_PATTERN.matcher(path).matches()) {
path = userHomeDirectory() + path.substring(1);
}
return Paths.get(path);
}
private static Optional<Path> resolveIfExists(Path path) {
return Optional.ofNullable(path).filter(Files::isRegularFile).filter(Files::isReadable);
}
}
| 2,416 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileProperty.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The properties used by the Java SDK from the credentials and config files.
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileProperty {
/**
* Property name for specifying the Amazon AWS Access Key
*/
public static final String AWS_ACCESS_KEY_ID = "aws_access_key_id";
/**
* Property name for specifying the Amazon AWS Secret Access Key
*/
public static final String AWS_SECRET_ACCESS_KEY = "aws_secret_access_key";
/**
* Property name for specifying the Amazon AWS Session Token
*/
public static final String AWS_SESSION_TOKEN = "aws_session_token";
/**
* Property name for specifying the IAM role to assume
*/
public static final String ROLE_ARN = "role_arn";
/**
* Property name for specifying the IAM role session name
*/
public static final String ROLE_SESSION_NAME = "role_session_name";
/**
* Property name for specifying how long in seconds to assume the role
*/
public static final String DURATION_SECONDS = "duration_seconds";
/**
* Property name for specifying the IAM role external id
*/
public static final String EXTERNAL_ID = "external_id";
/**
* Property name for specifying the profile credentials to use when assuming a role
*/
public static final String SOURCE_PROFILE = "source_profile";
/**
* Property name for specifying the credential source to use when assuming a role
*/
public static final String CREDENTIAL_SOURCE = "credential_source";
/**
* AWS Region to use when creating clients.
*/
public static final String REGION = "region";
/**
* Property name for specifying the identification number of the MFA device
*/
public static final String MFA_SERIAL = "mfa_serial";
/**
* Property name for specifying whether or not endpoint discovery is enabled.
*/
public static final String ENDPOINT_DISCOVERY_ENABLED = "aws_endpoint_discovery_enabled";
/**
* An external process that should be invoked to load credentials.
*/
public static final String CREDENTIAL_PROCESS = "credential_process";
public static final String WEB_IDENTITY_TOKEN_FILE = "web_identity_token_file";
/**
* The S3 regional endpoint setting for the {@code us-east-1} region. Setting the value to {@code regional} causes
* the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the {@code US_EAST_1} region instead of
* the global {@code s3.amazonaws.com}. Using the regional endpoint is disabled by default.
*/
public static final String S3_US_EAST_1_REGIONAL_ENDPOINT = "s3_us_east_1_regional_endpoint";
/**
* The "retry mode" to be used for clients created using the currently-configured profile. Values supported by all SDKs are
* "legacy" and "standard". See the {@code RetryMode} class JavaDoc for more information.
*/
public static final String RETRY_MODE = "retry_mode";
/**
* The "defaults mode" to be used for clients created using the currently-configured profile. Defaults mode determins how SDK
* default configuration should be resolved. See the {@code DefaultsMode} class JavaDoc for more
* information.
*/
public static final String DEFAULTS_MODE = "defaults_mode";
/**
* Aws region where the SSO directory for the given 'sso_start_url' is hosted. This is independent of the general 'region'.
*/
public static final String SSO_REGION = "sso_region";
/**
* The corresponding IAM role in the AWS account that temporary AWS credentials will be resolved for.
*/
public static final String SSO_ROLE_NAME = "sso_role_name";
/**
* AWS account ID that temporary AWS credentials will be resolved for.
*/
public static final String SSO_ACCOUNT_ID = "sso_account_id";
/**
* Start url provided by the SSO service via the console. It's the main URL used for login to the SSO directory.
* This is also referred to as the "User Portal URL" and can also be used to login to the SSO web interface for AWS
* console access.
*/
public static final String SSO_START_URL = "sso_start_url";
public static final String USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint";
public static final String USE_FIPS_ENDPOINT = "use_fips_endpoint";
public static final String EC2_METADATA_SERVICE_ENDPOINT_MODE = "ec2_metadata_service_endpoint_mode";
public static final String EC2_METADATA_SERVICE_ENDPOINT = "ec2_metadata_service_endpoint";
/**
* Whether request compression is disabled for operations marked with the RequestCompression trait. The default value is
* false, i.e., request compression is enabled.
*/
public static final String DISABLE_REQUEST_COMPRESSION = "disable_request_compression";
/**
* The minimum compression size in bytes, inclusive, for a request to be compressed. The default value is 10_240.
* The value must be non-negative and no greater than 10_485_760.
*/
public static final String REQUEST_MIN_COMPRESSION_SIZE_BYTES = "request_min_compression_size_bytes";
private ProfileProperty() {
}
}
| 2,417 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSystemSetting.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.SystemSetting;
/**
* System settings for loading configuration from profile files.
*/
@SdkProtectedApi
public enum ProfileFileSystemSetting implements SystemSetting {
/**
* Configure the default configuration file used in the ProfileFile. When not explicitly
* overridden in a client (eg. by specifying the region or credentials provider), this will be the location used when an
* AWS client is created.
*
* See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html for more information on configuring the
* SDK via a configuration file.
*/
AWS_CONFIG_FILE("aws.configFile", null),
/**
* Configure the default credentials file used in the ProfileFile. When not explicitly
* overridden in a client (eg. by specifying the region or credentials provider), this will be the location used when an
* AWS client is created.
*
* See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html for more information on configuring the
* SDK via a credentials file.
*/
AWS_SHARED_CREDENTIALS_FILE("aws.sharedCredentialsFile", null),
/**
* Configure the default profile that should be loaded from the {@link #AWS_CONFIG_FILE}
*
* @see #AWS_CONFIG_FILE
*/
AWS_PROFILE("aws.profile", "default");
private final String systemProperty;
private final String defaultValue;
ProfileFileSystemSetting(String systemProperty, String defaultValue) {
this.systemProperty = systemProperty;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return systemProperty;
}
@Override
public String environmentVariable() {
return name();
}
@Override
public String defaultValue() {
return defaultValue;
}
}
| 2,418 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFileSupplier.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.internal.ProfileFileRefresher;
/**
* Encapsulates the logic for supplying either a single or multiple ProfileFile instances.
* <p>
* Each call to the {@link #get()} method will result in either a new or previously supplied profile based on the
* implementation's rules.
*/
@SdkPublicApi
@FunctionalInterface
public interface ProfileFileSupplier extends Supplier<ProfileFile> {
/**
* Creates a {@link ProfileFileSupplier} capable of producing multiple profile objects by aggregating the default
* credentials and configuration files as determined by {@link ProfileFileLocation#credentialsFileLocation()} abd
* {@link ProfileFileLocation#configurationFileLocation()}. This supplier will return a new ProfileFile instance only once
* either disk file has been modified. Multiple calls to the supplier while both disk files are unchanged will return the
* same object.
*
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a new aggregate profile when either file
* has been modified.
*/
static ProfileFileSupplier defaultSupplier() {
Optional<ProfileFileSupplier> credentialsSupplierOptional
= ProfileFileLocation.credentialsFileLocation()
.map(path -> reloadWhenModified(path, ProfileFile.Type.CREDENTIALS));
Optional<ProfileFileSupplier> configurationSupplierOptional
= ProfileFileLocation.configurationFileLocation()
.map(path -> reloadWhenModified(path, ProfileFile.Type.CONFIGURATION));
ProfileFileSupplier supplier = () -> ProfileFile.builder().build();
if (credentialsSupplierOptional.isPresent() && configurationSupplierOptional.isPresent()) {
supplier = aggregate(credentialsSupplierOptional.get(), configurationSupplierOptional.get());
} else if (credentialsSupplierOptional.isPresent()) {
supplier = credentialsSupplierOptional.get();
} else if (configurationSupplierOptional.isPresent()) {
supplier = configurationSupplierOptional.get();
}
return supplier;
}
/**
* Creates a {@link ProfileFileSupplier} capable of producing multiple profile objects from a file. This supplier will
* return a new ProfileFile instance only once the disk file has been modified. Multiple calls to the supplier while the
* disk file is unchanged will return the same object.
*
* @param path Path to the file to read from.
* @param type The type of file. See {@link ProfileFile.Type} for possible values.
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a new profile when the file
* has been modified.
*/
static ProfileFileSupplier reloadWhenModified(Path path, ProfileFile.Type type) {
return new ProfileFileSupplier() {
final ProfileFile.Builder builder = ProfileFile.builder()
.content(path)
.type(type);
final ProfileFileRefresher refresher = ProfileFileRefresher.builder()
.profileFile(builder::build)
.profileFilePath(path)
.build();
@Override
public ProfileFile get() {
return refresher.refreshIfStale();
}
};
}
/**
* Creates a {@link ProfileFileSupplier} that produces an existing profile.
*
* @param profileFile Profile object to supply.
* @return Implementation of {@link ProfileFileSupplier} that is capable of supplying a single profile.
*/
static ProfileFileSupplier fixedProfileFile(ProfileFile profileFile) {
return () -> profileFile;
}
/**
* Creates a {@link ProfileFileSupplier} by combining the {@link ProfileFile} objects from multiple {@code
* ProfileFileSupplier}s. Objects are passed into {@link ProfileFile.Aggregator}.
*
* @param suppliers Array of {@code ProfileFileSupplier} objects. {@code ProfileFile} objects are passed to
* {@link ProfileFile.Aggregator#addFile(ProfileFile)} in the same argument order as the supplier that
* generated it.
* @return Implementation of {@link ProfileFileSupplier} aggregating results from the supplier objects.
*/
static ProfileFileSupplier aggregate(ProfileFileSupplier... suppliers) {
return new ProfileFileSupplier() {
final AtomicReference<ProfileFile> currentAggregateProfileFile = new AtomicReference<>();
final Map<Supplier<ProfileFile>, ProfileFile> currentValuesBySupplier
= Collections.synchronizedMap(new LinkedHashMap<>());
@Override
public ProfileFile get() {
boolean refreshAggregate = false;
for (ProfileFileSupplier supplier : suppliers) {
if (didSuppliedValueChange(supplier)) {
refreshAggregate = true;
}
}
if (refreshAggregate) {
refreshCurrentAggregate();
}
return currentAggregateProfileFile.get();
}
private boolean didSuppliedValueChange(Supplier<ProfileFile> supplier) {
ProfileFile next = supplier.get();
ProfileFile current = currentValuesBySupplier.put(supplier, next);
return !Objects.equals(next, current);
}
private void refreshCurrentAggregate() {
ProfileFile.Aggregator aggregator = ProfileFile.aggregator();
currentValuesBySupplier.values().forEach(aggregator::addFile);
ProfileFile current = currentAggregateProfileFile.get();
ProfileFile next = aggregator.build();
if (!Objects.equals(current, next)) {
currentAggregateProfileFile.compareAndSet(current, next);
}
}
};
}
}
| 2,419 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/ProfileFile.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.internal.ProfileFileReader;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Provides programmatic access to the contents of an AWS configuration profile file.
*
* AWS configuration profiles allow you to share multiple sets of AWS security credentials between different tools such as the
* AWS SDK for Java and the AWS CLI.
*
* <p>
* For more information on setting up AWS configuration profiles, see:
* http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
*
* <p>
* A profile file can be created with {@link #builder()} and merged with other profiles files with {@link #aggregator()}. By
* default, the SDK will use the {@link #defaultProfileFile()} when that behavior hasn't been explicitly overridden.
*/
@SdkPublicApi
public final class ProfileFile {
public static final String PROFILES_SECTION_TITLE = "profiles";
private final Map<String, Map<String, Profile>> profilesAndSectionsMap;
/**
* @see #builder()
*/
private ProfileFile(Map<String, Map<String, Map<String, String>>> profilesSectionMap) {
Validate.paramNotNull(profilesSectionMap, "profilesSectionMap");
this.profilesAndSectionsMap = convertToProfilesSectionsMap(profilesSectionMap);
}
public Optional<Profile> getSection(String sectionName, String sectionTitle) {
Map<String, Profile> sectionMap = profilesAndSectionsMap.get(sectionName);
if (sectionMap != null) {
return Optional.ofNullable(sectionMap.get(sectionTitle));
}
return Optional.empty();
}
/**
* Create a builder for a {@link ProfileFile}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a builder that can merge multiple {@link ProfileFile}s together.
*/
public static Aggregator aggregator() {
return new Aggregator();
}
/**
* Get the default profile file, using the credentials file from "~/.aws/credentials", the config file from "~/.aws/config"
* and the "default" profile. This default behavior can be customized using the
* {@link ProfileFileSystemSetting#AWS_SHARED_CREDENTIALS_FILE}, {@link ProfileFileSystemSetting#AWS_CONFIG_FILE} and
* {@link ProfileFileSystemSetting#AWS_PROFILE} settings or by specifying a different profile file and profile name.
*
* <p>
* The file is read each time this method is invoked.
*/
public static ProfileFile defaultProfileFile() {
return ProfileFile.aggregator()
.applyMutation(ProfileFile::addCredentialsFile)
.applyMutation(ProfileFile::addConfigFile)
.build();
}
/**
* Retrieve the profile from this file with the given name.
*
* @param profileName The name of the profile that should be retrieved from this file.
* @return The profile, if available.
*/
public Optional<Profile> profile(String profileName) {
Map<String, Profile> profileMap = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return profileMap != null ? Optional.ofNullable(profileMap.get(profileName)) : Optional.empty();
}
/**
* Retrieve an unmodifiable collection including all of the profiles in this file.
* @return An unmodifiable collection of the profiles in this file, keyed by profile name.
*/
public Map<String, Profile> profiles() {
Map<String, Profile> profileMap = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return profileMap != null ? Collections.unmodifiableMap(profileMap) : Collections.emptyMap();
}
@Override
public String toString() {
Map<String, Profile> profiles = profilesAndSectionsMap.get(PROFILES_SECTION_TITLE);
return ToString.builder("ProfileFile")
.add("sections", profilesAndSectionsMap.keySet())
.add("profiles", profiles == null ? null : profiles.values())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileFile that = (ProfileFile) o;
return Objects.equals(profilesAndSectionsMap, that.profilesAndSectionsMap);
}
@Override
public int hashCode() {
return Objects.hashCode(this.profilesAndSectionsMap);
}
private static void addCredentialsFile(ProfileFile.Aggregator builder) {
ProfileFileLocation.credentialsFileLocation()
.ifPresent(l -> builder.addFile(ProfileFile.builder()
.content(l)
.type(ProfileFile.Type.CREDENTIALS)
.build()));
}
private static void addConfigFile(ProfileFile.Aggregator builder) {
ProfileFileLocation.configurationFileLocation()
.ifPresent(l -> builder.addFile(ProfileFile.builder()
.content(l)
.type(ProfileFile.Type.CONFIGURATION)
.build()));
}
/**
* Convert the sorted map of profile and section properties into a sorted list of profiles and sections.
* Example: sortedProfilesSectionMap
* @param sortedProfilesSectionMap : Map of String to Profile/Sessions defined.
* <pre>
* {@code
* [profile sso-token]
* sso_session = admin
* [sso-session admin]
* sso_start_url = https://view.awsapps.com/start
* }
* </pre> would look like
* <pre>
* {@code
* sortedProfilesSectionMap
* profiles -- // Profile Section Title
* sso-token -- // Profile Name
* sso_session = admin // Property definition
* sso-session -- // Section title for Sso-sessions
* admin --
* sso_start_url = https://view.awsapps.com/start
*
* }
* </pre>
* @return Map with keys representing Profiles and sections and value as Map with keys as profile/section name and value as
* property definition.
*/
private Map<String, Map<String, Profile>> convertToProfilesSectionsMap(
Map<String, Map<String, Map<String, String>>> sortedProfilesSectionMap) {
Map<String, Map<String, Profile>> result = new LinkedHashMap<>();
sortedProfilesSectionMap.entrySet()
.forEach(sections -> {
result.put(sections.getKey(), new LinkedHashMap<>());
Map<String, Profile> stringProfileMap = result.get(sections.getKey());
sections.getValue().entrySet()
.forEach(section -> {
Profile profile = Profile.builder()
.name(section.getKey())
.properties(section.getValue())
.build();
stringProfileMap.put(section.getKey(), profile);
});
});
return result;
}
/**
* The supported types of profile files. The type of profile determines the way in which it is parsed.
*/
public enum Type {
/**
* A configuration profile file, typically located at ~/.aws/config, that expects all profile names (except the default
* profile) to be prefixed with "profile ". Any non-default profiles without this prefix will be ignored.
*/
CONFIGURATION,
/**
* A credentials profile file, typically located at ~/.aws/credentials, that expects all profile name to have no
* "profile " prefix. Any profiles with a profile prefix will be ignored.
*/
CREDENTIALS
}
/**
* A builder for a {@link ProfileFile}. {@link #content(Path)} (or {@link #content(InputStream)}) and {@link #type(Type)} are
* required fields.
*/
public interface Builder extends SdkBuilder<Builder, ProfileFile> {
/**
* Configure the content of the profile file. This stream will be read from and then closed when {@link #build()} is
* invoked.
*/
Builder content(InputStream contentStream);
/**
* Configure the location from which the profile file should be loaded.
*/
Builder content(Path contentLocation);
/**
* Configure the {@link Type} of file that should be loaded.
*/
Builder type(Type type);
@Override
ProfileFile build();
}
private static final class BuilderImpl implements Builder {
private InputStream content;
private Path contentLocation;
private Type type;
private BuilderImpl() {
}
@Override
public Builder content(InputStream contentStream) {
this.contentLocation = null;
this.content = contentStream;
return this;
}
public void setContent(InputStream contentStream) {
content(contentStream);
}
@Override
public Builder content(Path contentLocation) {
Validate.paramNotNull(contentLocation, "profileLocation");
Validate.validState(Files.exists(contentLocation), "Profile file '%s' does not exist.", contentLocation);
this.content = null;
this.contentLocation = contentLocation;
return this;
}
public void setContentLocation(Path contentLocation) {
content(contentLocation);
}
/**
* Configure the {@link Type} of file that should be loaded.
*/
@Override
public Builder type(Type type) {
this.type = type;
return this;
}
public void setType(Type type) {
type(type);
}
@Override
public ProfileFile build() {
InputStream stream = content != null ? content :
FunctionalUtils.invokeSafely(() -> Files.newInputStream(contentLocation));
Validate.paramNotNull(type, "type");
Validate.paramNotNull(stream, "content");
try {
return new ProfileFile(ProfileFileReader.parseFile(stream, type));
} finally {
IoUtils.closeQuietly(stream, null);
}
}
}
/**
* A mechanism for merging multiple {@link ProfileFile}s together into a single file. This will merge their profiles and
* properties together.
*/
public static final class Aggregator implements SdkBuilder<Aggregator, ProfileFile> {
private List<ProfileFile> files = new ArrayList<>();
/**
* Add a file to be aggregated. In the event that there is a duplicate profile/property pair in the files, files added
* earliest to this aggregator will take precedence, dropping the duplicated properties in the later files.
*/
public Aggregator addFile(ProfileFile file) {
files.add(file);
return this;
}
@Override
public ProfileFile build() {
Map<String, Map<String, Map<String, String>>> aggregateRawProfiles = new LinkedHashMap<>();
for (int i = files.size() - 1; i >= 0; --i) {
files.get(i).profilesAndSectionsMap.entrySet()
.forEach(sectionKeyValue -> addToAggregate(aggregateRawProfiles,
sectionKeyValue.getValue(),
sectionKeyValue.getKey()));
}
return new ProfileFile(aggregateRawProfiles);
}
private void addToAggregate(Map<String, Map<String, Map<String, String>>> aggregateRawProfiles,
Map<String, Profile> profiles, String sectionName) {
aggregateRawProfiles.putIfAbsent(sectionName, new LinkedHashMap<>());
Map<String, Map<String, String>> profileMap = aggregateRawProfiles.get(sectionName);
for (Entry<String, Profile> profile : profiles.entrySet()) {
profileMap.compute(profile.getKey(), (k, current) -> {
if (current == null) {
return new HashMap<>(profile.getValue().properties());
} else {
current.putAll(profile.getValue().properties());
return current;
}
});
}
}
}
}
| 2,420 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileSection.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Enum describing all the valid section names supported by SDK.
* The section declares that the attributes that follow are part of a named collection of attributes.
*/
@SdkInternalApi
public enum ProfileSection {
/**
* An `sso-session` section declares that the attributes that follow (until another section definition is encountered)
* are part of a named collection of attributes.
* This `sso-session` section is referenced by the user when configuring a profile to derive an SSO token.
*/
SSO_SESSION("sso-session", "sso_session");
private final String sectionTitle;
private final String propertyKeyName;
ProfileSection(String title, String propertyKeyName) {
this.sectionTitle = title;
this.propertyKeyName = propertyKeyName;
}
/**
*
* @param sectionTitle The section title in the config or credential file.
* @return ProfileSection enum that has title name as sectionTitle
*/
public static ProfileSection fromSectionTitle(String sectionTitle) {
if (sectionTitle == null) {
return null;
}
for (ProfileSection profileSection : values()) {
if (profileSection.sectionTitle.equals(sectionTitle)) {
return profileSection;
}
}
throw new IllegalArgumentException("Unknown enum value for ProfileSection : " + sectionTitle);
}
/**
*
* @param propertyName The property definition of a key that points to a Section.
* @return ProfileSection enum that corresponds to a propertyKeyName for the given propertyName.
*/
public static ProfileSection fromPropertyKeyName(String propertyName) {
if (propertyName == null) {
return null;
}
for (ProfileSection section : values()) {
if (section.getPropertyKeyName().equals(propertyName)) {
return section;
}
}
throw new IllegalArgumentException("Unknown enum value for ProfileSection : " + propertyName);
}
/**
*
* @return Gets the section title name for the given {@link ProfileSection}.
*/
public String getSectionTitle() {
return sectionTitle;
}
/**
*
* @return Gets the property Hey name for the given {@link ProfileSection}.
*/
public String getPropertyKeyName() {
return propertyKeyName;
}
} | 2,421 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileFileRefresher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* Class used for caching and reloading ProfileFile objects from a Supplier.
*/
@SdkInternalApi
public final class ProfileFileRefresher {
private static final ProfileFileRefreshRecord EMPTY_REFRESH_RECORD = ProfileFileRefreshRecord.builder()
.refreshTime(Instant.MIN)
.build();
private final CachedSupplier<ProfileFileRefreshRecord> profileFileCache;
private volatile ProfileFileRefreshRecord currentRefreshRecord;
private final Supplier<ProfileFile> profileFile;
private final Path profileFilePath;
private final Consumer<ProfileFile> onProfileFileReload;
private final Clock clock;
private ProfileFileRefresher(Builder builder) {
this.clock = builder.clock;
this.profileFile = builder.profileFile;
this.profileFilePath = builder.profileFilePath;
this.onProfileFileReload = builder.onProfileFileReload;
this.profileFileCache = CachedSupplier.builder(this::refreshResult)
.cachedValueName("ProfileFileSupplier()")
.clock(this.clock)
.build();
this.currentRefreshRecord = EMPTY_REFRESH_RECORD;
}
/**
* Builder method to construct instance of ProfileFileRefresher.
*/
public static ProfileFileRefresher.Builder builder() {
return new ProfileFileRefresher.Builder();
}
/**
* Retrieves the cache value or refreshes it if stale.
*/
public ProfileFile refreshIfStale() {
ProfileFileRefreshRecord cachedOrRefreshedRecord = profileFileCache.get();
ProfileFile cachedOrRefreshedProfileFile = cachedOrRefreshedRecord.profileFile;
if (isNewProfileFile(cachedOrRefreshedProfileFile)) {
currentRefreshRecord = cachedOrRefreshedRecord;
}
return cachedOrRefreshedProfileFile;
}
private RefreshResult<ProfileFileRefreshRecord> refreshResult() {
return reloadAsRefreshResultIfStale();
}
private RefreshResult<ProfileFileRefreshRecord> reloadAsRefreshResultIfStale() {
Instant now = clock.instant();
ProfileFileRefreshRecord refreshRecord;
if (canReloadProfileFile() || hasNotBeenPreviouslyLoaded()) {
ProfileFile reloadedProfileFile = reload(profileFile, onProfileFileReload);
refreshRecord = ProfileFileRefreshRecord.builder()
.profileFile(reloadedProfileFile)
.refreshTime(now)
.build();
} else {
refreshRecord = currentRefreshRecord;
}
return wrapIntoRefreshResult(refreshRecord, now);
}
private <T> RefreshResult<T> wrapIntoRefreshResult(T value, Instant staleTime) {
return RefreshResult.builder(value)
.staleTime(staleTime)
.build();
}
private static ProfileFile reload(Supplier<ProfileFile> supplier) {
return supplier.get();
}
private static ProfileFile reload(Supplier<ProfileFile> supplier, Consumer<ProfileFile> consumer) {
ProfileFile reloadedProfileFile = reload(supplier);
consumer.accept(reloadedProfileFile);
return reloadedProfileFile;
}
private boolean isNewProfileFile(ProfileFile profileFile) {
return !Objects.equals(currentRefreshRecord.profileFile, profileFile);
}
private boolean canReloadProfileFile() {
if (Objects.isNull(profileFilePath)) {
return false;
}
try {
Instant lastModifiedInstant = Files.getLastModifiedTime(profileFilePath).toInstant();
return currentRefreshRecord.refreshTime.isBefore(lastModifiedInstant);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private boolean hasNotBeenPreviouslyLoaded() {
return currentRefreshRecord == EMPTY_REFRESH_RECORD;
}
public static final class Builder {
private Supplier<ProfileFile> profileFile;
private Path profileFilePath;
private Consumer<ProfileFile> onProfileFileReload = p -> { };
private Clock clock = Clock.systemUTC();
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileFilePath(Path profileFilePath) {
this.profileFilePath = profileFilePath;
return this;
}
/**
* Sets a clock for managing stale and prefetch durations.
*/
@SdkTestInternalApi
public Builder clock(Clock clock) {
this.clock = clock;
return this;
}
/**
* Sets a custom action to perform when a profile file is reloaded. This action is executed when both the cache is stale
* and the disk file associated with the profile file has been modified since the last load.
*
* @param consumer The action to perform.
*/
public Builder onProfileFileReload(Consumer<ProfileFile> consumer) {
this.onProfileFileReload = consumer;
return this;
}
public ProfileFileRefresher build() {
return new ProfileFileRefresher(this);
}
}
/**
* Class used to encapsulate additional refresh information.
*/
public static final class ProfileFileRefreshRecord {
private final Instant refreshTime;
private final ProfileFile profileFile;
private ProfileFileRefreshRecord(Builder builder) {
this.profileFile = builder.profileFile;
this.refreshTime = builder.refreshTime;
}
/**
* The refreshed ProfileFile instance.
*/
public ProfileFile profileFile() {
return profileFile;
}
/**
* The time at which the RefreshResult was created.
*/
public Instant refreshTime() {
return refreshTime;
}
static Builder builder() {
return new Builder();
}
private static final class Builder {
private Instant refreshTime;
private ProfileFile profileFile;
Builder refreshTime(Instant refreshTime) {
this.refreshTime = refreshTime;
return this;
}
Builder profileFile(ProfileFile profileFile) {
this.profileFile = profileFile;
return this;
}
ProfileFileRefreshRecord build() {
return new ProfileFileRefreshRecord(this);
}
}
}
}
| 2,422 |
0 | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles | Create_ds/aws-sdk-java-v2/core/profiles/src/main/java/software/amazon/awssdk/profiles/internal/ProfileFileReader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.profiles.internal;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Converts an {@link InputStream} to a configuration or credentials file into a map of profiles and their properties.
*
* @see #parseFile(InputStream, ProfileFile.Type)
*/
@SdkInternalApi
public final class ProfileFileReader {
private static final Logger log = Logger.loggerFor(ProfileFileReader.class);
private static final Pattern EMPTY_LINE = Pattern.compile("^[\t ]*$");
private static final Pattern VALID_IDENTIFIER = Pattern.compile("^[A-Za-z0-9_\\-/.%@:\\+]*$");
private ProfileFileReader() {
}
/**
* Parses the input and returns a mutable map from profile name to a map of properties. This will not close the provided
* stream.
*/
public static Map<String, Map<String, Map<String, String>>> parseFile(InputStream profileStream, ProfileFile.Type fileType) {
ParserState state = new ParserState(fileType);
BufferedReader profileReader = new BufferedReader(new InputStreamReader(profileStream, StandardCharsets.UTF_8));
profileReader.lines().forEach(line -> parseLine(state, line));
return state.profiles;
}
/**
* Parse a line and update the parser state.
*/
private static void parseLine(ParserState state, String line) {
++state.currentLineNumber;
if (isEmptyLine(line) || isCommentLine(line)) {
return; // Skip line
}
Optional<String> sectionDefined = sectionDefinitionLine(line);
if (sectionDefined.isPresent()) {
state.sectionReadInProgress = sectionDefined.get();
readSectionProfileDefinitionLine(state, line);
} else if (isProfileDefinitionLine(line)) {
state.sectionReadInProgress = ProfileFile.PROFILES_SECTION_TITLE;
readProfileDefinitionLine(state, line);
} else if (isPropertyContinuationLine(line)) {
readPropertyContinuationLine(state, line);
} else {
readPropertyDefinitionLine(state, line);
}
}
/**
* Read a profile line and update the parser state with the results. This marks future properties as being in this profile.
*
* Configuration Files: [ Whitespace? profile Whitespace Identifier Whitespace? ] Whitespace? CommentLine?
* Credentials Files: [ Whitespace? Identifier Whitespace? ] Whitespace? CommentLine?
*/
private static void readProfileDefinitionLine(ParserState state, String line) {
// Profile definitions do not require a space between the closing bracket and the comment delimiter
String lineWithoutComments = removeTrailingComments(line, "#", ";");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Validate.isTrue(lineWithoutWhitespace.endsWith("]"),
"Profile definition must end with ']' on line " + state.currentLineNumber);
Optional<String> profileName = parseProfileDefinition(state, lineWithoutWhitespace);
updateStateBasedOnProfileName(state, profileName);
}
/**
* Read a property definition line and update the parser state with the results. This adds the property to the current profile
* and marks future property continuations as being part of this property.
*
* Identifier Whitespace? = Whitespace? Value? Whitespace? (Whitespace CommentLine)?
*/
private static void readPropertyDefinitionLine(ParserState state, String line) {
// If we're in an invalid profile, ignore its properties
if (state.ignoringCurrentProfile) {
return;
}
Validate.isTrue(state.currentProfileBeingRead != null,
"Expected a profile definition on line " + state.currentLineNumber);
// Property definition comments must have whitespace before them, or they will be considered part of the value
String lineWithoutComments = removeTrailingComments(line, " #", " ;", "\t#", "\t;");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Optional<Pair<String, String>> propertyDefinition = parsePropertyDefinition(state, lineWithoutWhitespace);
// If we couldn't get the property key and value, ignore this entire property.
if (!propertyDefinition.isPresent()) {
state.ignoringCurrentProperty = true;
return;
}
Pair<String, String> property = propertyDefinition.get();
if (state.profiles.get(state.sectionReadInProgress).get(state.currentProfileBeingRead).containsKey(property.left())) {
log.warn(() -> "Warning: Duplicate property '" + property.left() + "' detected on line " + state.currentLineNumber +
". The later one in the file will be used.");
}
state.currentPropertyBeingRead = property.left();
state.ignoringCurrentProperty = false;
state.validatingContinuationsAsSubProperties = property.right().equals("");
state.profiles.get(state.sectionReadInProgress)
.get(state.currentProfileBeingRead).put(property.left(), property.right());
}
/**
* Read a property continuation line and update the parser state with the results. This adds the value in the continuation
* to the current property, prefixed with a newline.
*
* Non-Blank Parent Property: Whitespace Value Whitespace?
* Blank Parent Property (Sub-Property): Whitespace Identifier Whitespace? = Whitespace? Value Whitespace?
*/
private static void readPropertyContinuationLine(ParserState state, String line) {
// If we're in an invalid profile or property, ignore its continuations
if (state.ignoringCurrentProfile || state.ignoringCurrentProperty) {
return;
}
Validate.isTrue(state.currentProfileBeingRead != null && state.currentPropertyBeingRead != null,
"Expected a profile or property definition on line " + state.currentLineNumber);
// Comments are not removed on property continuation lines. They're considered part of the value.
line = StringUtils.trim(line);
Map<String, String> profileProperties = state.profiles.get(state.sectionReadInProgress)
.get(state.currentProfileBeingRead);
String currentPropertyValue = profileProperties.get(state.currentPropertyBeingRead);
String newPropertyValue = currentPropertyValue + "\n" + line;
// If this is a sub-property, make sure it can be parsed correctly by the CLI.
if (state.validatingContinuationsAsSubProperties) {
parsePropertyDefinition(state, line);
}
profileProperties.put(state.currentPropertyBeingRead, newPropertyValue);
}
/**
* Given a profile line, load the profile name based on the file type. If the profile name is invalid for the file type,
* this will return empty.
*/
private static Optional<String> parseProfileDefinition(ParserState state, String lineWithoutWhitespace) {
String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
boolean hasProfilePrefix = rawProfileName.startsWith("profile ") || rawProfileName.startsWith("profile\t");
String standardizedProfileName;
if (state.fileType == ProfileFile.Type.CONFIGURATION) {
if (hasProfilePrefix) {
standardizedProfileName = StringUtils.trim(rawProfileName.substring(ProfileFile.PROFILES_SECTION_TITLE.length()));
} else if (rawProfileName.equals("default")) {
standardizedProfileName = "default";
} else {
log.warn(() -> "Ignoring profile '" + rawProfileName + "' on line " + state.currentLineNumber + " because it " +
"did not start with 'profile ' and it was not 'default'.");
return Optional.empty();
}
} else if (state.fileType == ProfileFile.Type.CREDENTIALS) {
standardizedProfileName = rawProfileName;
} else {
throw new IllegalStateException("Unknown profile file type: " + state.fileType);
}
String profileName = StringUtils.trim(standardizedProfileName);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(profileName)) {
log.warn(() -> "Ignoring profile '" + standardizedProfileName + "' on line " + state.currentLineNumber + " because " +
"it was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
// [profile default] must take priority over [default] in configuration files.
boolean isDefaultProfile = profileName.equals("default");
boolean seenProfileBefore = state.profiles.get(ProfileFile.PROFILES_SECTION_TITLE).containsKey(profileName);
if (state.fileType == ProfileFile.Type.CONFIGURATION && isDefaultProfile && seenProfileBefore) {
if (!hasProfilePrefix && state.seenDefaultProfileWithProfilePrefix) {
log.warn(() -> "Ignoring profile '[default]' on line " + state.currentLineNumber + ", because " +
"'[profile default]' was already seen in the same file.");
return Optional.empty();
} else if (hasProfilePrefix && !state.seenDefaultProfileWithProfilePrefix) {
log.warn(() -> "Ignoring earlier-seen '[default]', because '[profile default]' was found on line " +
state.currentLineNumber);
state.profiles.get(ProfileFile.PROFILES_SECTION_TITLE).remove("default");
}
}
if (isDefaultProfile && hasProfilePrefix) {
state.seenDefaultProfileWithProfilePrefix = true;
}
return Optional.of(profileName);
}
/**
* Given a property line, load the property key and value. If the property line is invalid and should be ignored, this will
* return empty.
*/
private static Optional<Pair<String, String>> parsePropertyDefinition(ParserState state, String line) {
int firstEqualsLocation = line.indexOf('=');
Validate.isTrue(firstEqualsLocation != -1, "Expected an '=' sign defining a property on line " + state.currentLineNumber);
String propertyKey = StringUtils.trim(line.substring(0, firstEqualsLocation));
String propertyValue = StringUtils.trim(line.substring(firstEqualsLocation + 1));
Validate.isTrue(!propertyKey.isEmpty(), "Property did not have a name on line " + state.currentLineNumber);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(propertyKey)) {
log.warn(() -> "Ignoring property '" + propertyKey + "' on line " + state.currentLineNumber + " because " +
"its name was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
return Optional.of(Pair.of(propertyKey, propertyValue));
}
/**
* Remove trailing comments from the provided line, using the provided patterns to find where the comment starts.
*
* Profile definitions don't require spaces before comments.
* Property definitions require spaces before comments.
* Property continuations don't allow trailing comments. They're considered part of the value.
*/
private static String removeTrailingComments(String line, String... commentPatterns) {
return line.substring(0, findEarliestMatch(line, commentPatterns));
}
/**
* Search the provided string for the requested patterns, returning the index of the match that is closest to the front of the
* string. If no match is found, this returns the length of the string (one past the final index in the string).
*/
private static int findEarliestMatch(String line, String... searchPatterns) {
return Stream.of(searchPatterns)
.mapToInt(line::indexOf)
.filter(location -> location >= 0)
.min()
.orElseGet(line::length);
}
private static boolean isEmptyLine(String line) {
return EMPTY_LINE.matcher(line).matches();
}
private static boolean isCommentLine(String line) {
return line.startsWith("#") || line.startsWith(";");
}
private static boolean isProfileDefinitionLine(String line) {
return line.startsWith("[");
}
private static boolean isPropertyContinuationLine(String line) {
return line.startsWith(" ") || line.startsWith("\t");
}
private static boolean isValidIdentifier(String value) {
return VALID_IDENTIFIER.matcher(value).matches();
}
private static Optional<String> sectionDefinitionLine(String line) {
if (line.startsWith("[")) {
String lineWithoutBrackets = line.substring(1, line.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
return Arrays.stream(ProfileSection.values())
.filter(x -> !ProfileFile.PROFILES_SECTION_TITLE.equals(x.getSectionTitle()))
.map(title -> title.getSectionTitle())
.filter(reservedTitle -> rawProfileName.startsWith(String.format("%s ", reservedTitle))
|| rawProfileName.startsWith(String.format("%s\t", reservedTitle)))
.findFirst();
}
return Optional.empty();
}
private static void readSectionProfileDefinitionLine(ParserState state, String line) {
// Profile definitions do not require a space between the closing bracket and the comment delimiter
String lineWithoutComments = removeTrailingComments(line, "#", ";");
String lineWithoutWhitespace = StringUtils.trim(lineWithoutComments);
Validate.isTrue(lineWithoutWhitespace.endsWith("]"),
"Section definition must end with ']' on line " + state.currentLineNumber);
Optional<String> profileName = parseSpecialProfileDefinition(state, lineWithoutWhitespace);
updateStateBasedOnProfileName(state, profileName);
}
private static void updateStateBasedOnProfileName(ParserState state, Optional<String> profileName) {
// If we couldn't get the profile name, ignore this entire profile.
if (!profileName.isPresent()) {
state.ignoringCurrentProfile = true;
return;
}
state.currentProfileBeingRead = profileName.get();
state.currentPropertyBeingRead = null;
state.ignoringCurrentProfile = false;
state.ignoringCurrentProperty = false;
// If we've seen this profile before, don't override the existing properties. We'll be merging them.
state.profiles.get(state.sectionReadInProgress).computeIfAbsent(profileName.get(),
i -> new LinkedHashMap<>());
}
private static Optional<String> parseSpecialProfileDefinition(ParserState state, String lineWithoutWhitespace) {
String lineWithoutBrackets = lineWithoutWhitespace.substring(1, lineWithoutWhitespace.length() - 1);
String rawProfileName = StringUtils.trim(lineWithoutBrackets);
String profilePrefix =
Arrays.stream(ProfileSection.values())
.filter(x -> !x.getSectionTitle().equals(ProfileFile.PROFILES_SECTION_TITLE))
.map(x -> x.getSectionTitle())
.filter(
title -> rawProfileName.startsWith(String.format("%s ", title))
|| rawProfileName.startsWith(String.format("%s\t", title)))
.findFirst()
.orElse(null);
if (state.fileType != ProfileFile.Type.CONFIGURATION || profilePrefix == null) {
return Optional.empty();
}
String standardizedProfileName = StringUtils.trim(rawProfileName.substring(profilePrefix.length()));
String profilePrefixName = StringUtils.trim(standardizedProfileName);
// If the profile name includes invalid characters, it should be ignored.
if (!isValidIdentifier(profilePrefixName)) {
log.warn(() -> "Ignoring " + standardizedProfileName + "' on line " + state.currentLineNumber + " because " +
"it was not alphanumeric with only these special characters: - / . % @ _ : +");
return Optional.empty();
}
return Optional.of(profilePrefixName);
}
/**
* When {@link #parseFile(InputStream, ProfileFile.Type)} is invoked, this is used to track the state of the parser as it
* reads the input stream.
*/
private static final class ParserState {
/**
* The type of file being parsed.
*/
private final ProfileFile.Type fileType;
/**
* The line currently being parsed. Useful for error messages.
*/
private int currentLineNumber = 0;
/**
* Which profile is currently being read. Updated after each [profile] has been successfully read.
*
* Properties read will be added to this profile.
*/
private String currentProfileBeingRead = null;
/**
* Which property is currently being read. Updated after each foo = bar has been successfully read.
*
* Property continuations read will be appended to this property.
*/
private String currentPropertyBeingRead = null;
/**
* Whether we are ignoring the current profile. Updated after a [profile] has been identified as being invalid, but we
* do not want to fail parsing the whole file.
*
* All lines other than property definitions read while this is true are dropped.
*/
private boolean ignoringCurrentProfile = false;
/**
* Whether we are ignoring the current property. Updated after a foo = bar has been identified as being invalid, but we
* do not want to fail parsing the whole file.
*
* All property continuations read while this are true are dropped.
*/
private boolean ignoringCurrentProperty = false;
/**
* Whether we are validating the current property value continuations are formatted like sub-properties. This will ensure
* that when the same file is used with the CLI, it won't cause failures.
*/
private boolean validatingContinuationsAsSubProperties = false;
/**
* Whether within the current file, we've seen the [profile default] profile definition. This is only used for
* configuration files. If this is true we'll ignore [default] profile definitions, because [profile default] takes
* precedence.
*/
private boolean seenDefaultProfileWithProfilePrefix = false;
/**
* Whether a section read is in progress. This is used to segregate section properties and profile properties.
*/
private String sectionReadInProgress;
/**
* The profiles read so far by the parser.
*/
private Map<String, Map<String, Map<String, String>>> profiles = new LinkedHashMap<>();
private ParserState(ProfileFile.Type fileType) {
profiles.put(ProfileFile.PROFILES_SECTION_TITLE, new LinkedHashMap<>());
Arrays.stream(ProfileSection.values())
.forEach(profileSection -> profiles.put(profileSection.getSectionTitle(), new LinkedHashMap<>()));
this.fileType = fileType;
}
}
}
| 2,423 |
0 | Create_ds/aws-sdk-java-v2/core/http-auth-aws-eventstream/src/main/java/software/amazon/awssdk/http/auth/aws | Create_ds/aws-sdk-java-v2/core/http-auth-aws-eventstream/src/main/java/software/amazon/awssdk/http/auth/aws/eventstream/HttpAuthAwsEventStream.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.http.auth.aws.eventstream;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* This is a place-holder class for this module, http-auth-aws-eventstream. In the event that we decide to move back
* event-stream signer logic back to this dedicated module, no issues will arise. This module should be an optional
* dependency in consumers (http-auth-aws), and should bring in the required dependencies (eventstream).
*/
@SdkProtectedApi
public final class HttpAuthAwsEventStream {
}
| 2,424 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/GreedyPathMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class GreedyPathMarshallerTest {
private final PathMarshaller marshaller = PathMarshaller.GREEDY;
@Test(expected = NullPointerException.class)
public void nullPathValue_ThrowsException() {
marshaller.marshall("/foo/{greedyParam+}", "greedyParam", null);
}
@Test(expected = IllegalArgumentException.class)
public void emptyPathValue_ThrowsException() {
marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "");
}
@Test
public void nonEmptyPathValue_ReplacesPlaceholder() {
assertEquals("/foo/nonEmpty", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "nonEmpty"));
}
@Test
public void pathValueWithSlashes_NotUrlEncodedWhenReplaced() {
assertEquals("/foo/my/greedy/value", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "my/greedy/value"));
}
@Test
public void pathValueWithLeadingSlash_TrimmedBeforeReplaced() {
assertEquals("/foo/my/greedy/value", marshaller.marshall("/foo/{greedyParam+}", "greedyParam", "/my/greedy/value"));
}
}
| 2,425 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/NonGreedyPathMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NonGreedyPathMarshallerTest {
private final PathMarshaller marshaller = PathMarshaller.NON_GREEDY;
@Test(expected = NullPointerException.class)
public void nullPathValue_ThrowsException() {
marshaller.marshall("/foo/{pathParam}", "pathParam", null);
}
@Test(expected = IllegalArgumentException.class)
public void emptyPathValue_ThrowsException() {
marshaller.marshall("/foo/{pathParam}", "pathParam", "");
}
@Test
public void nonEmptyPathValue_ReplacesPlaceholder() {
assertEquals("/foo/nonEmpty", marshaller.marshall("/foo/{pathParam}", "pathParam", "nonEmpty"));
}
@Test
public void pathValueWithSlashes_UrlEncodedWhenReplaced() {
assertEquals("/foo/has%2Fslash", marshaller.marshall("/foo/{pathParam}", "pathParam", "has/slash"));
}
}
| 2,426 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/test/java/software/amazon/awssdk/protocols/core/ProtocolUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
public class ProtocolUtilsTest {
@Test
public void createSdkHttpRequest_SetsHttpMethodAndEndpointCorrectly() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.build(), URI.create("http://localhost:8080"));
assertThat(sdkHttpRequest.protocol()).isEqualTo("http");
assertThat(sdkHttpRequest.host()).isEqualTo("localhost");
assertThat(sdkHttpRequest.port()).isEqualTo(8080);
assertThat(sdkHttpRequest.method()).isEqualTo(SdkHttpMethod.DELETE);
}
@Test
public void createSdkHttpRequest_EndpointWithPathSetCorrectly() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar");
}
@Test
public void createSdkHttpRequest_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("/baz")
.build(), URI.create("http://localhost/foo/bar/"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoTrailingSlashInEndpointPath_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("/baz")
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoLeadingSlashInRequestUri_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("baz")
.build(), URI.create("http://localhost/foo/bar/"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void createSdkHttpRequest_NoTrailingOrLeadingSlash_RequestUriAppendedToEndpointPath() {
SdkHttpFullRequest.Builder sdkHttpRequest = ProtocolUtils.createSdkHttpRequest(
OperationInfo.builder()
.httpMethod(SdkHttpMethod.DELETE)
.requestUri("baz")
.build(), URI.create("http://localhost/foo/bar"));
assertThat(sdkHttpRequest.encodedPath()).isEqualTo("/foo/bar/baz");
}
@Test
public void request_null_returns_null() {
assertNull(ProtocolUtils.addStaticQueryParametersToRequest(null,
"foo"));
}
@Test
public void uri_resource_path_null_returns_null() {
assertNull(ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), null));
}
private SdkHttpFullRequest.Builder emptyRequest() {
return SdkHttpFullRequest.builder();
}
@Test
public void uri_resource_path_doesnot_have_static_query_params_returns_uri_resource_path() {
final String uriResourcePath = "/foo/bar";
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), uriResourcePath));
}
@Test
public void uri_resource_path_ends_with_question_mark_returns_path_removed_with_question_mark() {
final String expectedResourcePath = "/foo/bar";
final String pathWithEmptyStaticQueryParams = expectedResourcePath + "?";
assertEquals(expectedResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(emptyRequest(), pathWithEmptyStaticQueryParams));
}
@Test
public void queryparam_value_empty_adds_parameter_with_empty_string_to_request() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param1=";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(request,
uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param1"));
assertEquals(singletonList(""), request.rawQueryParameters().get("param1"));
}
@Test
public void static_queryparams_in_path_added_to_request() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param1=value1¶m2=value2";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils
.addStaticQueryParametersToRequest(request,
uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param1"));
assertTrue(request.rawQueryParameters().containsKey("param2"));
assertEquals(singletonList("value1"), request.rawQueryParameters().get("param1"));
assertEquals(singletonList("value2"), request.rawQueryParameters().get("param2"));
}
@Test
public void queryparam_without_value_returns_list_containing_null_value() {
final String uriResourcePath = "/foo/bar";
final String uriResourcePathWithParams =
uriResourcePath + "?param";
SdkHttpFullRequest.Builder request = emptyRequest();
assertEquals(uriResourcePath, ProtocolUtils.addStaticQueryParametersToRequest(request, uriResourcePathWithParams));
assertTrue(request.rawQueryParameters().containsKey("param"));
assertEquals(singletonList((String) null), request.rawQueryParameters().get("param"));
}
}
| 2,427 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/Marshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Marker interface for marshallers.
*
* @param <T> Type being marshalled.
*/
@SdkProtectedApi
public interface Marshaller<T> {
}
| 2,428 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ProtocolMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
/**
* Interface used by generated marshallers to marshall a Java POJO.
*/
@SdkProtectedApi
public interface ProtocolMarshaller<MarshalledT> {
MarshalledT marshall(SdkPojo pojo);
}
| 2,429 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/OperationMetadataAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Key for additional metadata in {@link OperationInfo}. Used to register protocol specific metadata about
* an operation.
*
* @param <T> Type of metadata.
*/
@SdkProtectedApi
public final class OperationMetadataAttribute<T> extends AttributeMap.Key<T> {
public OperationMetadataAttribute(Class<T> valueType) {
super(valueType);
}
}
| 2,430 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/StringToValueConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.math.BigDecimal;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Converter implementations that transform a String to a specified type.
*/
@SdkProtectedApi
public final class StringToValueConverter {
/**
* Interface to convert a String into another type.
*
* @param <T> Type to convert to.
*/
@FunctionalInterface
public interface StringToValue<T> {
/**
* Converts the value to a string.
*
* @param s Value to convert from.
* @param sdkField {@link SdkField} containing metadata about the member being unmarshalled.
* @return Unmarshalled value.
*/
T convert(String s, SdkField<T> sdkField);
}
/**
* Simple interface to convert a String to another type. Useful for implementations that don't need the {@link SdkField}.
*
* @param <T> Type to convert to.
*/
@FunctionalInterface
public interface SimpleStringToValue<T> extends StringToValue<T> {
@Override
default T convert(String s, SdkField<T> sdkField) {
return convert(s);
}
/**
* Converts the value to a string.
*
* @param s Value to convert from.
* @return Unmarshalled value.
*/
T convert(String s);
}
/**
* Identity converter.
*/
public static final SimpleStringToValue<String> TO_STRING = val -> val;
public static final SimpleStringToValue<Integer> TO_INTEGER = Integer::parseInt;
public static final SimpleStringToValue<Long> TO_LONG = Long::parseLong;
public static final SimpleStringToValue<Short> TO_SHORT = Short::parseShort;
public static final SimpleStringToValue<Float> TO_FLOAT = Float::parseFloat;
public static final SimpleStringToValue<Double> TO_DOUBLE = Double::parseDouble;
public static final SimpleStringToValue<BigDecimal> TO_BIG_DECIMAL = BigDecimal::new;
public static final SimpleStringToValue<Boolean> TO_BOOLEAN = Boolean::parseBoolean;
public static final SimpleStringToValue<SdkBytes> TO_SDK_BYTES = StringToValueConverter::toSdkBytes;
private StringToValueConverter() {
}
private static SdkBytes toSdkBytes(String s) {
return SdkBytes.fromByteArray(BinaryUtils.fromBase64(s));
}
}
| 2,431 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ProtocolUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Utilities common to all protocols.
*/
@SdkProtectedApi
public final class ProtocolUtils {
private ProtocolUtils() {
}
/**
* Creates the basic {@link SdkHttpFullRequest} with information from the {@link OperationInfo} and the endpoint.
*
* @param operationInfo Metadata about operation, contains HTTP method and request URI.
* @param endpoint Endpoint of request.
* @return Mutable {@link SdkHttpFullRequest.Builder} with HTTP method, URI, and static query parameters set.
*/
public static SdkHttpFullRequest.Builder createSdkHttpRequest(OperationInfo operationInfo, URI endpoint) {
SdkHttpFullRequest.Builder request = SdkHttpFullRequest
.builder()
.method(operationInfo.httpMethod())
.uri(endpoint);
return request.encodedPath(SdkHttpUtils.appendUri(request.encodedPath(),
addStaticQueryParametersToRequest(request, operationInfo.requestUri())));
}
/**
* Identifies the static query parameters in Uri resource path for and adds it to
* request.
*
* Returns the updated uriResourcePath.
*/
@SdkTestInternalApi
static String addStaticQueryParametersToRequest(SdkHttpFullRequest.Builder request,
String uriResourcePath) {
if (request == null || uriResourcePath == null) {
return null;
}
String resourcePath = uriResourcePath;
int index = resourcePath.indexOf('?');
if (index != -1) {
String queryString = resourcePath.substring(index + 1);
resourcePath = resourcePath.substring(0, index);
for (String s : queryString.split("[;&]")) {
index = s.indexOf('=');
if (index != -1) {
request.putRawQueryParameter(s.substring(0, index), s.substring(index + 1));
} else {
request.putRawQueryParameter(s, (String) null);
}
}
}
return resourcePath;
}
}
| 2,432 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/OperationInfo.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Static information about an API operation used to marshall it correctly.
*/
@SdkProtectedApi
public final class OperationInfo {
private final String requestUri;
private final SdkHttpMethod httpMethod;
private final String operationIdentifier;
private final String apiVersion;
private final boolean hasExplicitPayloadMember;
private final boolean hasPayloadMembers;
private final boolean hasImplicitPayloadMembers;
private final boolean hasStreamingInput;
private final boolean hasEventStreamingInput;
private final boolean hasEvent;
private final AttributeMap additionalMetadata;
private OperationInfo(Builder builder) {
this.requestUri = builder.requestUri;
this.httpMethod = builder.httpMethod;
this.operationIdentifier = builder.operationIdentifier;
this.apiVersion = builder.apiVersion;
this.hasExplicitPayloadMember = builder.hasExplicitPayloadMember;
this.hasImplicitPayloadMembers = builder.hasImplicitPayloadMembers;
this.hasPayloadMembers = builder.hasPayloadMembers;
this.hasStreamingInput = builder.hasStreamingInput;
this.additionalMetadata = builder.additionalMetadata.build();
this.hasEventStreamingInput = builder.hasEventStreamingInput;
this.hasEvent = builder.hasEvent;
}
/**
* @return Request URI for operation (may contain placeholders for members bound to the uri).
*/
public String requestUri() {
return requestUri;
}
/**
* @return HTTP Method that should be used when sending the request.
*/
public SdkHttpMethod httpMethod() {
return httpMethod;
}
/**
* @return Identifier for the operation/API being invoked. This is used for RPC based protocols that
* need to identify which action is being taken. For Query/EC2 protocol this is sent as the 'Action' query
* parameter, for JSON RPC this is sent as the 'X-Amz-Target' header.
*/
public String operationIdentifier() {
return operationIdentifier;
}
/**
* @return Version of the service's API. For Query protocol this is sent as a 'Version' query parameter.
*/
public String apiVersion() {
return apiVersion;
}
/**
* @return True if the operation has a member that's explicitly marked as the payload. False otherwise. (Applicable only to
* RESTUL protocols).
*/
public boolean hasExplicitPayloadMember() {
return hasExplicitPayloadMember;
}
/**
* @return True if the operation has members bound to the payload. Some requests (especially GET and DELETE) may not
* have any members bound to the payload. (Applicable only to RESTFUL protocols).
*/
public boolean hasPayloadMembers() {
return hasPayloadMembers;
}
/**
* @return True if the operation has members that are not explicitly bound to a marshalling location, and thus are
* implicitly bound to the body.
*/
public boolean hasImplicitPayloadMembers() {
return hasImplicitPayloadMembers;
}
/**
* @return True if the operation has streaming input.
*/
public boolean hasStreamingInput() {
return hasStreamingInput;
}
/**
* @return True if the operation has event streaming input.
*/
public boolean hasEventStreamingInput() {
return hasEventStreamingInput;
}
/**
* @return True if the operation has event.
*/
public boolean hasEvent() {
return hasEvent;
}
/**
* Gets an unmodeled piece of metadata. Useful for protocol specific options.
*
* @param key Key the metadata was registered under.
* @param <T> Type of metadata being requested.
* @return The value of the additional metadata being requested or null if it's not present.
*/
public <T> T addtionalMetadata(OperationMetadataAttribute<T> key) {
return additionalMetadata.get(key);
}
/**
* @return Builder instance to construct a {@link OperationInfo}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link OperationInfo}.
*/
public static final class Builder {
private String requestUri;
private SdkHttpMethod httpMethod;
private String operationIdentifier;
private String apiVersion;
private boolean hasExplicitPayloadMember;
private boolean hasImplicitPayloadMembers;
private boolean hasPayloadMembers;
private boolean hasStreamingInput;
private boolean hasEventStreamingInput;
private boolean hasEvent;
private AttributeMap.Builder additionalMetadata = AttributeMap.builder();
private Builder() {
}
public Builder requestUri(String requestUri) {
this.requestUri = requestUri;
return this;
}
public Builder httpMethod(SdkHttpMethod httpMethod) {
this.httpMethod = httpMethod;
return this;
}
public Builder operationIdentifier(String operationIdentifier) {
this.operationIdentifier = operationIdentifier;
return this;
}
public Builder apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
public Builder hasExplicitPayloadMember(boolean hasExplicitPayloadMember) {
this.hasExplicitPayloadMember = hasExplicitPayloadMember;
return this;
}
public Builder hasPayloadMembers(boolean hasPayloadMembers) {
this.hasPayloadMembers = hasPayloadMembers;
return this;
}
public Builder hasImplicitPayloadMembers(boolean hasImplicitPayloadMembers) {
this.hasImplicitPayloadMembers = hasImplicitPayloadMembers;
return this;
}
public Builder hasStreamingInput(boolean hasStreamingInput) {
this.hasStreamingInput = hasStreamingInput;
return this;
}
public Builder hasEventStreamingInput(boolean hasEventStreamingInput) {
this.hasEventStreamingInput = hasEventStreamingInput;
return this;
}
public Builder hasEvent(boolean hasEvent) {
this.hasEvent = hasEvent;
return this;
}
/**
* Adds additional unmodeled metadata to the {@link OperationInfo}. Useful for communicating protocol
* specific operation metadata.
*
* @param key Key to register metadata.
* @param value Value of metadata.
* @param <T> Type of metadata being registered.
* @return This builder for method chaining.
*/
public <T> Builder putAdditionalMetadata(OperationMetadataAttribute<T> key, T value) {
additionalMetadata.put(key, value);
return this;
}
/**
* @return An immutable {@link OperationInfo} object.
*/
public OperationInfo build() {
return new OperationInfo(this);
}
}
}
| 2,433 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/InstantToString.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.time.Instant;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.protocols.core.ValueToStringConverter.ValueToString;
import software.amazon.awssdk.utils.DateUtils;
/**
* Implementation of {@link ValueToString} that converts and {@link Instant} to a string. * Respects the
* {@link TimestampFormatTrait} if present.
*/
@SdkProtectedApi
public final class InstantToString implements ValueToString<Instant> {
private final Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats;
private InstantToString(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
this.defaultFormats = defaultFormats;
}
@Override
public String convert(Instant val, SdkField<Instant> sdkField) {
if (val == null) {
return null;
}
TimestampFormatTrait.Format format =
sdkField.getOptionalTrait(TimestampFormatTrait.class)
.map(TimestampFormatTrait::format)
.orElseGet(() -> getDefaultTimestampFormat(sdkField.location(), defaultFormats));
switch (format) {
case ISO_8601:
return DateUtils.formatIso8601Date(val);
case RFC_822:
return DateUtils.formatRfc822Date(val);
case UNIX_TIMESTAMP:
return DateUtils.formatUnixTimestampInstant(val);
default:
throw SdkClientException.create("Unsupported timestamp format - " + format);
}
}
private TimestampFormatTrait.Format getDefaultTimestampFormat(
MarshallLocation location, Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
TimestampFormatTrait.Format format = defaultFormats.get(location);
if (format == null) {
throw SdkClientException.create("No default timestamp marshaller found for location - " + location);
}
return format;
}
public static InstantToString create(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
return new InstantToString(defaultFormats);
}
}
| 2,434 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/PathMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
@SdkProtectedApi
public abstract class PathMarshaller {
/**
* Marshaller for non greedy path labels. Value is URL encoded and then replaced in the request URI.
*/
public static final PathMarshaller NON_GREEDY = new NonGreedyPathMarshaller();
/**
* Marshaller for greedy path labels. Value is not URL encoded and replaced in the request URI.
*/
public static final PathMarshaller GREEDY = new GreedyPathMarshaller();
/**
* Marshaller for greedy path labels that allows leading slahes. Value is not URL encoded and
* replaced in the request URI.
*/
public static final PathMarshaller GREEDY_WITH_SLASHES = new GreedyLeadingSlashPathMarshaller();
private PathMarshaller() {
}
private static String trimLeadingSlash(String value) {
if (value.startsWith("/")) {
return value.replaceFirst("/", "");
}
return value;
}
/**
* @param resourcePath Current resource path with path param placeholder
* @param paramName Name of parameter (i.e. placeholder value {Foo})
* @param pathValue String value of path parameter.
* @return New URI with placeholder replaced with marshalled value.
*/
public abstract String marshall(String resourcePath, String paramName, String pathValue);
private static class NonGreedyPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath, "{" + paramName + "}", SdkHttpUtils.urlEncode(pathValue));
}
}
private static class GreedyPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath,
"{" + paramName + "+}",
SdkHttpUtils.urlEncodeIgnoreSlashes(trimLeadingSlash(pathValue)));
}
}
private static class GreedyLeadingSlashPathMarshaller extends PathMarshaller {
@Override
public String marshall(String resourcePath, String paramName, String pathValue) {
Validate.notEmpty(pathValue, "%s cannot be empty.", paramName);
return StringUtils.replace(resourcePath, "{" + paramName + "+}", SdkHttpUtils.urlEncodeIgnoreSlashes(pathValue));
}
}
}
| 2,435 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ValueToStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.math.BigDecimal;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Converts various types to Strings. Used for Query Param/Header/Path marshalling.
*/
@SdkProtectedApi
public final class ValueToStringConverter {
/**
* Interface to convert a type to a String.
*
* @param <T> Type to convert.
*/
@FunctionalInterface
public interface ValueToString<T> {
/**
* Converts the value to a string.
*
* @param t Value to convert.
* @param field {@link SdkField} containing metadata about the member being marshalled.
* @return String value.
*/
String convert(T t, SdkField<T> field);
}
/**
* Simple interface to convert a type to a String. Useful for implementations that don't need the {@link SdkField}.
*
* @param <T> Type to convert.
*/
@FunctionalInterface
public interface SimpleValueToString<T> extends ValueToString<T> {
@Override
default String convert(T t, SdkField<T> field) {
return convert(t);
}
/**
* Converts the value to a string.
*
* @param t Value to convert.
* @return String value.
*/
String convert(T t);
}
/**
* Identity converter.
*/
public static final SimpleValueToString<String> FROM_STRING = val -> val;
public static final SimpleValueToString<Integer> FROM_INTEGER = Object::toString;
public static final SimpleValueToString<Long> FROM_LONG = Object::toString;
public static final SimpleValueToString<Short> FROM_SHORT = Object::toString;
public static final SimpleValueToString<Float> FROM_FLOAT = Object::toString;
public static final SimpleValueToString<Double> FROM_DOUBLE = Object::toString;
public static final SimpleValueToString<BigDecimal> FROM_BIG_DECIMAL = Object::toString;
/**
* Marshalls boolean as a literal 'true' or 'false' string.
*/
public static final SimpleValueToString<Boolean> FROM_BOOLEAN = Object::toString;
/**
* Marshalls bytes as a Base64 string.
*/
public static final SimpleValueToString<SdkBytes> FROM_SDK_BYTES = b -> BinaryUtils.toBase64(b.asByteArray());
private ValueToStringConverter() {
}
}
| 2,436 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/StringToInstant.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.time.Instant;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.utils.DateUtils;
/**
* Implementation of {@link StringToValueConverter.StringToValue} that converts a string to an {@link Instant} type.
* Respects the {@link TimestampFormatTrait} if present.
*/
@SdkProtectedApi
public final class StringToInstant implements StringToValueConverter.StringToValue<Instant> {
/**
* Default formats for the given location.
*/
private final Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats;
private StringToInstant(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
this.defaultFormats = defaultFormats;
}
@Override
public Instant convert(String value, SdkField<Instant> field) {
if (value == null) {
return null;
}
TimestampFormatTrait.Format format = resolveTimestampFormat(field);
switch (format) {
case ISO_8601:
return DateUtils.parseIso8601Date(value);
case UNIX_TIMESTAMP:
return safeParseDate(DateUtils::parseUnixTimestampInstant).apply(value);
case UNIX_TIMESTAMP_MILLIS:
return safeParseDate(DateUtils::parseUnixTimestampMillisInstant).apply(value);
case RFC_822:
return DateUtils.parseRfc822Date(value);
default:
throw SdkClientException.create("Unrecognized timestamp format - " + format);
}
}
/**
* Wraps date unmarshalling function to handle the {@link NumberFormatException}.
* @param dateUnmarshaller Original date unmarshaller function.
* @return New date unmarshaller function with exception handling.
*/
private Function<String, Instant> safeParseDate(Function<String, Instant> dateUnmarshaller) {
return value -> {
try {
return dateUnmarshaller.apply(value);
} catch (NumberFormatException e) {
throw SdkClientException.builder()
.message("Unable to parse date : " + value)
.cause(e)
.build();
}
};
}
private TimestampFormatTrait.Format resolveTimestampFormat(SdkField<Instant> field) {
TimestampFormatTrait trait = field.getTrait(TimestampFormatTrait.class);
if (trait == null) {
TimestampFormatTrait.Format format = defaultFormats.get(field.location());
if (format == null) {
throw SdkClientException.create(
String.format("Timestamps are not supported for this location (%s)", field.location()));
}
return format;
} else {
return trait.format();
}
}
/**
* @param defaultFormats Default formats for each {@link MarshallLocation} as defined by the protocol.
* @return New {@link StringToValueConverter.StringToValue} for {@link Instant} types.
*/
public static StringToInstant create(Map<MarshallLocation, TimestampFormatTrait.Format> defaultFormats) {
return new StringToInstant(defaultFormats);
}
}
| 2,437 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/ExceptionMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
/**
* Metadata needed to unmarshall a modeled exception.
*/
@SdkProtectedApi
public final class ExceptionMetadata {
private final String errorCode;
private final Supplier<SdkPojo> exceptionBuilderSupplier;
private final Integer httpStatusCode;
private ExceptionMetadata(Builder builder) {
this.errorCode = builder.errorCode;
this.exceptionBuilderSupplier = builder.exceptionBuilderSupplier;
this.httpStatusCode = builder.httpStatusCode;
}
/**
* Returns the error code for the modeled exception.
*/
public String errorCode() {
return errorCode;
}
/**
* Returns the Supplier to get the builder class for the exception.
*/
public Supplier<SdkPojo> exceptionBuilderSupplier() {
return exceptionBuilderSupplier;
}
/**
* Returns the http status code for the exception.
* For modeled exceptions, this value is populated from the c2j model.
*/
public Integer httpStatusCode() {
return httpStatusCode;
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link ExceptionMetadata}
*/
public static final class Builder {
private String errorCode;
private Supplier<SdkPojo> exceptionBuilderSupplier;
private Integer httpStatusCode;
private Builder() {
}
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
public Builder exceptionBuilderSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) {
this.exceptionBuilderSupplier = exceptionBuilderSupplier;
return this;
}
public Builder httpStatusCode(Integer httpStatusCode) {
this.httpStatusCode = httpStatusCode;
return this;
}
public ExceptionMetadata build() {
return new ExceptionMetadata(this);
}
}
}
| 2,438 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/protocol-core/src/main/java/software/amazon/awssdk/protocols/core/AbstractMarshallingRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.core;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
/**
* Base class for marshaller/unmarshaller registry implementations.
*/
@SdkProtectedApi
public abstract class AbstractMarshallingRegistry {
private final Map<MarshallLocation, Map<MarshallingType, Object>> registry;
private final Set<MarshallingType<?>> marshallingTypes;
private final Map<Class<?>, MarshallingType<?>> marshallingTypeCache;
protected AbstractMarshallingRegistry(Builder builder) {
this.registry = builder.registry;
this.marshallingTypes = builder.marshallingTypes;
this.marshallingTypeCache = new HashMap<>(marshallingTypes.size());
}
/**
* Get a registered marshaller/unmarshaller by location and type.
*
* @param marshallLocation Location of registered (un)marshaller.
* @param marshallingType Type of registered (un)marshaller.
* @return Registered marshaller/unmarshaller.
* @throws SdkClientException if no marshaller/unmarshaller is registered for the given location and type.
*/
protected Object get(MarshallLocation marshallLocation, MarshallingType<?> marshallingType) {
Map<MarshallingType, Object> byLocation = registry.get(marshallLocation);
if (byLocation == null) {
throw SdkClientException.create("No marshaller/unmarshaller registered for location " + marshallLocation.name());
}
Object registered = byLocation.get(marshallingType);
if (registered == null) {
throw SdkClientException.create(String.format("No marshaller/unmarshaller of type %s registered for location %s.",
marshallingType,
marshallLocation.name()));
}
return registered;
}
@SuppressWarnings("unchecked")
protected <T> MarshallingType<T> toMarshallingType(T val) {
if (val == null) {
return (MarshallingType<T>) MarshallingType.NULL;
} else if (val instanceof SdkPojo) {
// We don't want to cache every single POJO type so we make a special case of it here.
return (MarshallingType<T>) MarshallingType.SDK_POJO;
} else if (!marshallingTypeCache.containsKey(val.getClass())) {
return (MarshallingType<T>) populateMarshallingTypeCache(val.getClass());
}
return (MarshallingType<T>) marshallingTypeCache.get(val.getClass());
}
private MarshallingType<?> populateMarshallingTypeCache(Class<?> clzz) {
synchronized (marshallingTypeCache) {
if (!marshallingTypeCache.containsKey(clzz)) {
for (MarshallingType<?> marshallingType : marshallingTypes) {
if (marshallingType.getTargetClass().isAssignableFrom(clzz)) {
marshallingTypeCache.put(clzz, marshallingType);
return marshallingType;
}
}
throw SdkClientException.builder().message("MarshallingType not found for class " + clzz).build();
}
}
return marshallingTypeCache.get(clzz);
}
/**
* Builder for a {@link AbstractMarshallingRegistry}.
*/
public abstract static class Builder {
private final Map<MarshallLocation, Map<MarshallingType, Object>> registry = new EnumMap<>(MarshallLocation.class);
private final Set<MarshallingType<?>> marshallingTypes = new HashSet<>();
protected Builder() {
}
protected <T> Builder register(MarshallLocation marshallLocation,
MarshallingType<T> marshallingType,
Object marshaller) {
marshallingTypes.add(marshallingType);
if (!registry.containsKey(marshallLocation)) {
registry.put(marshallLocation, new HashMap<>());
}
registry.get(marshallLocation).put(marshallingType, marshaller);
return this;
}
}
}
| 2,439 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/JsonErrorCodeParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonErrorCodeParser;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.utils.StringInputStream;
public class JsonErrorCodeParserTest {
/**
* Value of error type present in headers for tests below
*/
private static final String HEADER_ERROR_TYPE = "headerErrorType";
/**
* Value of error type present in JSON content for tests below
*/
private static final String JSON_ERROR_TYPE = "jsonErrorType";
private static final String ERROR_FIELD_NAME = "testErrorCode";
private final JsonErrorCodeParser parser = new JsonErrorCodeParser(ERROR_FIELD_NAME);
private static JsonContent toJsonContent(String errorType) throws IOException {
JsonNode node = JsonNode.parser().parse(new StringInputStream(
String.format("{\"%s\": \"%s\"}", ERROR_FIELD_NAME, errorType)));
return new JsonContent(null, node);
}
private static SdkHttpFullResponse httpResponseWithoutHeaders() {
return ValidSdkObjects.sdkHttpFullResponse().build();
}
private static SdkHttpFullResponse httpResponseWithHeaders(String header, String value) {
return ValidSdkObjects.sdkHttpFullResponse().putHeader(header, value).build();
}
@Test
public void parseErrorType_ErrorTypeInHeadersTakesPrecedence_NoSuffix() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders(JsonErrorCodeParser.X_AMZN_ERROR_TYPE, HEADER_ERROR_TYPE),
toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInHeadersTakesPrecedence_SuffixIgnored() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders(JsonErrorCodeParser.X_AMZN_ERROR_TYPE,
String.format("%s:%s", HEADER_ERROR_TYPE, "someSuffix")), toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInHeaders_HonorCaseInsensitivity() throws IOException {
String actualErrorType = parser.parseErrorCode(
httpResponseWithHeaders("x-amzn-errortype",
String.format("%s:%s", HEADER_ERROR_TYPE, "someSuffix")), toJsonContent(JSON_ERROR_TYPE));
assertEquals(HEADER_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInContent_NoPrefix() throws IOException {
String actualErrorType = parser.parseErrorCode(httpResponseWithoutHeaders(), toJsonContent(JSON_ERROR_TYPE));
assertEquals(JSON_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_ErrorTypeInContent_PrefixIgnored() throws IOException {
String actualErrorType = parser.parseErrorCode(httpResponseWithoutHeaders(),
toJsonContent(String.format("%s#%s", "somePrefix", JSON_ERROR_TYPE)));
assertEquals(JSON_ERROR_TYPE, actualErrorType);
}
@Test
public void parseErrorType_NotPresentInHeadersAndNullContent_ReturnsNull() {
assertNull(parser.parseErrorCode(httpResponseWithoutHeaders(), null));
}
@Test
public void parseErrorType_NotPresentInHeadersAndEmptyContent_ReturnsNull() {
assertNull(parser.parseErrorCode(httpResponseWithoutHeaders(),
new JsonContent(null, JsonNode.emptyObjectNode())));
}
}
| 2,440 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/SdkJsonGeneratorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.BinaryUtils;
public class SdkJsonGeneratorTest {
/**
* Delta for comparing double values
*/
private static final double DELTA = .0001;
private StructuredJsonGenerator jsonGenerator;
@BeforeEach
public void setup() {
jsonGenerator = new SdkJsonGenerator(JsonFactory.builder().build(), "application/json");
}
@Test
public void simpleObject_AllPrimitiveTypes() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("stringProp").writeValue("stringVal");
jsonGenerator.writeFieldName("integralProp").writeValue(42);
jsonGenerator.writeFieldName("booleanProp").writeValue(true);
jsonGenerator.writeFieldName("doubleProp").writeValue(123.456);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertTrue(node.isObject());
assertEquals("stringVal", node.asObject().get("stringProp").text());
assertEquals("42", node.asObject().get("integralProp").asNumber());
assertEquals(true, node.asObject().get("booleanProp").asBoolean());
assertEquals(123.456, Double.parseDouble(node.asObject().get("doubleProp").asNumber()), DELTA);
}
@Test
public void simpleObject_WithLongProperty_PreservesLongValue() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("longProp").writeValue(Long.MAX_VALUE);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(Long.toString(Long.MAX_VALUE), node.asObject().get("longProp").asNumber());
}
@Test
public void simpleObject_WithBinaryData_WritesAsBase64() throws IOException {
byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("binaryProp").writeValue(ByteBuffer.wrap(data));
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(BinaryUtils.toBase64(data), node.asObject().get("binaryProp").text());
}
@Test
public void simpleObject_WithServiceDate() throws IOException {
Instant instant = Instant.ofEpochMilli(123456);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("dateProp").writeValue(instant);
jsonGenerator.writeEndObject();
JsonNode node = toJsonNode();
assertEquals(123.456, Double.parseDouble(node.asObject().get("dateProp").asNumber()), DELTA);
}
@Test
public void stringArray() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeValue("valOne");
jsonGenerator.writeValue("valTwo");
jsonGenerator.writeValue("valThree");
jsonGenerator.writeEndArray();
JsonNode node = toJsonNode();
assertTrue(node.isArray());
assertEquals("valOne", node.asArray().get(0).text());
assertEquals("valTwo", node.asArray().get(1).text());
assertEquals("valThree", node.asArray().get(2).text());
}
@Test
public void complexArray() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("nestedProp").writeValue("nestedVal");
jsonGenerator.writeEndObject();
jsonGenerator.writeEndArray();
JsonNode node = toJsonNode();
assertEquals("nestedVal", node.asArray().get(0).asObject().get("nestedProp").text());
}
@Test
public void unclosedObject_AutoClosesOnClose() throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("stringProp").writeValue("stringVal");
JsonNode node = toJsonNode();
assertTrue(node.isObject());
}
@Test
public void unclosedArray_AutoClosesOnClose() throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeValue("valOne");
jsonGenerator.writeValue("valTwo");
jsonGenerator.writeValue("valThree");
JsonNode node = toJsonNode();
assertTrue(node.isArray());
assertEquals(3, node.asArray().size());
}
// See https://forums.aws.amazon.com/thread.jspa?threadID=158756
@Test
public void testNumericNoQuote() {
StructuredJsonGenerator jw = new SdkJsonGenerator(new JsonFactory(), null);
jw.writeStartObject();
jw.writeFieldName("foo").writeValue(Instant.now());
jw.writeEndObject();
String s = new String(jw.getBytes(), Charset.forName("UTF-8"));
// Something like: {"foo":1408378076.135}.
// Note prior to the changes, it was {"foo":1408414571}
// (with no decimal point nor places.)
System.out.println(s);
final String prefix = "{\"foo\":";
assertTrue(s.startsWith(prefix), s);
final int startPos = prefix.length();
// verify no starting quote for the value
assertFalse(s.startsWith("{\"foo\":\""), s);
assertTrue(s.endsWith("}"), s);
// Not: {"foo":"1408378076.135"}.
// verify no ending quote for the value
assertFalse(s.endsWith("\"}"), s);
final int endPos = s.indexOf("}");
final int dotPos = s.length() - 5;
assertTrue(s.charAt(dotPos) == '.', s);
// verify all numeric before '.'
char[] a = s.toCharArray();
for (int i = startPos; i < dotPos; i++) {
assertTrue(a[i] <= '9' && a[i] >= '0');
}
int j = 0;
// verify all numeric after '.'
for (int i = dotPos + 1; i < endPos; i++) {
assertTrue(a[i] <= '9' && a[i] >= '0');
j++;
}
// verify decimal precision of exactly 3
assertTrue(j == 3);
}
private JsonNode toJsonNode() throws IOException {
return JsonNode.parser().parse(new ByteArrayInputStream(jsonGenerator.getBytes()));
}
}
| 2,441 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/AwsJsonErrorMessageParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonErrorMessageParser;
import software.amazon.awssdk.protocols.json.internal.unmarshall.ErrorMessageParser;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.StringInputStream;
public class AwsJsonErrorMessageParserTest {
private static final String X_AMZN_ERROR_MESSAGE = "x-amzn-error-message";
private static final ErrorMessageParser parser = AwsJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER;
private static final String MESSAGE_CONTENT = "boom";
private SdkHttpFullResponse.Builder responseBuilder;
private JsonNodeParser jsonParser;
@BeforeEach
public void setup() {
jsonParser = JsonNode.parser();
responseBuilder = ValidSdkObjects.sdkHttpFullResponse();
}
@Test
public void testErrorMessageAt_message() {
JsonNode jsonNode = parseJson("message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
private JsonNode parseJson(String fieldName, String value) {
return jsonParser.parse(new StringInputStream(String.format("{\"%s\": \"%s\"}", fieldName, value)));
}
private JsonNode parseJson(String json) {
return jsonParser.parse(new StringInputStream(json));
}
@Test
public void testErrorMessageAt_Message() {
JsonNode jsonNode = parseJson("Message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void testErrorMessageAt_errorMessage() {
JsonNode jsonNode = parseJson("errorMessage", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void testNoErrorMessage_ReturnsNull() {
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertNull(parsed);
}
@Test
public void testErrorMessageIsNumber_ReturnsStringValue() {
JsonNode jsonNode = parseJson("{\"message\": 1}");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals("1", parsed);
}
@Test
public void testErrorMessageIsObject_ReturnsNull() {
JsonNode jsonNode = parseJson("{\"message\": {\"foo\": \"bar\"}}");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertNull(parsed);
}
@Test
public void testErrorMessageAtMultipleLocations_ReturnsLowerMessage() {
String randomStuff = UUID.randomUUID().toString();
String json = String.format("{"
+ " \"%s\": \"%s\","
+ " \"%s\": \"%s\","
+ " \"%s\": \"%s\""
+ "}", "message", MESSAGE_CONTENT,
"Message", randomStuff,
"errorMessage", randomStuff);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson(json));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_ReturnsHeaderValue() {
responseBuilder.putHeader(X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_ReturnsHeaderValue_CaseInsensitive() {
responseBuilder.putHeader("x-AMZN-error-message", MESSAGE_CONTENT);
String parsed = parser.parseErrorMessage(responseBuilder.build(), parseJson("{}"));
assertEquals(MESSAGE_CONTENT, parsed);
}
@Test
public void errorMessageInHeader_TakesPrecedenceOverMessageInBody() {
responseBuilder.putHeader(X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
JsonNode jsonNode = parseJson("message", "other message in body");
String parsed = parser.parseErrorMessage(responseBuilder.build(), jsonNode);
assertEquals(MESSAGE_CONTENT, parsed);
}
}
| 2,442 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/ValidSdkObjects.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.net.URI;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
/**
* A collection of objects (or object builder) pre-populated with all required fields. This allows tests to focus on what data
* they care about, not necessarily what data is required.
*/
public final class ValidSdkObjects {
private ValidSdkObjects() {}
public static SdkHttpFullRequest.Builder sdkHttpFullRequest() {
return SdkHttpFullRequest.builder()
.uri(URI.create("http://test.com:80"))
.method(SdkHttpMethod.GET);
}
public static SdkHttpFullResponse.Builder sdkHttpFullResponse() {
return SdkHttpFullResponse.builder()
.statusCode(200);
}
}
| 2,443 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/FaultStatusCodeMappingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonProtocolErrorUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
public class FaultStatusCodeMappingTest {
@ParameterizedTest
@MethodSource("unmarshal_faultValue_testCases")
public void unmarshal_faultValue_useCorrectly(TestCase tc) {
AwsJsonProtocolErrorUnmarshaller unmarshaller = makeUnmarshaller(
Arrays.asList(ExceptionMetadata.builder()
.errorCode("ServiceException")
.httpStatusCode(tc.metadataStatusCode)
.exceptionBuilderSupplier(AwsServiceException::builder)
.build()), false);
SdkHttpFullResponse.Builder responseBuilder =
SdkHttpFullResponse
.builder()
.content(errorContent("ServiceException"))
.putHeader("x-amzn-query-error", "actualErrorCode;Sender");
if (tc.httpStatusCode != null) {
responseBuilder.statusCode(tc.httpStatusCode);
}
AwsServiceException exception = unmarshaller.handle(responseBuilder.build(), new ExecutionAttributes());
assertThat(exception.statusCode()).isEqualTo(tc.expectedStatusCode);
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("ServiceException");
}
@ParameterizedTest
@MethodSource("x_amzn_query_error_testCases")
public void unmarshal_faultValue_useCorrectly_awsQueryCompatible(QueryErrorTestCase tc) {
AwsJsonProtocolErrorUnmarshaller unmarshaller = makeUnmarshaller(
Arrays.asList(ExceptionMetadata.builder()
.errorCode("ServiceException")
.exceptionBuilderSupplier(AwsServiceException::builder)
.build()), tc.hasAwsQueryCompatible);
SdkHttpFullResponse.Builder responseBuilder =
SdkHttpFullResponse
.builder()
.content(errorContent("ServiceException"))
.putHeader("x-amzn-query-error", tc.queryErrorHeader);
AwsServiceException exception = unmarshaller.handle(responseBuilder.build(), new ExecutionAttributes());
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo(tc.expectedErrorCode);
}
public static List<TestCase> unmarshal_faultValue_testCases() {
return Arrays.asList(
new TestCase(null, null, 500),
new TestCase(null, 1, 1),
new TestCase(2, null, 2),
new TestCase(2, 1, 2)
);
}
public static List<QueryErrorTestCase> x_amzn_query_error_testCases() {
return Arrays.asList(
new QueryErrorTestCase(true, "customErrorCode;Sender", "customErrorCode"),
new QueryErrorTestCase(true, "customError CodeSender", "ServiceException"),
new QueryErrorTestCase(true, "customError", "ServiceException"),
new QueryErrorTestCase(true, ";Sender", "ServiceException"),
new QueryErrorTestCase(true, null, "ServiceException"),
new QueryErrorTestCase(true, "", "ServiceException"),
new QueryErrorTestCase(false, "customErrorCode;Sender", "ServiceException")
);
}
private static AwsJsonProtocolErrorUnmarshaller makeUnmarshaller(List<ExceptionMetadata> exceptionMetadata,
boolean hasAwsQueryCompatible) {
return AwsJsonProtocolErrorUnmarshaller.builder()
.exceptions(exceptionMetadata)
.jsonProtocolUnmarshaller(JsonProtocolUnmarshaller.builder()
.defaultTimestampFormats(Collections.emptyMap())
.build())
.jsonFactory(new JsonFactory())
.errorMessageParser((resp, content) -> "Some server error")
.errorCodeParser((resp, content) ->
content.getJsonNode().asObject().get("errorCode").asString())
.hasAwsQueryCompatible(hasAwsQueryCompatible)
.build();
}
private static AbortableInputStream errorContent(String code) {
String json = String.format("{\"errorCode\":\"%s\"}", code);
return contentAsStream(json);
}
private static AbortableInputStream contentAsStream(String content) {
return AbortableInputStream.create(SdkBytes.fromUtf8String(content).asInputStream());
}
private static class TestCase {
private final Integer httpStatusCode;
private final Integer metadataStatusCode;
private final int expectedStatusCode;
public TestCase(Integer httpStatusCode, Integer metadataStatusCode, int expectedStatusCode) {
this.httpStatusCode = httpStatusCode;
this.metadataStatusCode = metadataStatusCode;
this.expectedStatusCode = expectedStatusCode;
}
}
private static class QueryErrorTestCase {
private final boolean hasAwsQueryCompatible;
private final String queryErrorHeader;
private final String expectedErrorCode;
public QueryErrorTestCase(boolean hasAwsQueryCompatible, String queryErrorHeader, String expectedErrorCode) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
this.queryErrorHeader = queryErrorHeader;
this.expectedErrorCode = expectedErrorCode;
}
}
}
| 2,444 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/test/java/software/amazon/awssdk/protocols/json/internal/dom/DocumentUnmarshallerTest.java | package software.amazon.awssdk.protocols.json.internal.dom;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkNumber;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.protocols.json.internal.unmarshall.document.DocumentUnmarshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode;
public class DocumentUnmarshallerTest {
@Test
public void testDocumentFromNumberNode() throws ParseException {
JsonNode node = JsonNode.parser().parse("100");
assertThat(Document.fromNumber(SdkNumber.fromInteger(100)).asNumber().intValue())
.isEqualTo(node.visit(new DocumentUnmarshaller()).asNumber().intValue());
}
@Test
public void testDocumentFromBoolean() {
JsonNode node = JsonNode.parser().parse("true");
assertThat(Document.fromBoolean(true)).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromString() {
JsonNode node = JsonNode.parser().parse("\"100.00\"");
assertThat(Document.fromString("100.00")).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromNull() {
JsonNode node = JsonNode.parser().parse("null");
assertThat(Document.fromNull()).isEqualTo(node.visit(new DocumentUnmarshaller()));
}
@Test
public void testExceptionIsThrownFromEmbededObjectType() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> new EmbeddedObjectJsonNode(new Object()).visit(new DocumentUnmarshaller()));
}
@Test
public void testDocumentFromObjectNode(){
JsonNode node = JsonNode.parser().parse("{\"firstKey\": \"firstValue\", \"secondKey\": \"secondValue\"}");
Document documentMap = node.visit(new DocumentUnmarshaller());
Map<String, Document> expectedMap = new LinkedHashMap<>();
expectedMap.put("firstKey", Document.fromString("firstValue"));
expectedMap.put("secondKey", Document.fromString("secondValue"));
final Document expectedDocumentMap = Document.fromMap(expectedMap);
assertThat(documentMap).isEqualTo(expectedDocumentMap);
}
@Test
public void testDocumentFromArrayNode(){
JsonNode node = JsonNode.parser().parse("[\"One\", 10, true, null]");
List<Document> documentList = new ArrayList<>();
documentList.add(Document.fromString("One"));
documentList.add(Document.fromNumber(SdkNumber.fromBigDecimal(BigDecimal.TEN)));
documentList.add(Document.fromBoolean(true));
documentList.add(Document.fromNull());
final Document document = Document.fromList(documentList);
final Document actualDocument = node.visit(new DocumentUnmarshaller());
assertThat(actualDocument).isEqualTo(document);
}
}
| 2,445 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/ErrorCodeParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
/**
* Error code parser to parse error code from the response returned by AWS services.
*/
@SdkProtectedApi
public interface ErrorCodeParser {
String parseErrorCode(SdkHttpFullResponse response, JsonContent jsonContent);
}
| 2,446 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/StructuredJsonGenerator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface for generating a JSON
*/
@SdkProtectedApi
public interface StructuredJsonGenerator {
/**
* No-op implementation that ignores all calls and returns empty bytes from getBytes.
*/
StructuredJsonGenerator NO_OP = new StructuredJsonGenerator() {
@Override
public StructuredJsonGenerator writeStartArray() {
return this;
}
@Override
public StructuredJsonGenerator writeEndArray() {
return this;
}
@Override
public StructuredJsonGenerator writeNull() {
return this;
}
@Override
public StructuredJsonGenerator writeStartObject() {
return this;
}
@Override
public StructuredJsonGenerator writeEndObject() {
return this;
}
@Override
public StructuredJsonGenerator writeFieldName(String fieldName) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(String val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(boolean bool) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(long val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(double val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(float val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(short val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(int val) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(ByteBuffer bytes) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigDecimal value) {
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigInteger value) {
return this;
}
@Override
public StructuredJsonGenerator writeNumber(String number) {
return this;
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public String getContentType() {
return null;
}
};
StructuredJsonGenerator writeStartArray();
StructuredJsonGenerator writeEndArray();
StructuredJsonGenerator writeNull();
StructuredJsonGenerator writeStartObject();
StructuredJsonGenerator writeEndObject();
StructuredJsonGenerator writeFieldName(String fieldName);
StructuredJsonGenerator writeValue(String val);
StructuredJsonGenerator writeValue(boolean bool);
StructuredJsonGenerator writeValue(long val);
StructuredJsonGenerator writeValue(double val);
StructuredJsonGenerator writeValue(float val);
StructuredJsonGenerator writeValue(short val);
StructuredJsonGenerator writeValue(int val);
StructuredJsonGenerator writeValue(ByteBuffer bytes);
StructuredJsonGenerator writeValue(Instant instant);
StructuredJsonGenerator writeNumber(String number);
StructuredJsonGenerator writeValue(BigDecimal value);
StructuredJsonGenerator writeValue(BigInteger value);
byte[] getBytes();
/**
* New clients use {@link SdkJsonProtocolFactory#getContentType()}.
*/
@Deprecated
String getContentType();
}
| 2,447 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonContentTypeResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Interface to compute the content type to send in requests for JSON based protocols.
*/
@SdkProtectedApi
public interface JsonContentTypeResolver {
/**
* Computes content type to send in requests.
*
* @param protocolMetadata Metadata about the protocol.
* @return Correct content type to send in request based on metadata about the client.
*/
String resolveContentType(AwsJsonProtocolMetadata protocolMetadata);
}
| 2,448 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocol.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Supported protocols for the new marshalling style. Currently only includes JSON based services.
*/
@SdkProtectedApi
public enum AwsJsonProtocol {
/**
* RPC protocol that sends all data in the payload as JSON and sends the X-Amz-Target header to indicate the
* operation to invoke.
*/
AWS_JSON,
/**
* Protocol that supports RESTful bindings. Members can be bound to the headers, query params, path, or payload. Supports
* binary and streaming data. Operation is identified by HTTP verb and resource path combination.
*/
REST_JSON,
}
| 2,449 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/StructuredJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Common interface for creating generators (writers) and protocol handlers for JSON like protocols.
*/
@SdkProtectedApi
public interface StructuredJsonFactory {
/**
* Returns the {@link StructuredJsonGenerator} to be used for marshalling the request.
*
* @param contentType Content type to send for requests.
*/
StructuredJsonGenerator createWriter(String contentType);
JsonFactory getJsonFactory();
ErrorCodeParser getErrorCodeParser(String customErrorCodeFieldName);
}
| 2,450 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/SdkJsonGenerator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.DateUtils;
/**
* Thin wrapper around Jackson's JSON generator.
*/
@SdkProtectedApi
public class SdkJsonGenerator implements StructuredJsonGenerator {
/**
* Default buffer size for the BAOS. Chosen somewhat arbitrarily. Should be large enough to
* prevent frequent resizings but small enough to avoid wasted allocations for small requests.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
private final JsonGenerator generator;
private final String contentType;
public SdkJsonGenerator(JsonFactory factory, String contentType) {
try {
/**
* A {@link JsonGenerator} created is by default enabled with
* UTF-8 encoding
*/
this.generator = factory.createGenerator(baos);
this.contentType = contentType;
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
@Override
public StructuredJsonGenerator writeStartArray() {
try {
generator.writeStartArray();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeEndArray() {
try {
generator.writeEndArray();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeNull() {
try {
generator.writeNull();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeStartObject() {
try {
generator.writeStartObject();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeEndObject() {
try {
generator.writeEndObject();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeFieldName(String fieldName) {
try {
generator.writeFieldName(fieldName);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(String val) {
try {
generator.writeString(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(boolean bool) {
try {
generator.writeBoolean(bool);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(long val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(double val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(float val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(short val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(int val) {
try {
generator.writeNumber(val);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(ByteBuffer bytes) {
try {
generator.writeBinary(BinaryUtils.copyBytesFrom(bytes));
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
//TODO: This date formatting is coupled to AWS's format. Should generalize it
public StructuredJsonGenerator writeValue(Instant instant) {
try {
generator.writeNumber(DateUtils.formatUnixTimestampInstant(instant));
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigDecimal value) {
try {
/**
* Note that this is not how the backend represents BigDecimal types. On the wire
* it's normally a JSON number but this causes problems with certain JSON implementations
* that parse JSON numbers as floating points automatically. (See API-433)
*/
generator.writeString(value.toString());
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeValue(BigInteger value) {
try {
generator.writeNumber(value);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
@Override
public StructuredJsonGenerator writeNumber(String number) {
try {
generator.writeNumber(number);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
/**
* Closes the generator and flushes to write. Must be called when finished writing JSON
* content.
*/
private void close() {
try {
generator.close();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
/**
* Get the JSON content as a UTF-8 encoded byte array. It is recommended to hold onto the array
* reference rather then making repeated calls to this method as a new array will be created
* each time.
*
* @return Array of UTF-8 encoded bytes that make up the generated JSON.
*/
@Override
public byte[] getBytes() {
close();
return baos.toByteArray();
}
@Override
public String getContentType() {
return contentType;
}
protected JsonGenerator getGenerator() {
return generator;
}
/**
* Indicates an issue writing JSON content.
*/
public static class JsonGenerationException extends SdkClientException {
public JsonGenerationException(Throwable t) {
super(SdkClientException.builder().cause(t));
}
}
}
| 2,451 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonOperationMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler;
/**
* Contains various information needed to create a {@link JsonResponseHandler}
* for the client.
*/
@SdkProtectedApi
public final class JsonOperationMetadata {
private final boolean hasStreamingSuccessResponse;
private final boolean isPayloadJson;
private JsonOperationMetadata(Builder builder) {
this.hasStreamingSuccessResponse = builder.hasStreamingSuccessResponse;
this.isPayloadJson = builder.isPayloadJson;
}
public boolean hasStreamingSuccessResponse() {
return hasStreamingSuccessResponse;
}
public boolean isPayloadJson() {
return isPayloadJson;
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link JsonOperationMetadata}.
*/
public static final class Builder {
private boolean hasStreamingSuccessResponse;
private boolean isPayloadJson;
private Builder() {
}
/**
* True is payload contains JSON content, false if it doesn't (i.e. it contains binary content or no content).
*
* @return This builder for method chaining.
*/
public Builder isPayloadJson(boolean payloadJson) {
isPayloadJson = payloadJson;
return this;
}
/**
* True if the success response (2xx response) contains a payload that should be treated as streaming. False otherwise.
*
* @return This builder for method chaining.
*/
public Builder hasStreamingSuccessResponse(boolean hasStreamingSuccessResponse) {
this.hasStreamingSuccessResponse = hasStreamingSuccessResponse;
return this;
}
public JsonOperationMetadata build() {
return new JsonOperationMetadata(this);
}
}
}
| 2,452 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/BaseAwsJsonProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.core.OperationInfo;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.json.internal.AwsStructuredPlainJsonFactory;
import software.amazon.awssdk.protocols.json.internal.marshall.JsonProtocolMarshallerBuilder;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonErrorMessageParser;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonProtocolErrorUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonResponseHandler;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
@SdkProtectedApi
public abstract class BaseAwsJsonProtocolFactory {
/**
* Content type resolver implementation for plain text AWS_JSON services.
*/
protected static final JsonContentTypeResolver AWS_JSON = new DefaultJsonContentTypeResolver("application/x-amz-json-");
private final AwsJsonProtocolMetadata protocolMetadata;
private final List<ExceptionMetadata> modeledExceptions;
private final Supplier<SdkPojo> defaultServiceExceptionSupplier;
private final String customErrorCodeFieldName;
private final boolean hasAwsQueryCompatible;
private final SdkClientConfiguration clientConfiguration;
private final JsonProtocolUnmarshaller protocolUnmarshaller;
protected BaseAwsJsonProtocolFactory(Builder<?> builder) {
this.protocolMetadata = builder.protocolMetadata.build();
this.modeledExceptions = unmodifiableList(builder.modeledExceptions);
this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier;
this.customErrorCodeFieldName = builder.customErrorCodeFieldName;
this.hasAwsQueryCompatible = builder.hasAwsQueryCompatible;
this.clientConfiguration = builder.clientConfiguration;
this.protocolUnmarshaller = JsonProtocolUnmarshaller
.builder()
.parser(JsonNodeParser.builder()
.jsonFactory(getSdkFactory().getJsonFactory())
.build())
.defaultTimestampFormats(getDefaultTimestampFormats())
.build();
}
/**
* Creates a new response handler with the given {@link JsonOperationMetadata} and a supplier of the POJO response
* type.
*
* @param operationMetadata Metadata about operation being unmarshalled.
* @param pojoSupplier {@link Supplier} of the POJO response type.
* @param <T> Type being unmarshalled.
* @return HttpResponseHandler that will handle the HTTP response and unmarshall into a POJO.
*/
public final <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(JsonOperationMetadata operationMetadata,
Supplier<SdkPojo> pojoSupplier) {
return createResponseHandler(operationMetadata, r -> pojoSupplier.get());
}
/**
* Creates a new response handler with the given {@link JsonOperationMetadata} and a supplier of the POJO response
* type.
*
* @param operationMetadata Metadata about operation being unmarshalled.
* @param pojoSupplier {@link Supplier} of the POJO response type. Has access to the HTTP response, primarily for polymorphic
* deserialization as seen in event stream (i.e. unmarshalled event depends on ':event-type' header).
* @param <T> Type being unmarshalled.
* @return HttpResponseHandler that will handle the HTTP response and unmarshall into a POJO.
*/
public final <T extends SdkPojo> HttpResponseHandler<T> createResponseHandler(
JsonOperationMetadata operationMetadata,
Function<SdkHttpFullResponse, SdkPojo> pojoSupplier) {
return timeUnmarshalling(
new AwsJsonResponseHandler<>(
new JsonResponseHandler<>(protocolUnmarshaller,
pojoSupplier,
operationMetadata.hasStreamingSuccessResponse(),
operationMetadata.isPayloadJson())));
}
/**
* Creates a response handler for handling a error response (non 2xx response).
*/
public final HttpResponseHandler<AwsServiceException> createErrorResponseHandler(
JsonOperationMetadata errorResponseMetadata) {
return timeUnmarshalling(AwsJsonProtocolErrorUnmarshaller
.builder()
.jsonProtocolUnmarshaller(protocolUnmarshaller)
.exceptions(modeledExceptions)
.errorCodeParser(getSdkFactory().getErrorCodeParser(customErrorCodeFieldName))
.hasAwsQueryCompatible(hasAwsQueryCompatible)
.errorMessageParser(AwsJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER)
.jsonFactory(getSdkFactory().getJsonFactory())
.defaultExceptionSupplier(defaultServiceExceptionSupplier)
.build());
}
private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) {
return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate);
}
private StructuredJsonGenerator createGenerator(OperationInfo operationInfo) {
if (operationInfo.hasPayloadMembers() || protocolMetadata.protocol() == AwsJsonProtocol.AWS_JSON) {
return createGenerator();
} else {
return StructuredJsonGenerator.NO_OP;
}
}
@SdkTestInternalApi
private StructuredJsonGenerator createGenerator() {
return getSdkFactory().createWriter(getContentType());
}
@SdkTestInternalApi
public final String getContentType() {
return protocolMetadata.contentType() != null ? protocolMetadata.contentType()
: getContentTypeResolver().resolveContentType(protocolMetadata);
}
/**
* @return Content type resolver implementation to use.
*/
protected JsonContentTypeResolver getContentTypeResolver() {
return AWS_JSON;
}
/**
* @return Instance of {@link StructuredJsonFactory} to use in creating handlers.
*/
protected StructuredJsonFactory getSdkFactory() {
return AwsStructuredPlainJsonFactory.SDK_JSON_FACTORY;
}
/**
* @return The default timestamp format for unmarshalling for each location in the response. This
* can be overridden by subclasses to customize behavior.
*/
protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() {
Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class);
formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822);
formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP);
return Collections.unmodifiableMap(formats);
}
public final ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller(OperationInfo operationInfo) {
return JsonProtocolMarshallerBuilder.create()
.endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT))
.jsonGenerator(createGenerator(operationInfo))
.contentType(getContentType())
.operationInfo(operationInfo)
.sendExplicitNullForPayload(false)
.protocolMetadata(protocolMetadata)
.build();
}
/**
* Builder for {@link AwsJsonProtocolFactory}.
*/
public abstract static class Builder<SubclassT extends Builder> {
private final AwsJsonProtocolMetadata.Builder protocolMetadata = AwsJsonProtocolMetadata.builder();
private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>();
private Supplier<SdkPojo> defaultServiceExceptionSupplier;
private String customErrorCodeFieldName;
private SdkClientConfiguration clientConfiguration;
private boolean hasAwsQueryCompatible;
protected Builder() {
}
/**
* Registers a new modeled exception by the error code.
*
* @param errorMetadata Metadata to unmarshall the modeled exception.
* @return This builder for method chaining.
*/
public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) {
modeledExceptions.add(errorMetadata);
return getSubclass();
}
/**
* A supplier for the services base exception builder. This is used when we can't identify any modeled
* exception to unmarshall into.
*
* @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder.
* @return This builder for method chaining.
*/
public final SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) {
this.defaultServiceExceptionSupplier = exceptionBuilderSupplier;
return getSubclass();
}
/**
* @param protocol Protocol of the client (i.e. REST or RPC).
* @return This builder for method chaining.
*/
public final SubclassT protocol(AwsJsonProtocol protocol) {
protocolMetadata.protocol(protocol);
return getSubclass();
}
/**
* Protocol version of the client (right now supports JSON 1.0 and JSON 1.1). Used to determine content type.
*
* @param protocolVersion JSON protocol version.
* @return This builder for method chaining.
*/
public final SubclassT protocolVersion(String protocolVersion) {
protocolMetadata.protocolVersion(protocolVersion);
return getSubclass();
}
/**
* ContentType of the client (By default it is used from {@link #AWS_JSON} ).
* Used to determine content type.
*
* @param contentType JSON protocol contentType.
* @return This builder for method chaining.
*/
public final SubclassT contentType(String contentType) {
protocolMetadata.contentType(contentType);
return getSubclass();
}
/**
* Custom field name containing the error code that identifies the exception. Currently only used by Glacier
* which uses the "code" field instead of the traditional "__type".
*
* @param customErrorCodeFieldName Custom field name to look for error code.
* @return This builder for method chaining.
*/
public final SubclassT customErrorCodeFieldName(String customErrorCodeFieldName) {
this.customErrorCodeFieldName = customErrorCodeFieldName;
return getSubclass();
}
/**
* Sets the {@link SdkClientConfiguration} which contains the service endpoint.
*
* @param clientConfiguration Configuration of the client.
* @return This builder for method chaining.
*/
public final SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
return getSubclass();
}
/**
* Provides a check on whether AwsQueryCompatible trait is found in Metadata.
* If true, custom error codes can be provided
*
* @param hasAwsQueryCompatible boolean of whether the AwsQueryCompatible trait is found
* @return This builder for method chaining.
*/
public final SubclassT hasAwsQueryCompatible(boolean hasAwsQueryCompatible) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
return getSubclass();
}
@SuppressWarnings("unchecked")
private SubclassT getSubclass() {
return (SubclassT) this;
}
}
}
| 2,453 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Factory to generate the various JSON protocol handlers and generators to be used for
* communicating with the service.
*/
@ThreadSafe
@SdkProtectedApi
public final class AwsJsonProtocolFactory extends BaseAwsJsonProtocolFactory {
protected AwsJsonProtocolFactory(Builder builder) {
super(builder);
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsJsonProtocolFactory}.
*/
public static final class Builder extends BaseAwsJsonProtocolFactory.Builder<Builder> {
private Builder() {
}
public AwsJsonProtocolFactory build() {
return new AwsJsonProtocolFactory(this);
}
}
}
| 2,454 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/AwsJsonProtocolMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Provides additional metadata about AWS Json protocol.
*/
@SdkProtectedApi
public final class AwsJsonProtocolMetadata {
private final AwsJsonProtocol protocol;
private final String protocolVersion;
private final String contentType;
private AwsJsonProtocolMetadata(Builder builder) {
this.protocol = builder.protocol;
this.protocolVersion = builder.protocolVersion;
this.contentType = builder.contentType;
}
/**
* @return the protocol
*/
public AwsJsonProtocol protocol() {
return protocol;
}
/**
* @return the protocol version
*/
public String protocolVersion() {
return protocolVersion;
}
public static Builder builder() {
return new AwsJsonProtocolMetadata.Builder();
}
/**
*
* @return the content Type.
*/
public String contentType() {
return contentType;
}
public static final class Builder {
private AwsJsonProtocol protocol;
private String protocolVersion;
private String contentType;
private Builder() {
}
public Builder protocol(AwsJsonProtocol protocol) {
this.protocol = protocol;
return this;
}
public Builder protocolVersion(String protocolVersion) {
this.protocolVersion = protocolVersion;
return this;
}
public Builder contentType(String contentType) {
this.contentType = contentType;
return this;
}
public AwsJsonProtocolMetadata build() {
return new AwsJsonProtocolMetadata(this);
}
}
}
| 2,455 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/DefaultJsonContentTypeResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Prefers an explicit content type if provided. Otherwise computes the correct content type based
* on the wire format used and the version of the protocol.
*/
@SdkProtectedApi
public class DefaultJsonContentTypeResolver implements JsonContentTypeResolver {
private static final String REST_JSON_CONTENT_TYPE = "application/json";
private final String prefix;
public DefaultJsonContentTypeResolver(String prefix) {
this.prefix = prefix;
}
@Override
public String resolveContentType(AwsJsonProtocolMetadata protocolMetadata) {
if (AwsJsonProtocol.REST_JSON.equals(protocolMetadata.protocol())) {
return REST_JSON_CONTENT_TYPE;
}
return prefix + protocolMetadata.protocolVersion();
}
}
| 2,456 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/JsonContent.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.IoUtils;
/**
* Simple struct like class to hold both the raw json string content and it's parsed JsonNode
*/
@SdkProtectedApi
//TODO Do we need this? It isn't well encapsulated because of storing non-copied arrays.
public class JsonContent {
private static final Logger LOG = LoggerFactory.getLogger(JsonContent.class);
private final byte[] rawContent;
private final JsonNode jsonNode;
JsonContent(byte[] rawJsonContent, JsonNode jsonNode) {
this.rawContent = rawJsonContent;
this.jsonNode = jsonNode;
}
private JsonContent(byte[] rawJsonContent, JsonFactory jsonFactory) {
this.rawContent = rawJsonContent;
this.jsonNode = parseJsonContent(rawJsonContent, jsonFactory);
}
/**
* Static factory method to create a JsonContent object from the contents of the HttpResponse
* provided
*/
public static JsonContent createJsonContent(SdkHttpFullResponse httpResponse,
JsonFactory jsonFactory) {
byte[] rawJsonContent = httpResponse.content().map(c -> {
try {
return IoUtils.toByteArray(c);
} catch (IOException e) {
LOG.debug("Unable to read HTTP response content", e);
}
return null;
}).orElse(null);
return new JsonContent(rawJsonContent, jsonFactory);
}
private static JsonNode parseJsonContent(byte[] rawJsonContent, JsonFactory jsonFactory) {
if (rawJsonContent == null || rawJsonContent.length == 0) {
return JsonNode.emptyObjectNode();
}
try {
JsonNodeParser parser = JsonNodeParser.builder().jsonFactory(jsonFactory).build();
return parser.parse(rawJsonContent);
} catch (Exception e) {
LOG.debug("Unable to parse HTTP response content", e);
return JsonNode.emptyObjectNode();
}
}
public byte[] getRawContent() {
return rawContent;
}
public JsonNode getJsonNode() {
return jsonNode;
}
}
| 2,457 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/BaseAwsStructuredJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.json.internal.unmarshall.JsonErrorCodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Generic implementation of a structured JSON factory that is pluggable for different variants of
* JSON.
*/
@SdkProtectedApi
public abstract class BaseAwsStructuredJsonFactory implements StructuredJsonFactory {
private final JsonFactory jsonFactory;
protected BaseAwsStructuredJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
}
@Override
public StructuredJsonGenerator createWriter(String contentType) {
return createWriter(jsonFactory, contentType);
}
protected abstract StructuredJsonGenerator createWriter(JsonFactory jsonFactory,
String contentType);
@Override
public ErrorCodeParser getErrorCodeParser(String customErrorCodeFieldName) {
return new JsonErrorCodeParser(customErrorCodeFieldName);
}
}
| 2,458 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/MarshallerUtil.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
@SdkInternalApi
public final class MarshallerUtil {
private MarshallerUtil() {
}
/**
* @return true if the location is in the URI, false otherwise.
*/
public static boolean isInUri(MarshallLocation location) {
switch (location) {
case PATH:
case QUERY_PARAM:
return true;
default:
return false;
}
}
}
| 2,459 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/AwsStructuredPlainJsonFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.BaseAwsStructuredJsonFactory;
import software.amazon.awssdk.protocols.json.SdkJsonGenerator;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Creates generators and protocol handlers for plain text JSON wire format.
*/
@SdkInternalApi
public final class AwsStructuredPlainJsonFactory {
/**
* Recommended to share JsonFactory instances per http://wiki.fasterxml
* .com/JacksonBestPracticesPerformance
*/
private static final JsonFactory JSON_FACTORY = new JsonFactory();
public static final BaseAwsStructuredJsonFactory SDK_JSON_FACTORY = new BaseAwsStructuredJsonFactory(JSON_FACTORY) {
@Override
protected StructuredJsonGenerator createWriter(JsonFactory jsonFactory,
String contentType) {
return new SdkJsonGenerator(jsonFactory, contentType);
}
@Override
public JsonFactory getJsonFactory() {
return JsonNodeParser.DEFAULT_JSON_FACTORY;
}
};
protected AwsStructuredPlainJsonFactory() {
}
}
| 2,460 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonErrorCodeParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.ErrorCodeParser;
import software.amazon.awssdk.protocols.json.JsonContent;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public class JsonErrorCodeParser implements ErrorCodeParser {
/**
* Services using AWS JSON 1.1 protocol with HTTP binding send the error code information in the
* response headers, instead of the content. Package private for tests.
*/
public static final String X_AMZN_ERROR_TYPE = "x-amzn-ErrorType";
static final String ERROR_CODE_HEADER = ":error-code";
static final String EXCEPTION_TYPE_HEADER = ":exception-type";
private static final Logger log = LoggerFactory.getLogger(JsonErrorCodeParser.class);
/**
* List of header keys that represent the error code sent by service.
* Response should only contain one of these headers
*/
private final List<String> errorCodeHeaders;
private final String errorCodeFieldName;
public JsonErrorCodeParser(String errorCodeFieldName) {
this.errorCodeFieldName = errorCodeFieldName == null ? "__type" : errorCodeFieldName;
this.errorCodeHeaders = Arrays.asList(X_AMZN_ERROR_TYPE, ERROR_CODE_HEADER, EXCEPTION_TYPE_HEADER);
}
/**
* Parse the error code from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorCode(SdkHttpFullResponse response, JsonContent jsonContent) {
String errorCodeFromHeader = parseErrorCodeFromHeader(response);
if (errorCodeFromHeader != null) {
return errorCodeFromHeader;
} else if (jsonContent != null) {
return parseErrorCodeFromContents(jsonContent.getJsonNode());
} else {
return null;
}
}
/**
* Attempt to parse the error code from the response headers. Returns null if information is not
* present in the header.
*/
private String parseErrorCodeFromHeader(SdkHttpFullResponse response) {
for (String errorCodeHeader : errorCodeHeaders) {
Optional<String> errorCode = response.firstMatchingHeader(errorCodeHeader);
if (errorCode.isPresent()) {
if (X_AMZN_ERROR_TYPE.equals(errorCodeHeader)) {
return parseErrorCodeFromXAmzErrorType(errorCode.get());
}
return errorCode.get();
}
}
return null;
}
private String parseErrorCodeFromXAmzErrorType(String headerValue) {
if (headerValue != null) {
int separator = headerValue.indexOf(':');
if (separator != -1) {
headerValue = headerValue.substring(0, separator);
}
}
return headerValue;
}
/**
* Attempt to parse the error code from the response content. Returns null if information is not
* present in the content. Codes are expected to be in the form <b>"typeName"</b> or
* <b>"prefix#typeName"</b> Examples : "AccessDeniedException",
* "software.amazon.awssdk.dynamodb.v20111205#ProvisionedThroughputExceededException"
*/
private String parseErrorCodeFromContents(JsonNode jsonContents) {
if (jsonContents == null) {
return null;
}
JsonNode errorCodeField = jsonContents.field(errorCodeFieldName).orElse(null);
if (errorCodeField == null) {
return null;
}
String code = errorCodeField.text();
int separator = code.lastIndexOf('#');
return code.substring(separator + 1);
}
}
| 2,461 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsResponse;
import software.amazon.awssdk.awscore.AwsResponseMetadata;
import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
@SdkInternalApi
public final class AwsJsonResponseHandler<T> implements HttpResponseHandler<T> {
private final HttpResponseHandler<T> responseHandler;
public AwsJsonResponseHandler(HttpResponseHandler<T> responseHandler) {
this.responseHandler = responseHandler;
}
@Override
@SuppressWarnings("unchecked")
public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
T result = responseHandler.handle(response, executionAttributes);
// As T is not bounded to AwsResponse, we need to do explicitly cast here.
if (result instanceof AwsResponse) {
AwsResponseMetadata responseMetadata = generateResponseMetadata(response);
return (T) ((AwsResponse) result).toBuilder().responseMetadata(responseMetadata).build();
}
return result;
}
/**
* Create the default {@link AwsResponseMetadata}.
*/
private AwsResponseMetadata generateResponseMetadata(SdkHttpResponse response) {
Map<String, String> metadata = new HashMap<>();
metadata.put(AWS_REQUEST_ID, response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null));
response.forEachHeader((key, value) -> metadata.put(key, value.get(0)));
return DefaultAwsResponseMetadata.create(metadata);
}
}
| 2,462 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/SdkJsonErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public class SdkJsonErrorMessageParser implements ErrorMessageParser {
private static final List<String> DEFAULT_ERROR_MESSAGE_LOCATIONS = Arrays
.asList("message", "Message", "errorMessage");
/**
* Standard JSON Error Message Parser that checks for JSON fields in this order: 'message',
* 'Message', 'errorMessage'
*/
public static final SdkJsonErrorMessageParser DEFAULT_ERROR_MESSAGE_PARSER = new SdkJsonErrorMessageParser(
DEFAULT_ERROR_MESSAGE_LOCATIONS);
private final List<String> errorMessageJsonLocations;
/**
* @param errorMessageJsonLocations JSON field locations where the parser will attempt to
* extract the error message from.
*/
private SdkJsonErrorMessageParser(List<String> errorMessageJsonLocations) {
this.errorMessageJsonLocations = new LinkedList<>(errorMessageJsonLocations);
}
/**
* Parse the error message from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode) {
for (String field : errorMessageJsonLocations) {
String value = jsonNode.field(field).map(JsonNode::text).orElse(null);
if (value != null) {
return value;
}
}
return null;
}
}
| 2,463 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshallerRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry;
/**
* Registry of {@link JsonUnmarshaller} implementations by location and type.
*/
@SdkInternalApi
final class JsonUnmarshallerRegistry extends AbstractMarshallingRegistry {
private JsonUnmarshallerRegistry(Builder builder) {
super(builder);
}
@SuppressWarnings("unchecked")
public <T> JsonUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) {
return (JsonUnmarshaller<Object>) get(marshallLocation, marshallingType);
}
/**
* @return Builder instance to construct a {@link JsonUnmarshallerRegistry}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonUnmarshallerRegistry}.
*/
public static final class Builder extends AbstractMarshallingRegistry.Builder {
private Builder() {
}
public <T> Builder payloadUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.PAYLOAD, marshallingType, marshaller);
return this;
}
public <T> Builder headerUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.HEADER, marshallingType, marshaller);
return this;
}
public <T> Builder statusCodeUnmarshaller(MarshallingType<T> marshallingType,
JsonUnmarshaller<T> marshaller) {
register(MarshallLocation.STATUS_CODE, marshallingType, marshaller);
return this;
}
/**
* @return An immutable {@link JsonUnmarshallerRegistry} object.
*/
public JsonUnmarshallerRegistry build() {
return new JsonUnmarshallerRegistry(this);
}
}
}
| 2,464 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
/**
* Interface for unmarshalling a field from a JSON based service.
*
* @param <T> Type to unmarshall into.
*/
@SdkInternalApi
public interface JsonUnmarshaller<T> {
/**
* @param context Context containing dependencies and unmarshaller registry.
* @param jsonContent Parsed JSON content of body. May be null for REST JSON based services that don't have payload members.
* @param field {@link SdkField} of member being unmarshalled.
* @return Unmarshalled value.
*/
T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field);
}
| 2,465 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.SdkStandardLogger;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.IoUtils;
/**
* Default implementation of HttpResponseHandler that handles a successful response from a
* service and unmarshalls the result using a JSON unmarshaller.
*
* @param <T> Indicates the type being unmarshalled by this response handler.
*/
@SdkInternalApi
public final class JsonResponseHandler<T extends SdkPojo> implements HttpResponseHandler<T> {
private final Function<SdkHttpFullResponse, SdkPojo> pojoSupplier;
private final boolean needsConnectionLeftOpen;
private final boolean isPayloadJson;
/**
* The JSON unmarshaller to use when handling the response
*/
private JsonProtocolUnmarshaller unmarshaller;
/**
* Constructs a new response handler that will use the specified JSON unmarshaller to unmarshall
* the service response and uses the specified response element path to find the root of the
* business data in the service's response.
*
* @param unmarshaller The JSON unmarshaller to use on the response.
*/
public JsonResponseHandler(JsonProtocolUnmarshaller unmarshaller,
Function<SdkHttpFullResponse, SdkPojo> pojoSupplier,
boolean needsConnectionLeftOpen,
boolean isPayloadJson) {
this.unmarshaller = paramNotNull(unmarshaller, "unmarshaller");
this.pojoSupplier = pojoSupplier;
this.needsConnectionLeftOpen = needsConnectionLeftOpen;
this.isPayloadJson = isPayloadJson;
}
/**
* @see HttpResponseHandler#handle(SdkHttpFullResponse, ExecutionAttributes)
*/
@Override
public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Parsing service response JSON.");
try {
T result = unmarshaller.unmarshall(pojoSupplier.apply(response), response);
// Make sure we read all the data to get an accurate CRC32 calculation.
// See https://github.com/aws/aws-sdk-java/issues/1018
if (shouldParsePayloadAsJson() && response.content().isPresent()) {
IoUtils.drainInputStream(response.content().get());
}
SdkStandardLogger.REQUEST_LOGGER.trace(() -> "Done parsing service response.");
return result;
} finally {
if (!needsConnectionLeftOpen) {
response.content().ifPresent(i -> FunctionalUtils.invokeSafely(i::close));
}
}
}
@Override
public boolean needsConnectionLeftOpen() {
return needsConnectionLeftOpen;
}
/**
* @return True if the payload will be parsed as JSON, false otherwise.
*/
private boolean shouldParsePayloadAsJson() {
return !needsConnectionLeftOpen && isPayloadJson;
}
}
| 2,466 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/HeaderUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.traits.JsonValueTrait;
import software.amazon.awssdk.protocols.core.StringToValueConverter;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Header unmarshallers for all the simple types we support.
*/
@SdkInternalApi
final class HeaderUnmarshaller {
public static final JsonUnmarshaller<String> STRING =
new SimpleHeaderUnmarshaller<>(HeaderUnmarshaller::unmarshallStringHeader);
public static final JsonUnmarshaller<Integer> INTEGER = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_INTEGER);
public static final JsonUnmarshaller<Long> LONG = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_LONG);
public static final JsonUnmarshaller<Short> SHORT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_SHORT);
public static final JsonUnmarshaller<Double> DOUBLE = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_DOUBLE);
public static final JsonUnmarshaller<Boolean> BOOLEAN = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_BOOLEAN);
public static final JsonUnmarshaller<Float> FLOAT = new SimpleHeaderUnmarshaller<>(StringToValueConverter.TO_FLOAT);
// Only supports string value type
public static final JsonUnmarshaller<List<?>> LIST =
(context, jsonContent, field) -> context.response().matchingHeaders(field.locationName());
private HeaderUnmarshaller() {
}
/**
* Unmarshalls a string header, taking into account whether it's a Base 64 encoded JSON value.
* <p>
* <em>Note:</em> This code does no attempt to validate whether the unmarshalled string does, in fact, represent valid
* JSON values. The string value is returned as-is, and it's up to the user to validate the results.
*
* @param value Value to unmarshall
* @param field {@link SdkField} containing metadata about member being unmarshalled.
* @return Unmarshalled value.
*/
private static String unmarshallStringHeader(String value,
SdkField<String> field) {
return field.containsTrait(JsonValueTrait.class) ?
new String(BinaryUtils.fromBase64(value), StandardCharsets.UTF_8) : value;
}
public static JsonUnmarshaller<Instant> createInstantHeaderUnmarshaller(
StringToValueConverter.StringToValue<Instant> instantStringToValue) {
return new SimpleHeaderUnmarshaller<>(instantStringToValue);
}
/**
* Simple unmarshaller implementation that calls a {@link StringToValueConverter} with the header value if it's present.
*
* @param <T> Type to unmarshall into.
*/
private static class SimpleHeaderUnmarshaller<T> implements JsonUnmarshaller<T> {
private final StringToValueConverter.StringToValue<T> stringToValue;
private SimpleHeaderUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) {
this.stringToValue = stringToValue;
}
@Override
public T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field) {
return context.response().firstMatchingHeader(field.locationName())
.map(s -> stringToValue.convert(s, field))
.orElse(null);
}
}
}
| 2,467 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonProtocolUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import static software.amazon.awssdk.protocols.core.StringToValueConverter.TO_SDK_BYTES;
import java.io.IOException;
import java.time.Instant;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.core.traits.ListTrait;
import software.amazon.awssdk.core.traits.MapTrait;
import software.amazon.awssdk.core.traits.PayloadTrait;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.StringToInstant;
import software.amazon.awssdk.protocols.core.StringToValueConverter;
import software.amazon.awssdk.protocols.json.internal.MarshallerUtil;
import software.amazon.awssdk.protocols.json.internal.unmarshall.document.DocumentUnmarshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.builder.Buildable;
/**
* Unmarshaller implementation for both JSON RPC and REST JSON services. This class is thread-safe and it is
* recommended to reuse a single instance for best performance.
*/
@SdkInternalApi
@ThreadSafe
public final class JsonProtocolUnmarshaller {
public final StringToValueConverter.StringToValue<Instant> instantStringToValue;
private final JsonUnmarshallerRegistry registry;
private final JsonNodeParser parser;
private JsonProtocolUnmarshaller(Builder builder) {
this.parser = builder.parser;
this.instantStringToValue = StringToInstant.create(builder.defaultTimestampFormats.isEmpty() ?
new EnumMap<>(MarshallLocation.class) :
new EnumMap<>(builder.defaultTimestampFormats));
this.registry = createUnmarshallerRegistry(instantStringToValue);
}
private static JsonUnmarshallerRegistry createUnmarshallerRegistry(
StringToValueConverter.StringToValue<Instant> instantStringToValue) {
return JsonUnmarshallerRegistry
.builder()
.statusCodeUnmarshaller(MarshallingType.INTEGER, (context, json, f) -> context.response().statusCode())
.headerUnmarshaller(MarshallingType.STRING, HeaderUnmarshaller.STRING)
.headerUnmarshaller(MarshallingType.INTEGER, HeaderUnmarshaller.INTEGER)
.headerUnmarshaller(MarshallingType.LONG, HeaderUnmarshaller.LONG)
.headerUnmarshaller(MarshallingType.SHORT, HeaderUnmarshaller.SHORT)
.headerUnmarshaller(MarshallingType.DOUBLE, HeaderUnmarshaller.DOUBLE)
.headerUnmarshaller(MarshallingType.BOOLEAN, HeaderUnmarshaller.BOOLEAN)
.headerUnmarshaller(MarshallingType.INSTANT, HeaderUnmarshaller.createInstantHeaderUnmarshaller(instantStringToValue))
.headerUnmarshaller(MarshallingType.FLOAT, HeaderUnmarshaller.FLOAT)
.headerUnmarshaller(MarshallingType.LIST, HeaderUnmarshaller.LIST)
.payloadUnmarshaller(MarshallingType.STRING, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_STRING))
.payloadUnmarshaller(MarshallingType.INTEGER, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_INTEGER))
.payloadUnmarshaller(MarshallingType.LONG, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_LONG))
.payloadUnmarshaller(MarshallingType.SHORT, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_SHORT))
.payloadUnmarshaller(MarshallingType.FLOAT, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_FLOAT))
.payloadUnmarshaller(MarshallingType.DOUBLE, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_DOUBLE))
.payloadUnmarshaller(MarshallingType.BIG_DECIMAL, new SimpleTypeJsonUnmarshaller<>(
StringToValueConverter.TO_BIG_DECIMAL))
.payloadUnmarshaller(MarshallingType.BOOLEAN, new SimpleTypeJsonUnmarshaller<>(StringToValueConverter.TO_BOOLEAN))
.payloadUnmarshaller(MarshallingType.SDK_BYTES, JsonProtocolUnmarshaller::unmarshallSdkBytes)
.payloadUnmarshaller(MarshallingType.INSTANT, new SimpleTypeJsonUnmarshaller<>(instantStringToValue))
.payloadUnmarshaller(MarshallingType.SDK_POJO, JsonProtocolUnmarshaller::unmarshallStructured)
.payloadUnmarshaller(MarshallingType.LIST, JsonProtocolUnmarshaller::unmarshallList)
.payloadUnmarshaller(MarshallingType.MAP, JsonProtocolUnmarshaller::unmarshallMap)
.payloadUnmarshaller(MarshallingType.DOCUMENT, JsonProtocolUnmarshaller::unmarshallDocument)
.build();
}
private static SdkBytes unmarshallSdkBytes(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<SdkBytes> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
// Binary protocols like CBOR may already have the raw bytes extracted.
if (jsonContent.isEmbeddedObject()) {
return SdkBytes.fromByteArray((byte[]) jsonContent.asEmbeddedObject());
} else {
// Otherwise decode the JSON string as Base64
return TO_SDK_BYTES.convert(jsonContent.text(), field);
}
}
private static SdkPojo unmarshallStructured(JsonUnmarshallerContext context, JsonNode jsonContent, SdkField<SdkPojo> f) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
} else {
return unmarshallStructured(f.constructor().get(), jsonContent, context);
}
}
private static Document unmarshallDocument(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<Document> field) {
if (jsonContent == null) {
return null;
}
return jsonContent.isNull() ? Document.fromNull() : getDocumentFromJsonContent(jsonContent);
}
private static Document getDocumentFromJsonContent(JsonNode jsonContent) {
return jsonContent.visit(new DocumentUnmarshaller());
}
private static Map<String, ?> unmarshallMap(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<Map<String, ?>> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
SdkField<Object> valueInfo = field.getTrait(MapTrait.class).valueFieldInfo();
Map<String, Object> map = new HashMap<>();
jsonContent.asObject().forEach((fieldName, value) -> {
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(valueInfo.location(), valueInfo.marshallingType());
map.put(fieldName, unmarshaller.unmarshall(context, value, valueInfo));
});
return map;
}
private static List<?> unmarshallList(JsonUnmarshallerContext context, JsonNode jsonContent, SdkField<List<?>> field) {
if (jsonContent == null || jsonContent.isNull()) {
return null;
}
return jsonContent.asArray()
.stream()
.map(item -> {
SdkField<Object> memberInfo = field.getTrait(ListTrait.class).memberFieldInfo();
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(memberInfo.location(),
memberInfo.marshallingType());
return unmarshaller.unmarshall(context, item, memberInfo);
})
.collect(Collectors.toList());
}
private static class SimpleTypeJsonUnmarshaller<T> implements JsonUnmarshaller<T> {
private final StringToValueConverter.StringToValue<T> stringToValue;
private SimpleTypeJsonUnmarshaller(StringToValueConverter.StringToValue<T> stringToValue) {
this.stringToValue = stringToValue;
}
@Override
public T unmarshall(JsonUnmarshallerContext context,
JsonNode jsonContent,
SdkField<T> field) {
return jsonContent != null && !jsonContent.isNull() ? stringToValue.convert(jsonContent.text(), field) : null;
}
}
public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo,
SdkHttpFullResponse response) throws IOException {
JsonNode jsonNode = hasJsonPayload(sdkPojo, response) ? parser.parse(response.content().get()) : null;
return unmarshall(sdkPojo, response, jsonNode);
}
private boolean hasJsonPayload(SdkPojo sdkPojo, SdkHttpFullResponse response) {
return sdkPojo.sdkFields()
.stream()
.anyMatch(f -> isPayloadMemberOnUnmarshall(f) && !isExplicitBlobPayloadMember(f)
&& !isExplicitStringPayloadMember(f))
&& response.content().isPresent();
}
private boolean isExplicitBlobPayloadMember(SdkField<?> f) {
return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.SDK_BYTES;
}
private boolean isExplicitStringPayloadMember(SdkField<?> f) {
return isExplicitPayloadMember(f) && f.marshallingType() == MarshallingType.STRING;
}
private static boolean isExplicitPayloadMember(SdkField<?> f) {
return f.containsTrait(PayloadTrait.class);
}
private boolean isPayloadMemberOnUnmarshall(SdkField<?> f) {
return f.location() == MarshallLocation.PAYLOAD || MarshallerUtil.isInUri(f.location());
}
public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo,
SdkHttpFullResponse response,
JsonNode jsonContent) {
JsonUnmarshallerContext context = JsonUnmarshallerContext.builder()
.unmarshallerRegistry(registry)
.response(response)
.build();
return unmarshallStructured(sdkPojo, jsonContent, context);
}
@SuppressWarnings("unchecked")
private static <TypeT extends SdkPojo> TypeT unmarshallStructured(SdkPojo sdkPojo,
JsonNode jsonContent,
JsonUnmarshallerContext context) {
for (SdkField<?> field : sdkPojo.sdkFields()) {
if (isExplicitPayloadMember(field) && field.marshallingType() == MarshallingType.SDK_BYTES) {
Optional<AbortableInputStream> responseContent = context.response().content();
if (responseContent.isPresent()) {
field.set(sdkPojo, SdkBytes.fromInputStream(responseContent.get()));
} else {
field.set(sdkPojo, SdkBytes.fromByteArrayUnsafe(new byte[0]));
}
} else if (isExplicitPayloadMember(field) && field.marshallingType() == MarshallingType.STRING) {
Optional<AbortableInputStream> responseContent = context.response().content();
if (responseContent.isPresent()) {
field.set(sdkPojo, SdkBytes.fromInputStream(responseContent.get()).asUtf8String());
} else {
field.set(sdkPojo, "");
}
} else {
JsonNode jsonFieldContent = getJsonNode(jsonContent, field);
JsonUnmarshaller<Object> unmarshaller = context.getUnmarshaller(field.location(), field.marshallingType());
field.set(sdkPojo, unmarshaller.unmarshall(context, jsonFieldContent, (SdkField<Object>) field));
}
}
return (TypeT) ((Buildable) sdkPojo).build();
}
private static JsonNode getJsonNode(JsonNode jsonContent, SdkField<?> field) {
if (jsonContent == null) {
return null;
}
return isFieldExplicitlyTransferredAsJson(field) ? jsonContent : jsonContent.field(field.locationName()).orElse(null);
}
private static boolean isFieldExplicitlyTransferredAsJson(SdkField<?> field) {
return isExplicitPayloadMember(field) && !MarshallingType.DOCUMENT.equals(field.marshallingType());
}
/**
* @return New instance of {@link Builder}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link JsonProtocolUnmarshaller}.
*/
public static final class Builder {
private JsonNodeParser parser;
private Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats;
private Builder() {
}
/**
* @param parser JSON parser to use.
* @return This builder for method chaining.
*/
public Builder parser(JsonNodeParser parser) {
this.parser = parser;
return this;
}
/**
* @param formats The default timestamp formats for each location in the HTTP response.
* @return This builder for method chaining.
*/
public Builder defaultTimestampFormats(Map<MarshallLocation, TimestampFormatTrait.Format> formats) {
this.defaultTimestampFormats = formats;
return this;
}
/**
* @return New instance of {@link JsonProtocolUnmarshaller}.
*/
public JsonProtocolUnmarshaller build() {
return new JsonProtocolUnmarshaller(this);
}
}
}
| 2,468 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/ErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public interface ErrorMessageParser {
String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode);
}
| 2,469 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonErrorMessageParser.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public final class AwsJsonErrorMessageParser implements ErrorMessageParser {
public static final ErrorMessageParser DEFAULT_ERROR_MESSAGE_PARSER =
new AwsJsonErrorMessageParser(SdkJsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER);
/**
* x-amzn-error-message may be returned by RESTFUL services that do not send a response
* payload (like in a HEAD request).
*/
private static final String X_AMZN_ERROR_MESSAGE = "x-amzn-error-message";
/**
* Error message header returned by event stream errors
*/
private static final String EVENT_ERROR_MESSAGE = ":error-message";
private SdkJsonErrorMessageParser errorMessageParser;
/**
* @param errorMessageJsonLocations JSON field locations where the parser will attempt to
* extract the error message from.
*/
public AwsJsonErrorMessageParser(SdkJsonErrorMessageParser errorMessageJsonLocations) {
this.errorMessageParser = errorMessageJsonLocations;
}
/**
* Parse the error message from the response.
*
* @return Error Code of exceptional response or null if it can't be determined
*/
@Override
public String parseErrorMessage(SdkHttpFullResponse httpResponse, JsonNode jsonNode) {
String headerMessage = httpResponse.firstMatchingHeader(X_AMZN_ERROR_MESSAGE).orElse(null);
if (headerMessage != null) {
return headerMessage;
}
String eventHeaderMessage = httpResponse.firstMatchingHeader(EVENT_ERROR_MESSAGE).orElse(null);
if (eventHeaderMessage != null) {
return eventHeaderMessage;
}
return errorMessageParser.parseErrorMessage(httpResponse, jsonNode);
}
}
| 2,470 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/JsonUnmarshallerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.json.internal.MarshallerUtil;
/**
* Dependencies needed by implementations of {@link JsonUnmarshaller}.
*/
@SdkInternalApi
public final class JsonUnmarshallerContext {
private final SdkHttpFullResponse response;
private final JsonUnmarshallerRegistry unmarshallerRegistry;
private JsonUnmarshallerContext(Builder builder) {
this.response = builder.response;
this.unmarshallerRegistry = builder.unmarshallerRegistry;
}
/**
* @return The {@link SdkHttpFullResponse} of the API call.
*/
public SdkHttpFullResponse response() {
return response;
}
/**
* Lookup the marshaller for the given location andtype.
*
* @param location {@link MarshallLocation} of member.
* @param marshallingType {@link MarshallingType} of member.
* @return Unmarshaller implementation.
* @throws SdkClientException if no unmarshaller is found.
*/
public JsonUnmarshaller<Object> getUnmarshaller(MarshallLocation location, MarshallingType<?> marshallingType) {
// A member being in the URI on a response is nonsensical; when a member is declared to be somewhere in the URI,
// it should be found in the payload on response
if (MarshallerUtil.isInUri(location)) {
location = MarshallLocation.PAYLOAD;
}
return unmarshallerRegistry.getUnmarshaller(location, marshallingType);
}
/**
* @return Builder instance to construct a {@link JsonUnmarshallerContext}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonUnmarshallerContext}.
*/
public static final class Builder {
private SdkHttpFullResponse response;
private JsonUnmarshallerRegistry unmarshallerRegistry;
private Builder() {
}
public Builder response(SdkHttpFullResponse response) {
this.response = response;
return this;
}
public Builder unmarshallerRegistry(JsonUnmarshallerRegistry unmarshallerRegistry) {
this.unmarshallerRegistry = unmarshallerRegistry;
return this;
}
/**
* @return An immutable {@link JsonUnmarshallerContext} object.
*/
public JsonUnmarshallerContext build() {
return new JsonUnmarshallerContext(this);
}
}
}
| 2,471 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/AwsJsonProtocolErrorUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.ErrorCodeParser;
import software.amazon.awssdk.protocols.json.JsonContent;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.utils.StringUtils;
/**
* Unmarshaller for AWS specific error responses. All errors are unmarshalled into a subtype of
* {@link AwsServiceException} (more specifically a subtype generated for each AWS service).
*/
@SdkInternalApi
public final class AwsJsonProtocolErrorUnmarshaller implements HttpResponseHandler<AwsServiceException> {
private static final String QUERY_COMPATIBLE_ERRORCODE_DELIMITER = ";";
private static final String X_AMZN_QUERY_ERROR = "x-amzn-query-error";
private final JsonProtocolUnmarshaller jsonProtocolUnmarshaller;
private final List<ExceptionMetadata> exceptions;
private final ErrorMessageParser errorMessageParser;
private final JsonFactory jsonFactory;
private final Supplier<SdkPojo> defaultExceptionSupplier;
private final ErrorCodeParser errorCodeParser;
private final boolean hasAwsQueryCompatible;
private AwsJsonProtocolErrorUnmarshaller(Builder builder) {
this.jsonProtocolUnmarshaller = builder.jsonProtocolUnmarshaller;
this.errorCodeParser = builder.errorCodeParser;
this.errorMessageParser = builder.errorMessageParser;
this.jsonFactory = builder.jsonFactory;
this.defaultExceptionSupplier = builder.defaultExceptionSupplier;
this.exceptions = builder.exceptions;
this.hasAwsQueryCompatible = builder.hasAwsQueryCompatible;
}
@Override
public AwsServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) {
return unmarshall(response, executionAttributes);
}
private AwsServiceException unmarshall(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) {
JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory);
String errorCode = errorCodeParser.parseErrorCode(response, jsonContent);
Optional<ExceptionMetadata> modeledExceptionMetadata = exceptions.stream()
.filter(e -> e.errorCode().equals(errorCode))
.findAny();
SdkPojo sdkPojo = modeledExceptionMetadata.map(ExceptionMetadata::exceptionBuilderSupplier)
.orElse(defaultExceptionSupplier)
.get();
AwsServiceException.Builder exception = ((AwsServiceException) jsonProtocolUnmarshaller
.unmarshall(sdkPojo, response, jsonContent.getJsonNode())).toBuilder();
String errorMessage = errorMessageParser.parseErrorMessage(response, jsonContent.getJsonNode());
exception.awsErrorDetails(extractAwsErrorDetails(response, executionAttributes, jsonContent,
getEffectiveErrorCode(response, errorCode), errorMessage));
exception.clockSkew(getClockSkew(executionAttributes));
// Status code and request id are sdk level fields
exception.message(errorMessageForException(errorMessage, errorCode, response.statusCode()));
exception.statusCode(statusCode(response, modeledExceptionMetadata));
exception.requestId(response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(null));
exception.extendedRequestId(response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(null));
return exception.build();
}
private String getEffectiveErrorCode(SdkHttpFullResponse response, String errorCode) {
if (this.hasAwsQueryCompatible) {
String compatibleErrorCode = queryCompatibleErrorCodeFromResponse(response);
if (!StringUtils.isEmpty(compatibleErrorCode)) {
return compatibleErrorCode;
}
}
return errorCode;
}
private String queryCompatibleErrorCodeFromResponse(SdkHttpFullResponse response) {
Optional<String> headerValue = response.firstMatchingHeader(X_AMZN_QUERY_ERROR);
return headerValue.map(this::parseQueryErrorCodeFromDelimiter).orElse(null);
}
private String parseQueryErrorCodeFromDelimiter(String queryHeaderValue) {
int delimiter = queryHeaderValue.indexOf(QUERY_COMPATIBLE_ERRORCODE_DELIMITER);
if (delimiter > 0) {
return queryHeaderValue.substring(0, delimiter);
}
return null;
}
private String errorMessageForException(String errorMessage, String errorCode, int statusCode) {
if (StringUtils.isNotBlank(errorMessage)) {
return errorMessage;
}
if (StringUtils.isNotBlank(errorCode)) {
return "Service returned error code " + errorCode;
}
return "Service returned HTTP status code " + statusCode;
}
private Duration getClockSkew(ExecutionAttributes executionAttributes) {
Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET);
return timeOffset == null ? null : Duration.ofSeconds(timeOffset);
}
private int statusCode(SdkHttpFullResponse response, Optional<ExceptionMetadata> modeledExceptionMetadata) {
if (response.statusCode() != 0) {
return response.statusCode();
}
return modeledExceptionMetadata.filter(m -> m.httpStatusCode() != null)
.map(ExceptionMetadata::httpStatusCode)
.orElse(500);
}
/**
* Build the {@link AwsErrorDetails} from the metadata in the response.
*
* @param response HTTP response.
* @param executionAttributes Execution attributes.
* @param jsonContent Parsed JSON content.
* @param errorCode Parsed error code/type.
* @param errorMessage Parsed error message.
* @return AwsErrorDetails
*/
private AwsErrorDetails extractAwsErrorDetails(SdkHttpFullResponse response,
ExecutionAttributes executionAttributes,
JsonContent jsonContent,
String errorCode,
String errorMessage) {
AwsErrorDetails.Builder errorDetails =
AwsErrorDetails.builder()
.errorCode(errorCode)
.serviceName(executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME))
.sdkHttpResponse(response);
if (jsonContent.getRawContent() != null) {
errorDetails.rawResponse(SdkBytes.fromByteArray(jsonContent.getRawContent()));
}
errorDetails.errorMessage(errorMessage);
return errorDetails.build();
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsJsonProtocolErrorUnmarshaller}.
*/
public static final class Builder {
private JsonProtocolUnmarshaller jsonProtocolUnmarshaller;
private List<ExceptionMetadata> exceptions;
private ErrorMessageParser errorMessageParser;
private JsonFactory jsonFactory;
private Supplier<SdkPojo> defaultExceptionSupplier;
private ErrorCodeParser errorCodeParser;
private boolean hasAwsQueryCompatible;
private Builder() {
}
/**
* Underlying response unmarshaller. Exceptions for the JSON protocol are follow the same unmarshalling logic
* as success responses but with an additional "error type" that allows for polymorphic deserialization.
*
* @return This builder for method chaining.
*/
public Builder jsonProtocolUnmarshaller(JsonProtocolUnmarshaller jsonProtocolUnmarshaller) {
this.jsonProtocolUnmarshaller = jsonProtocolUnmarshaller;
return this;
}
/**
* List of {@link ExceptionMetadata} to represent the modeled exceptions for the service.
* For AWS services the error type is a string representing the type of the modeled exception.
*
* @return This builder for method chaining.
*/
public Builder exceptions(List<ExceptionMetadata> exceptions) {
this.exceptions = exceptions;
return this;
}
/**
* Implementation that can extract an error message from the JSON response. Implementations may look for a
* specific field in the JSON document or a specific header for example.
*
* @return This builder for method chaining.
*/
public Builder errorMessageParser(ErrorMessageParser errorMessageParser) {
this.errorMessageParser = errorMessageParser;
return this;
}
/**
* JSON Factory to create a JSON parser.
*
* @return This builder for method chaining.
*/
public Builder jsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}
/**
* Default exception type if "error code" does not match any known modeled exception. This is the generated
* base exception for the service (i.e. DynamoDbException).
*
* @return This builder for method chaining.
*/
public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) {
this.defaultExceptionSupplier = defaultExceptionSupplier;
return this;
}
/**
* Implementation of {@link ErrorCodeParser} that can extract an error code or type from the JSON response.
* Implementations may look for a specific field in the JSON document or a specific header for example.
*
* @return This builder for method chaining.
*/
public Builder errorCodeParser(ErrorCodeParser errorCodeParser) {
this.errorCodeParser = errorCodeParser;
return this;
}
public AwsJsonProtocolErrorUnmarshaller build() {
return new AwsJsonProtocolErrorUnmarshaller(this);
}
/**
* Provides a check on whether AwsQueryCompatible trait is found in Metadata.
* If true, error code will be derived from custom header. Otherwise, error code will be retrieved from its
* original source
*
* @param hasAwsQueryCompatible boolean of whether the AwsQueryCompatible trait is found
* @return This builder for method chaining.
*/
public Builder hasAwsQueryCompatible(boolean hasAwsQueryCompatible) {
this.hasAwsQueryCompatible = hasAwsQueryCompatible;
return this;
}
}
}
| 2,472 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/unmarshall/document/DocumentUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.unmarshall.document;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
@SdkInternalApi
public class DocumentUnmarshaller implements JsonNodeVisitor<Document> {
@Override
public Document visitNull() {
return Document.fromNull();
}
@Override
public Document visitBoolean(boolean bool) {
return Document.fromBoolean(bool);
}
@Override
public Document visitNumber(String number) {
return Document.fromNumber(number);
}
@Override
public Document visitString(String string) {
return Document.fromString(string);
}
@Override
public Document visitArray(List<JsonNode> array) {
return Document.fromList(array.stream()
.map(node -> node.visit(this))
.collect(Collectors.toList()));
}
@Override
public Document visitObject(Map<String, JsonNode> object) {
return Document.fromMap(object.entrySet()
.stream().collect(Collectors.toMap(entry -> entry.getKey(),
entry -> entry.getValue().visit(this),
(left, right) -> left,
LinkedHashMap::new)));
}
@Override
public Document visitEmbeddedObject(Object embeddedObject) {
throw new UnsupportedOperationException("Embedded objects are not supported within Document types.");
}
}
| 2,473 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshallerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
/**
* Dependencies needed by implementations of {@link JsonMarshaller}.
*/
@SdkInternalApi
public final class JsonMarshallerContext {
private final StructuredJsonGenerator jsonGenerator;
private final JsonProtocolMarshaller protocolHandler;
private final JsonMarshallerRegistry marshallerRegistry;
private final SdkHttpFullRequest.Builder request;
private JsonMarshallerContext(Builder builder) {
this.jsonGenerator = builder.jsonGenerator;
this.protocolHandler = builder.protocolHandler;
this.marshallerRegistry = builder.marshallerRegistry;
this.request = builder.request;
}
/**
* @return StructuredJsonGenerator used to produce the JSON document for a request.
*/
public StructuredJsonGenerator jsonGenerator() {
return jsonGenerator;
}
/**
* @return Implementation of {@link ProtocolMarshaller} that can be used to call back out to marshall structured data (i.e.
* dlists of objects).
*/
public JsonProtocolMarshaller protocolHandler() {
return protocolHandler;
}
/**
* @return Marshaller registry to obtain marshaller implementations for nested types (i.e. lists of objects or maps of string
* to string).
*/
public JsonMarshallerRegistry marshallerRegistry() {
return marshallerRegistry;
}
/**
* @return Mutable {@link SdkHttpFullRequest.Builder} object that can be used to add headers, query params,
* modify request URI, etc.
*/
public SdkHttpFullRequest.Builder request() {
return request;
}
/**
* Convenience method to marshall a nested object (may be simple or structured) at the given location.
*
* @param marshallLocation Current {@link MarshallLocation}
* @param val Value to marshall.
*/
public void marshall(MarshallLocation marshallLocation, Object val) {
marshallerRegistry().getMarshaller(marshallLocation, val).marshall(val, this, null, null);
}
/**
* Convenience method to marshall a nested object (may be simple or structured) at the given location.
*
* @param marshallLocation Current {@link MarshallLocation}
* @param val Value to marshall.
* @param paramName Name of parameter to marshall.
*/
public <T> void marshall(MarshallLocation marshallLocation, T val, String paramName) {
marshallerRegistry().getMarshaller(marshallLocation, val).marshall(val, this, paramName, null);
}
/**
* @return Builder instance to construct a {@link JsonMarshallerContext}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonMarshallerContext}.
*/
public static final class Builder {
private StructuredJsonGenerator jsonGenerator;
private JsonProtocolMarshaller protocolHandler;
private JsonMarshallerRegistry marshallerRegistry;
private SdkHttpFullRequest.Builder request;
private Builder() {
}
public Builder jsonGenerator(StructuredJsonGenerator jsonGenerator) {
this.jsonGenerator = jsonGenerator;
return this;
}
public Builder protocolHandler(JsonProtocolMarshaller protocolHandler) {
this.protocolHandler = protocolHandler;
return this;
}
public Builder marshallerRegistry(JsonMarshallerRegistry marshallerRegistry) {
this.marshallerRegistry = marshallerRegistry;
return this;
}
public Builder request(SdkHttpFullRequest.Builder request) {
this.request = request;
return this;
}
/**
* @return An immutable {@link JsonMarshallerContext} object.
*/
public JsonMarshallerContext build() {
return new JsonMarshallerContext(this);
}
}
}
| 2,474 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/SimpleTypePathMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.protocols.core.PathMarshaller;
import software.amazon.awssdk.protocols.core.ValueToStringConverter;
@SdkInternalApi
public final class SimpleTypePathMarshaller {
public static final JsonMarshaller<String> STRING =
new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.NON_GREEDY);
public static final JsonMarshaller<Integer> INTEGER =
new SimplePathMarshaller<>(ValueToStringConverter.FROM_INTEGER, PathMarshaller.NON_GREEDY);
public static final JsonMarshaller<Long> LONG =
new SimplePathMarshaller<>(ValueToStringConverter.FROM_LONG, PathMarshaller.NON_GREEDY);
public static final JsonMarshaller<Short> SHORT =
new SimplePathMarshaller<>(ValueToStringConverter.FROM_SHORT, PathMarshaller.NON_GREEDY);
/**
* Marshallers for Strings bound to a greedy path param. No URL encoding is done on the string
* so that it preserves the path structure.
*/
public static final JsonMarshaller<String> GREEDY_STRING =
new SimplePathMarshaller<>(ValueToStringConverter.FROM_STRING, PathMarshaller.GREEDY);
public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> {
throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName));
};
private SimpleTypePathMarshaller() {
}
private static class SimplePathMarshaller<T> implements JsonMarshaller<T> {
private final ValueToStringConverter.ValueToString<T> converter;
private final PathMarshaller pathMarshaller;
private SimplePathMarshaller(ValueToStringConverter.ValueToString<T> converter,
PathMarshaller pathMarshaller) {
this.converter = converter;
this.pathMarshaller = pathMarshaller;
}
@Override
public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) {
context.request().encodedPath(
pathMarshaller.marshall(context.request().encodedPath(), paramName, converter.convert(val, sdkField)));
}
}
}
| 2,475 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/HeaderMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import static software.amazon.awssdk.utils.CollectionUtils.isNullOrEmpty;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.JsonValueTrait;
import software.amazon.awssdk.core.traits.ListTrait;
import software.amazon.awssdk.core.traits.RequiredTrait;
import software.amazon.awssdk.protocols.core.ValueToStringConverter;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.StringUtils;
@SdkInternalApi
public final class HeaderMarshaller {
public static final JsonMarshaller<String> STRING = new SimpleHeaderMarshaller<>(
(val, field) -> field.containsTrait(JsonValueTrait.class) ?
BinaryUtils.toBase64(val.getBytes(StandardCharsets.UTF_8)) : val);
public static final JsonMarshaller<Integer> INTEGER = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_INTEGER);
public static final JsonMarshaller<Long> LONG = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_LONG);
public static final JsonMarshaller<Short> SHORT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_SHORT);
public static final JsonMarshaller<Double> DOUBLE = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_DOUBLE);
public static final JsonMarshaller<Float> FLOAT = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_FLOAT);
public static final JsonMarshaller<Boolean> BOOLEAN = new SimpleHeaderMarshaller<>(ValueToStringConverter.FROM_BOOLEAN);
public static final JsonMarshaller<Instant> INSTANT
= new SimpleHeaderMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING);
public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> {
// Null or empty lists cannot be meaningfully (or safely) represented in an HTTP header message since header-fields must
// typically have a non-empty field-value. https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
if (isNullOrEmpty(list)) {
return;
}
SdkField memberFieldInfo = sdkField.getRequiredTrait(ListTrait.class).memberFieldInfo();
for (Object listValue : list) {
if (shouldSkipElement(listValue)) {
continue;
}
JsonMarshaller marshaller = context.marshallerRegistry().getMarshaller(MarshallLocation.HEADER, listValue);
marshaller.marshall(listValue, context, paramName, memberFieldInfo);
}
};
public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> {
if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) {
throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName));
}
};
private HeaderMarshaller() {
}
private static boolean shouldSkipElement(Object element) {
return element instanceof String && StringUtils.isBlank((String) element);
}
private static class SimpleHeaderMarshaller<T> implements JsonMarshaller<T> {
private final ValueToStringConverter.ValueToString<T> converter;
private SimpleHeaderMarshaller(ValueToStringConverter.ValueToString<T> converter) {
this.converter = converter;
}
@Override
public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) {
context.request().appendHeader(paramName, converter.convert(val, sdkField));
}
}
}
| 2,476 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonProtocolMarshallerBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.core.OperationInfo;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolMetadata;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
/**
* Builder to create an appropriate implementation of {@link ProtocolMarshaller} for JSON based services.
*/
@SdkInternalApi
public final class JsonProtocolMarshallerBuilder {
private URI endpoint;
private StructuredJsonGenerator jsonGenerator;
private String contentType;
private OperationInfo operationInfo;
private boolean sendExplicitNullForPayload;
private AwsJsonProtocolMetadata protocolMetadata;
private JsonProtocolMarshallerBuilder() {
}
/**
* @return New instance of {@link JsonProtocolMarshallerBuilder}.
*/
public static JsonProtocolMarshallerBuilder create() {
return new JsonProtocolMarshallerBuilder();
}
/**
* @param endpoint Endpoint to set on the marshalled request.
* @return This builder for method chaining.
*/
public JsonProtocolMarshallerBuilder endpoint(URI endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Sets the implementation of {@link StructuredJsonGenerator} which allows writing JSON or JSON like (i.e. CBOR and Ion)
* data formats.
*
* @param jsonGenerator Generator to use.
* @return This builder for method chaining.
*/
public JsonProtocolMarshallerBuilder jsonGenerator(StructuredJsonGenerator jsonGenerator) {
this.jsonGenerator = jsonGenerator;
return this;
}
/**
* @param contentType The content type to set on the marshalled requests.
* @return This builder for method chaining.
*/
public JsonProtocolMarshallerBuilder contentType(String contentType) {
this.contentType = contentType;
return this;
}
/**
* @param operationInfo Metadata about the operation like URI, HTTP method, etc.
* @return This builder for method chaining.
*/
public JsonProtocolMarshallerBuilder operationInfo(OperationInfo operationInfo) {
this.operationInfo = operationInfo;
return this;
}
/**
* @param sendExplicitNullForPayload True if an explicit JSON null should be sent as the body when the
* payload member is null. See {@link NullAsEmptyBodyProtocolRequestMarshaller}.
*/
public JsonProtocolMarshallerBuilder sendExplicitNullForPayload(boolean sendExplicitNullForPayload) {
this.sendExplicitNullForPayload = sendExplicitNullForPayload;
return this;
}
/**
* @param protocolMetadata
*/
public JsonProtocolMarshallerBuilder protocolMetadata(AwsJsonProtocolMetadata protocolMetadata) {
this.protocolMetadata = protocolMetadata;
return this;
}
/**
* @return New instance of {@link ProtocolMarshaller}. If {@link #sendExplicitNullForPayload} is true then the marshaller
* will be wrapped with {@link NullAsEmptyBodyProtocolRequestMarshaller}.
*/
public ProtocolMarshaller<SdkHttpFullRequest> build() {
ProtocolMarshaller<SdkHttpFullRequest> protocolMarshaller = new JsonProtocolMarshaller(endpoint,
jsonGenerator,
contentType,
operationInfo,
protocolMetadata);
return sendExplicitNullForPayload ? protocolMarshaller
: new NullAsEmptyBodyProtocolRequestMarshaller(protocolMarshaller);
}
}
| 2,477 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.protocols.core.Marshaller;
/**
* Interface to marshall data according to the JSON protocol specification.
*
* @param <T> Type to marshall.
*/
@FunctionalInterface
@SdkInternalApi
public interface JsonMarshaller<T> extends Marshaller<T> {
JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> { };
/**
* Marshall the data into the request.
*
* @param val Data to marshall (may be null).
* @param context Dependencies needed for marshalling.
* @param paramName Optional param/field name. May be null in certain situations.
*/
void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField);
}
| 2,478 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/NullAsEmptyBodyProtocolRequestMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
/**
* AWS services expect an empty body when the payload member is null instead of an explicit JSON null.
*/
@SdkInternalApi
public class NullAsEmptyBodyProtocolRequestMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> {
private final ProtocolMarshaller<SdkHttpFullRequest> delegate;
public NullAsEmptyBodyProtocolRequestMarshaller(ProtocolMarshaller<SdkHttpFullRequest> delegate) {
this.delegate = delegate;
}
@Override
public SdkHttpFullRequest marshall(SdkPojo pojo) {
return delegate.marshall(pojo);
}
}
| 2,479 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/QueryParamMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.RequiredTrait;
import software.amazon.awssdk.protocols.core.ValueToStringConverter;
@SdkInternalApi
public final class QueryParamMarshaller {
public static final JsonMarshaller<String> STRING = new SimpleQueryParamMarshaller<>(
ValueToStringConverter.FROM_STRING);
public static final JsonMarshaller<Integer> INTEGER = new SimpleQueryParamMarshaller<>(
ValueToStringConverter.FROM_INTEGER);
public static final JsonMarshaller<Long> LONG = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_LONG);
public static final JsonMarshaller<Short> SHORT = new SimpleQueryParamMarshaller<>(ValueToStringConverter.FROM_SHORT);
public static final JsonMarshaller<Double> DOUBLE = new SimpleQueryParamMarshaller<>(
ValueToStringConverter.FROM_DOUBLE);
public static final JsonMarshaller<Float> FLOAT = new SimpleQueryParamMarshaller<>(
ValueToStringConverter.FROM_FLOAT);
public static final JsonMarshaller<Boolean> BOOLEAN = new SimpleQueryParamMarshaller<>(
ValueToStringConverter.FROM_BOOLEAN);
public static final JsonMarshaller<Instant> INSTANT
= new SimpleQueryParamMarshaller<>(JsonProtocolMarshaller.INSTANT_VALUE_TO_STRING);
public static final JsonMarshaller<List<?>> LIST = (list, context, paramName, sdkField) -> {
for (Object listVal : list) {
context.marshall(MarshallLocation.QUERY_PARAM, listVal, paramName);
}
};
public static final JsonMarshaller<Map<String, ?>> MAP = (val, context, paramName, sdkField) -> {
for (Map.Entry<String, ?> mapEntry : val.entrySet()) {
context.marshall(MarshallLocation.QUERY_PARAM, mapEntry.getValue(), mapEntry.getKey());
}
};
public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> {
if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) {
throw new IllegalArgumentException(String.format("Parameter '%s' must not be null", paramName));
}
};
private QueryParamMarshaller() {
}
private static class SimpleQueryParamMarshaller<T> implements JsonMarshaller<T> {
private final ValueToStringConverter.ValueToString<T> converter;
private SimpleQueryParamMarshaller(ValueToStringConverter.ValueToString<T> converter) {
this.converter = converter;
}
@Override
public void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) {
context.request().appendRawQueryParameter(paramName, converter.convert(val, sdkField));
}
}
}
| 2,480 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/DocumentTypeJsonMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkNumber;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.document.VoidDocumentVisitor;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
@SdkInternalApi
public class DocumentTypeJsonMarshaller implements VoidDocumentVisitor {
private final StructuredJsonGenerator jsonGenerator;
public DocumentTypeJsonMarshaller(StructuredJsonGenerator jsonGenerator) {
this.jsonGenerator = jsonGenerator;
}
@Override
public void visitNull() {
jsonGenerator.writeNull();
}
@Override
public void visitBoolean(Boolean document) {
jsonGenerator.writeValue(document);
}
@Override
public void visitString(String document) {
jsonGenerator.writeValue(document);
}
@Override
public void visitNumber(SdkNumber document) {
jsonGenerator.writeNumber(document.stringValue());
}
@Override
public void visitMap(Map<String, Document> documentMap) {
jsonGenerator.writeStartObject();
documentMap.entrySet().forEach(entry -> {
jsonGenerator.writeFieldName(entry.getKey());
entry.getValue().accept(this);
});
jsonGenerator.writeEndObject();
}
@Override
public void visitList(List<Document> documentList) {
jsonGenerator.writeStartArray();
documentList.stream().forEach(document -> document.accept(this));
jsonGenerator.writeEndArray();
}
}
| 2,481 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonMarshallerRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry;
/**
* Marshaller registry for JSON based protocols.
*/
@SdkInternalApi
public final class JsonMarshallerRegistry extends AbstractMarshallingRegistry {
private JsonMarshallerRegistry(Builder builder) {
super(builder);
}
@SuppressWarnings("unchecked")
public <T> JsonMarshaller<T> getMarshaller(MarshallLocation marshallLocation, T val) {
return (JsonMarshaller<T>) get(marshallLocation, toMarshallingType(val));
}
@SuppressWarnings("unchecked")
public <T> JsonMarshaller<Object> getMarshaller(MarshallLocation marshallLocation,
MarshallingType<T> marshallingType,
Object val) {
return (JsonMarshaller<Object>) get(marshallLocation,
val == null ? MarshallingType.NULL : marshallingType);
}
/**
* @return Builder instance to construct a {@link JsonMarshallerRegistry}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link JsonMarshallerRegistry}.
*/
public static final class Builder extends AbstractMarshallingRegistry.Builder {
private Builder() {
}
public <T> Builder payloadMarshaller(MarshallingType<T> marshallingType,
JsonMarshaller<T> marshaller) {
register(MarshallLocation.PAYLOAD, marshallingType, marshaller);
return this;
}
public <T> Builder headerMarshaller(MarshallingType<T> marshallingType,
JsonMarshaller<T> marshaller) {
register(MarshallLocation.HEADER, marshallingType, marshaller);
return this;
}
public <T> Builder queryParamMarshaller(MarshallingType<T> marshallingType,
JsonMarshaller<T> marshaller) {
register(MarshallLocation.QUERY_PARAM, marshallingType, marshaller);
return this;
}
public <T> Builder pathParamMarshaller(MarshallingType<T> marshallingType,
JsonMarshaller<T> marshaller) {
register(MarshallLocation.PATH, marshallingType, marshaller);
return this;
}
public <T> Builder greedyPathParamMarshaller(MarshallingType<T> marshallingType,
JsonMarshaller<T> marshaller) {
register(MarshallLocation.GREEDY_PATH, marshallingType, marshaller);
return this;
}
/**
* @return An immutable {@link JsonMarshallerRegistry} object.
*/
public JsonMarshallerRegistry build() {
return new JsonMarshallerRegistry(this);
}
}
}
| 2,482 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/JsonProtocolMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM;
import static software.amazon.awssdk.http.Header.CHUNKED;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.core.traits.PayloadTrait;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.core.InstantToString;
import software.amazon.awssdk.protocols.core.OperationInfo;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.core.ProtocolUtils;
import software.amazon.awssdk.protocols.core.ValueToStringConverter.ValueToString;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolMetadata;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
/**
* Implementation of {@link ProtocolMarshaller} for JSON based services. This includes JSON-RPC and REST-JSON.
*/
@SdkInternalApi
public class JsonProtocolMarshaller implements ProtocolMarshaller<SdkHttpFullRequest> {
public static final ValueToString<Instant> INSTANT_VALUE_TO_STRING =
InstantToString.create(getDefaultTimestampFormats());
private static final JsonMarshallerRegistry MARSHALLER_REGISTRY = createMarshallerRegistry();
private final URI endpoint;
private final StructuredJsonGenerator jsonGenerator;
private final SdkHttpFullRequest.Builder request;
private final String contentType;
private final AwsJsonProtocolMetadata protocolMetadata;
private final boolean hasExplicitPayloadMember;
private final boolean hasImplicitPayloadMembers;
private final boolean hasStreamingInput;
private final JsonMarshallerContext marshallerContext;
private final boolean hasEventStreamingInput;
private final boolean hasEvent;
JsonProtocolMarshaller(URI endpoint,
StructuredJsonGenerator jsonGenerator,
String contentType,
OperationInfo operationInfo,
AwsJsonProtocolMetadata protocolMetadata) {
this.endpoint = endpoint;
this.jsonGenerator = jsonGenerator;
this.contentType = contentType;
this.protocolMetadata = protocolMetadata;
this.hasExplicitPayloadMember = operationInfo.hasExplicitPayloadMember();
this.hasImplicitPayloadMembers = operationInfo.hasImplicitPayloadMembers();
this.hasStreamingInput = operationInfo.hasStreamingInput();
this.hasEventStreamingInput = operationInfo.hasEventStreamingInput();
this.hasEvent = operationInfo.hasEvent();
this.request = fillBasicRequestParams(operationInfo);
this.marshallerContext = JsonMarshallerContext.builder()
.jsonGenerator(jsonGenerator)
.marshallerRegistry(MARSHALLER_REGISTRY)
.protocolHandler(this)
.request(request)
.build();
}
private static JsonMarshallerRegistry createMarshallerRegistry() {
return JsonMarshallerRegistry
.builder()
.payloadMarshaller(MarshallingType.STRING, SimpleTypeJsonMarshaller.STRING)
.payloadMarshaller(MarshallingType.INTEGER, SimpleTypeJsonMarshaller.INTEGER)
.payloadMarshaller(MarshallingType.LONG, SimpleTypeJsonMarshaller.LONG)
.payloadMarshaller(MarshallingType.SHORT, SimpleTypeJsonMarshaller.SHORT)
.payloadMarshaller(MarshallingType.DOUBLE, SimpleTypeJsonMarshaller.DOUBLE)
.payloadMarshaller(MarshallingType.FLOAT, SimpleTypeJsonMarshaller.FLOAT)
.payloadMarshaller(MarshallingType.BIG_DECIMAL, SimpleTypeJsonMarshaller.BIG_DECIMAL)
.payloadMarshaller(MarshallingType.BOOLEAN, SimpleTypeJsonMarshaller.BOOLEAN)
.payloadMarshaller(MarshallingType.INSTANT, SimpleTypeJsonMarshaller.INSTANT)
.payloadMarshaller(MarshallingType.SDK_BYTES, SimpleTypeJsonMarshaller.SDK_BYTES)
.payloadMarshaller(MarshallingType.SDK_POJO, SimpleTypeJsonMarshaller.SDK_POJO)
.payloadMarshaller(MarshallingType.LIST, SimpleTypeJsonMarshaller.LIST)
.payloadMarshaller(MarshallingType.MAP, SimpleTypeJsonMarshaller.MAP)
.payloadMarshaller(MarshallingType.NULL, SimpleTypeJsonMarshaller.NULL)
.payloadMarshaller(MarshallingType.DOCUMENT, SimpleTypeJsonMarshaller.DOCUMENT)
.headerMarshaller(MarshallingType.STRING, HeaderMarshaller.STRING)
.headerMarshaller(MarshallingType.INTEGER, HeaderMarshaller.INTEGER)
.headerMarshaller(MarshallingType.LONG, HeaderMarshaller.LONG)
.headerMarshaller(MarshallingType.SHORT, HeaderMarshaller.SHORT)
.headerMarshaller(MarshallingType.DOUBLE, HeaderMarshaller.DOUBLE)
.headerMarshaller(MarshallingType.FLOAT, HeaderMarshaller.FLOAT)
.headerMarshaller(MarshallingType.BOOLEAN, HeaderMarshaller.BOOLEAN)
.headerMarshaller(MarshallingType.INSTANT, HeaderMarshaller.INSTANT)
.headerMarshaller(MarshallingType.LIST, HeaderMarshaller.LIST)
.headerMarshaller(MarshallingType.NULL, HeaderMarshaller.NULL)
.queryParamMarshaller(MarshallingType.STRING, QueryParamMarshaller.STRING)
.queryParamMarshaller(MarshallingType.INTEGER, QueryParamMarshaller.INTEGER)
.queryParamMarshaller(MarshallingType.LONG, QueryParamMarshaller.LONG)
.queryParamMarshaller(MarshallingType.SHORT, QueryParamMarshaller.SHORT)
.queryParamMarshaller(MarshallingType.DOUBLE, QueryParamMarshaller.DOUBLE)
.queryParamMarshaller(MarshallingType.FLOAT, QueryParamMarshaller.FLOAT)
.queryParamMarshaller(MarshallingType.BOOLEAN, QueryParamMarshaller.BOOLEAN)
.queryParamMarshaller(MarshallingType.INSTANT, QueryParamMarshaller.INSTANT)
.queryParamMarshaller(MarshallingType.LIST, QueryParamMarshaller.LIST)
.queryParamMarshaller(MarshallingType.MAP, QueryParamMarshaller.MAP)
.queryParamMarshaller(MarshallingType.NULL, QueryParamMarshaller.NULL)
.pathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.STRING)
.pathParamMarshaller(MarshallingType.INTEGER, SimpleTypePathMarshaller.INTEGER)
.pathParamMarshaller(MarshallingType.LONG, SimpleTypePathMarshaller.LONG)
.pathParamMarshaller(MarshallingType.SHORT, SimpleTypePathMarshaller.SHORT)
.pathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL)
.greedyPathParamMarshaller(MarshallingType.STRING, SimpleTypePathMarshaller.GREEDY_STRING)
.greedyPathParamMarshaller(MarshallingType.NULL, SimpleTypePathMarshaller.NULL)
.build();
}
private static Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() {
Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class);
// TODO the default is supposedly rfc822. See JAVA-2949
// We are using ISO_8601 in v1. Investigate which is the right format
formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822);
formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP);
formats.put(MarshallLocation.QUERY_PARAM, TimestampFormatTrait.Format.ISO_8601);
return Collections.unmodifiableMap(formats);
}
private SdkHttpFullRequest.Builder fillBasicRequestParams(OperationInfo operationInfo) {
return ProtocolUtils.createSdkHttpRequest(operationInfo, endpoint)
.applyMutation(b -> {
if (operationInfo.operationIdentifier() != null) {
b.putHeader("X-Amz-Target", operationInfo.operationIdentifier());
}
});
}
/**
* If there is not an explicit payload member then we need to start the implicit JSON request object. All
* members bound to the payload will be added as fields to this object.
*/
private void startMarshalling() {
// Create the implicit request object if needed.
if (needTopLevelJsonObject()) {
jsonGenerator.writeStartObject();
}
}
void doMarshall(SdkPojo pojo) {
for (SdkField<?> field : pojo.sdkFields()) {
Object val = field.getValueOrDefault(pojo);
if (isExplicitBinaryPayload(field)) {
if (val != null) {
request.contentStreamProvider(((SdkBytes) val)::asInputStream);
}
} else if (isExplicitStringPayload(field)) {
if (val != null) {
byte[] content = ((String) val).getBytes(StandardCharsets.UTF_8);
request.contentStreamProvider(() -> new ByteArrayInputStream(content));
}
} else if (isExplicitPayloadMember(field)) {
marshallExplicitJsonPayload(field, val);
} else {
marshallField(field, val);
}
}
}
private boolean isExplicitBinaryPayload(SdkField<?> field) {
return isExplicitPayloadMember(field) && MarshallingType.SDK_BYTES.equals(field.marshallingType());
}
private boolean isExplicitStringPayload(SdkField<?> field) {
return isExplicitPayloadMember(field) && MarshallingType.STRING.equals(field.marshallingType());
}
private boolean isExplicitPayloadMember(SdkField<?> field) {
return field.containsTrait(PayloadTrait.class);
}
private void marshallExplicitJsonPayload(SdkField<?> field, Object val) {
// Explicit JSON payloads are always marshalled as an object,
// even if they're null, in which case it's an empty object.
jsonGenerator.writeStartObject();
if (val != null) {
if (MarshallingType.DOCUMENT.equals(field.marshallingType())) {
marshallField(field, val);
} else {
doMarshall((SdkPojo) val);
}
}
jsonGenerator.writeEndObject();
}
@Override
public SdkHttpFullRequest marshall(SdkPojo pojo) {
startMarshalling();
doMarshall(pojo);
return finishMarshalling();
}
private SdkHttpFullRequest finishMarshalling() {
// Content may already be set if the payload is binary data.
if (request.contentStreamProvider() == null) {
// End the implicit request object if needed.
if (needTopLevelJsonObject()) {
jsonGenerator.writeEndObject();
}
byte[] content = jsonGenerator.getBytes();
if (content != null) {
request.contentStreamProvider(() -> new ByteArrayInputStream(content));
if (content.length > 0) {
request.putHeader(CONTENT_LENGTH, Integer.toString(content.length));
}
}
}
// We skip setting the default content type if the request is streaming as
// content-type is determined based on the body of the stream
// TODO: !request.headers().containsKey(CONTENT_TYPE) does not work because request is created from line 77
// and not from the original request
if (!request.firstMatchingHeader(CONTENT_TYPE).isPresent() && !hasEvent) {
if (hasEventStreamingInput) {
AwsJsonProtocol protocol = protocolMetadata.protocol();
if (protocol == AwsJsonProtocol.AWS_JSON) {
// For RPC formats, this content type will later be pushed down into the `initial-event` in the body
request.putHeader(CONTENT_TYPE, contentType);
} else if (protocol == AwsJsonProtocol.REST_JSON) {
request.putHeader(CONTENT_TYPE, MIMETYPE_EVENT_STREAM);
} else {
throw new IllegalArgumentException("Unknown AwsJsonProtocol: " + protocol);
}
request.removeHeader(CONTENT_LENGTH);
request.putHeader(TRANSFER_ENCODING, CHUNKED);
} else if (contentType != null && !hasStreamingInput && request.firstMatchingHeader(CONTENT_LENGTH).isPresent()) {
request.putHeader(CONTENT_TYPE, contentType);
}
}
return request.build();
}
private void marshallField(SdkField<?> field, Object val) {
MARSHALLER_REGISTRY.getMarshaller(field.location(), field.marshallingType(), val)
.marshall(val, marshallerContext, field.locationName(), (SdkField<Object>) field);
}
private boolean needTopLevelJsonObject() {
return AwsJsonProtocol.AWS_JSON.equals(protocolMetadata.protocol())
|| (!hasExplicitPayloadMember && hasImplicitPayloadMembers);
}
}
| 2,483 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-json-protocol/src/main/java/software/amazon/awssdk/protocols/json/internal/marshall/SimpleTypeJsonMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.json.internal.marshall;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.RequiredTrait;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.core.util.SdkAutoConstructList;
import software.amazon.awssdk.core.util.SdkAutoConstructMap;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.utils.DateUtils;
@SdkInternalApi
public final class SimpleTypeJsonMarshaller {
public static final JsonMarshaller<Void> NULL = (val, context, paramName, sdkField) -> {
if (Objects.nonNull(sdkField) && sdkField.containsTrait(RequiredTrait.class)) {
throw new IllegalArgumentException(String.format("Parameter '%s' must not be null",
Optional.ofNullable(paramName)
.orElseGet(() -> "paramName null")));
}
// If paramName is non null then we are emitting a field of an object, in that
// we just don't write the field. If param name is null then we are either in a container
// or the thing being marshalled is the payload itself in which case we want to preserve
// the JSON null.
if (paramName == null) {
context.jsonGenerator().writeNull();
}
};
public static final JsonMarshaller<String> STRING = new BaseJsonMarshaller<String>() {
@Override
public void marshall(String val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Integer> INTEGER = new BaseJsonMarshaller<Integer>() {
@Override
public void marshall(Integer val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Long> LONG = new BaseJsonMarshaller<Long>() {
@Override
public void marshall(Long val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Short> SHORT = new BaseJsonMarshaller<Short>() {
@Override
public void marshall(Short val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Float> FLOAT = new BaseJsonMarshaller<Float>() {
@Override
public void marshall(Float val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<BigDecimal> BIG_DECIMAL = new BaseJsonMarshaller<BigDecimal>() {
@Override
public void marshall(BigDecimal val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Double> DOUBLE = new BaseJsonMarshaller<Double>() {
@Override
public void marshall(Double val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Boolean> BOOLEAN = new BaseJsonMarshaller<Boolean>() {
@Override
public void marshall(Boolean val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<Instant> INSTANT = (val, context, paramName, sdkField) -> {
StructuredJsonGenerator jsonGenerator = context.jsonGenerator();
if (paramName != null) {
jsonGenerator.writeFieldName(paramName);
}
TimestampFormatTrait trait = sdkField != null ? sdkField.getTrait(TimestampFormatTrait.class) : null;
if (trait != null) {
switch (trait.format()) {
case UNIX_TIMESTAMP:
jsonGenerator.writeNumber(DateUtils.formatUnixTimestampInstant(val));
break;
case RFC_822:
jsonGenerator.writeValue(DateUtils.formatRfc822Date(val));
break;
case ISO_8601:
jsonGenerator.writeValue(DateUtils.formatIso8601Date(val));
break;
default:
throw SdkClientException.create("Unrecognized timestamp format - " + trait.format());
}
} else {
// Important to fallback to the jsonGenerator implementation as that may differ per wire format,
// irrespective of protocol. I.E. CBOR would default to unix timestamp as milliseconds while JSON
// will default to unix timestamp as seconds with millisecond decimal precision.
jsonGenerator.writeValue(val);
}
};
public static final JsonMarshaller<SdkBytes> SDK_BYTES = new BaseJsonMarshaller<SdkBytes>() {
@Override
public void marshall(SdkBytes val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeValue(val.asByteBuffer());
}
};
public static final JsonMarshaller<SdkPojo> SDK_POJO = new BaseJsonMarshaller<SdkPojo>() {
@Override
public void marshall(SdkPojo val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeStartObject();
context.protocolHandler().doMarshall(val);
jsonGenerator.writeEndObject();
}
};
public static final JsonMarshaller<List<?>> LIST = new BaseJsonMarshaller<List<?>>() {
@Override
public void marshall(List<?> list, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeStartArray();
for (Object listValue : list) {
context.marshall(MarshallLocation.PAYLOAD, listValue);
}
jsonGenerator.writeEndArray();
}
@Override
protected boolean shouldEmit(List list) {
return !list.isEmpty() || !(list instanceof SdkAutoConstructList);
}
};
/**
* Marshalls a Map as a JSON object where each key becomes a field.
*/
public static final JsonMarshaller<Map<String, ?>> MAP = new BaseJsonMarshaller<Map<String, ?>>() {
@Override
public void marshall(Map<String, ?> map, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
jsonGenerator.writeStartObject();
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (entry.getValue() != null) {
Object value = entry.getValue();
jsonGenerator.writeFieldName(entry.getKey());
context.marshall(MarshallLocation.PAYLOAD, value);
}
}
jsonGenerator.writeEndObject();
}
@Override
protected boolean shouldEmit(Map<String, ?> map) {
return !map.isEmpty() || !(map instanceof SdkAutoConstructMap);
}
};
/**
* Marshalls Document type members by visiting the document using DocumentTypeJsonMarshaller.
*/
public static final JsonMarshaller<Document> DOCUMENT = new BaseJsonMarshaller<Document>() {
@Override
public void marshall(Document document, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context) {
document.accept(new DocumentTypeJsonMarshaller(jsonGenerator));
}
};
private SimpleTypeJsonMarshaller() {
}
/**
* Base marshaller that emits the field name if present. The field name may be null in cases like
* marshalling something inside a list or if the object is the explicit payload member.
*
* @param <T> Type to marshall.
*/
private abstract static class BaseJsonMarshaller<T> implements JsonMarshaller<T> {
@Override
public final void marshall(T val, JsonMarshallerContext context, String paramName, SdkField<T> sdkField) {
if (!shouldEmit(val)) {
return;
}
if (paramName != null) {
context.jsonGenerator().writeFieldName(paramName);
}
marshall(val, context.jsonGenerator(), context);
}
public abstract void marshall(T val, StructuredJsonGenerator jsonGenerator, JsonMarshallerContext context);
protected boolean shouldEmit(T val) {
return true;
}
}
}
| 2,484 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/test/java/software/amazon/awssdk/protocols/cbor/AwsCborProtocolFactoryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.cbor;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.core.SdkSystemSetting.CBOR_ENABLED;
import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.RFC_822;
import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.UNIX_TIMESTAMP;
import static software.amazon.awssdk.core.traits.TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS;
import java.util.Map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
public class AwsCborProtocolFactoryTest {
private static AwsCborProtocolFactory factory;
@BeforeAll
public static void setup() {
factory = AwsCborProtocolFactory.builder().build();
}
@Test
public void defaultTimestampFormats_cborEnabled() {
Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats();
assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822);
assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP_MILLIS);
}
@Test
public void defaultTimestampFormats_cborDisabled() {
System.setProperty(CBOR_ENABLED.property(), "false");
try {
Map<MarshallLocation, TimestampFormatTrait.Format> defaultTimestampFormats = factory.getDefaultTimestampFormats();
assertThat(defaultTimestampFormats.get(MarshallLocation.HEADER)).isEqualTo(RFC_822);
assertThat(defaultTimestampFormats.get(MarshallLocation.PAYLOAD)).isEqualTo(UNIX_TIMESTAMP);
} finally {
System.clearProperty(CBOR_ENABLED.property());
}
}
}
| 2,485 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/AwsCborProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.cbor;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.traits.TimestampFormatTrait;
import software.amazon.awssdk.protocols.cbor.internal.AwsStructuredCborFactory;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.DefaultJsonContentTypeResolver;
import software.amazon.awssdk.protocols.json.JsonContentTypeResolver;
import software.amazon.awssdk.protocols.json.StructuredJsonFactory;
/**
* Protocol factory for AWS/CBOR protocols. Supports both JSON RPC and REST JSON versions of CBOR. Defaults to
* the CBOR wire format but can fallback to standard JSON if the {@link SdkSystemSetting#CBOR_ENABLED} is
* set to false.
*/
@SdkProtectedApi
public final class AwsCborProtocolFactory extends BaseAwsJsonProtocolFactory {
/**
* Content type resolver implementation for AWS_CBOR enabled services.
*/
private static final JsonContentTypeResolver AWS_CBOR = new DefaultJsonContentTypeResolver("application/x-amz-cbor-");
private AwsCborProtocolFactory(Builder builder) {
super(builder);
}
/**
* @return Content type resolver implementation to use.
*/
@Override
protected JsonContentTypeResolver getContentTypeResolver() {
if (isCborEnabled()) {
return AWS_CBOR;
} else {
return AwsJsonProtocolFactory.AWS_JSON;
}
}
/**
* @return Instance of {@link StructuredJsonFactory} to use in creating handlers.
*/
@Override
protected StructuredJsonFactory getSdkFactory() {
if (isCborEnabled()) {
return AwsStructuredCborFactory.SDK_CBOR_FACTORY;
} else {
return super.getSdkFactory();
}
}
/**
* CBOR uses epoch millis for timestamps rather than epoch seconds with millisecond decimal precision like JSON protocols.
*/
@Override
protected Map<MarshallLocation, TimestampFormatTrait.Format> getDefaultTimestampFormats() {
// If Cbor is disabled, getting the default timestamp format from parent class
if (!isCborEnabled()) {
return super.getDefaultTimestampFormats();
}
Map<MarshallLocation, TimestampFormatTrait.Format> formats = new EnumMap<>(MarshallLocation.class);
formats.put(MarshallLocation.HEADER, TimestampFormatTrait.Format.RFC_822);
formats.put(MarshallLocation.PAYLOAD, TimestampFormatTrait.Format.UNIX_TIMESTAMP_MILLIS);
return Collections.unmodifiableMap(formats);
}
private boolean isCborEnabled() {
return SdkSystemSetting.CBOR_ENABLED.getBooleanValueOrThrow();
}
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsJsonProtocolFactory}.
*/
public static final class Builder extends BaseAwsJsonProtocolFactory.Builder<Builder> {
private Builder() {
}
public AwsCborProtocolFactory build() {
return new AwsCborProtocolFactory(this);
}
}
}
| 2,486 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkCborGenerator.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.cbor.internal;
import java.io.IOException;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.SdkJsonGenerator;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.dataformat.cbor.CBORGenerator;
/**
* Thin wrapper around Jackson's JSON generator for CBOR.
*/
@SdkInternalApi
public final class SdkCborGenerator extends SdkJsonGenerator {
private static final int CBOR_TAG_TIMESTAMP = 1;
SdkCborGenerator(JsonFactory factory, String contentType) {
super(factory, contentType);
}
/**
* Jackson doesn't have native support for timestamp. As per the RFC 7049
* (https://tools.ietf.org/html/rfc7049#section-2.4.1) we will need to
* write a tag and write the epoch.
*/
@Override
public StructuredJsonGenerator writeValue(Instant instant) {
if (!(getGenerator() instanceof CBORGenerator)) {
throw new IllegalStateException("SdkCborGenerator is not created with a CBORGenerator.");
}
CBORGenerator generator = (CBORGenerator) getGenerator();
try {
generator.writeTag(CBOR_TAG_TIMESTAMP);
generator.writeNumber(instant.toEpochMilli());
} catch (IOException e) {
throw new JsonGenerationException(e);
}
return this;
}
}
| 2,487 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/SdkStructuredCborFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.cbor.internal;
import java.util.function.BiFunction;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.dataformat.cbor.CBORFactory;
/**
* Creates generators and protocol handlers for CBOR wire format.
*/
@SdkInternalApi
public abstract class SdkStructuredCborFactory {
protected static final JsonFactory CBOR_FACTORY = new CBORFactory();
protected static final CborGeneratorSupplier CBOR_GENERATOR_SUPPLIER = SdkCborGenerator::new;
SdkStructuredCborFactory() {
}
@FunctionalInterface
protected interface CborGeneratorSupplier extends BiFunction<JsonFactory, String, StructuredJsonGenerator> {
@Override
StructuredJsonGenerator apply(JsonFactory jsonFactory, String contentType);
}
}
| 2,488 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor | Create_ds/aws-sdk-java-v2/core/protocols/aws-cbor-protocol/src/main/java/software/amazon/awssdk/protocols/cbor/internal/AwsStructuredCborFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.cbor.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.json.BaseAwsStructuredJsonFactory;
import software.amazon.awssdk.protocols.json.StructuredJsonGenerator;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* Creates generators and protocol handlers for CBOR wire format.
*/
@SdkInternalApi
public final class AwsStructuredCborFactory extends SdkStructuredCborFactory {
public static final BaseAwsStructuredJsonFactory SDK_CBOR_FACTORY =
new BaseAwsStructuredJsonFactory(CBOR_FACTORY) {
@Override
protected StructuredJsonGenerator createWriter(JsonFactory jsonFactory,
String contentType) {
return CBOR_GENERATOR_SUPPLIER.apply(jsonFactory, contentType);
}
@Override
public JsonFactory getJsonFactory() {
return CBOR_FACTORY;
}
};
protected AwsStructuredCborFactory() {
}
}
| 2,489 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/test/java/software/amazon/awssdk/protocols/query/XmlDomParserTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import javax.xml.stream.XMLStreamException;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
import software.amazon.awssdk.utils.StringInputStream;
public class XmlDomParserTest {
@Test
public void simpleXmlDocument_ParsedCorrectly() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Struct>"
+ " <stringMember>stringVal</stringMember>"
+ " <integerMember>42</integerMember>"
+ "</Struct>";
XmlElement element = XmlDomParser.parse(new StringInputStream(xml));
assertThat(element.elementName()).isEqualTo("Struct");
assertThat(element.children()).hasSize(2);
assertThat(element.getElementsByName("stringMember"))
.hasSize(1);
assertThat(element.getElementsByName("stringMember").get(0).textContent())
.isEqualTo("stringVal");
assertThat(element.getElementsByName("integerMember"))
.hasSize(1);
assertThat(element.getElementsByName("integerMember").get(0).textContent())
.isEqualTo("42");
}
@Test
public void xmlWithAttributes_ParsedCorrectly() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Struct xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"foo\" xsi:nil=\"bar\">"
+ " <stringMember>stringVal</stringMember>"
+ "</Struct>";
XmlElement element = XmlDomParser.parse(new StringInputStream(xml));
assertThat(element.elementName()).isEqualTo("Struct");
assertThat(element.children()).hasSize(1);
assertThat(element.getElementsByName("stringMember"))
.hasSize(1);
assertThat(element.attributes()).hasSize(2);
assertThat(element.getOptionalAttributeByName("xsi:type").get()).isEqualTo("foo");
assertThat(element.getOptionalAttributeByName("xsi:nil").get()).isEqualTo("bar");
}
@Test
public void multipleElementsWithSameName_ParsedCorrectly() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Struct>"
+ " <member>valOne</member>"
+ " <member>valTwo</member>"
+ "</Struct>";
XmlElement element = XmlDomParser.parse(new StringInputStream(xml));
assertThat(element.getElementsByName("member"))
.hasSize(2);
assertThat(element.getElementsByName("member").get(0).textContent())
.isEqualTo("valOne");
assertThat(element.getElementsByName("member").get(1).textContent())
.isEqualTo("valTwo");
}
@Test
public void invalidXml_ThrowsException() {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Struct>"
+ " <member>valOne"
+ " <member>valTwo</member>"
+ "</Struct>";
assertThatThrownBy(() -> XmlDomParser.parse(new StringInputStream(xml)))
.isInstanceOf(SdkClientException.class)
.hasCauseInstanceOf(XMLStreamException.class);
}
}
| 2,490 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/AwsQueryProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.awscore.AwsResponse;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.http.MetricCollectingHttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.core.OperationInfo;
import software.amazon.awssdk.protocols.core.ProtocolMarshaller;
import software.amazon.awssdk.protocols.query.internal.marshall.QueryProtocolMarshaller;
import software.amazon.awssdk.protocols.query.internal.unmarshall.AwsQueryResponseHandler;
import software.amazon.awssdk.protocols.query.internal.unmarshall.QueryProtocolUnmarshaller;
import software.amazon.awssdk.protocols.query.unmarshall.AwsXmlErrorProtocolUnmarshaller;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
/**
* Protocol factory for the AWS/Query protocol.
*/
@SdkProtectedApi
public class AwsQueryProtocolFactory {
private final SdkClientConfiguration clientConfiguration;
private final List<ExceptionMetadata> modeledExceptions;
private final Supplier<SdkPojo> defaultServiceExceptionSupplier;
private final MetricCollectingHttpResponseHandler<AwsServiceException> errorUnmarshaller;
AwsQueryProtocolFactory(Builder<?> builder) {
this.clientConfiguration = builder.clientConfiguration;
this.modeledExceptions = unmodifiableList(builder.modeledExceptions);
this.defaultServiceExceptionSupplier = builder.defaultServiceExceptionSupplier;
this.errorUnmarshaller = timeUnmarshalling(AwsXmlErrorProtocolUnmarshaller
.builder()
.defaultExceptionSupplier(defaultServiceExceptionSupplier)
.exceptions(modeledExceptions)
// We don't set result wrapper since that's handled by the errorRootExtractor
.errorUnmarshaller(QueryProtocolUnmarshaller.builder().build())
.errorRootExtractor(this::getErrorRoot)
.build());
}
/**
* Creates a new marshaller for the given request.
*
* @param operationInfo Object containing metadata about the operation.
* @return New {@link ProtocolMarshaller}.
*/
public final ProtocolMarshaller<SdkHttpFullRequest> createProtocolMarshaller(
OperationInfo operationInfo) {
return QueryProtocolMarshaller.builder()
.endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT))
.operationInfo(operationInfo)
.isEc2(isEc2())
.build();
}
/**
* Creates the success response handler to unmarshall the response into a POJO.
*
* @param pojoSupplier Supplier of the POJO builder we are unmarshalling into.
* @param <T> Type being unmarshalled.
* @return New {@link HttpResponseHandler} for success responses.
*/
public final <T extends AwsResponse> HttpResponseHandler<T> createResponseHandler(Supplier<SdkPojo> pojoSupplier) {
return timeUnmarshalling(new AwsQueryResponseHandler<>(QueryProtocolUnmarshaller.builder()
.hasResultWrapper(!isEc2())
.build(), r -> pojoSupplier.get()));
}
/**
* @return A {@link HttpResponseHandler} that will unmarshall the service exceptional response into
* a modeled exception or the service base exception.
*/
public final HttpResponseHandler<AwsServiceException> createErrorResponseHandler() {
return errorUnmarshaller;
}
private <T> MetricCollectingHttpResponseHandler<T> timeUnmarshalling(HttpResponseHandler<T> delegate) {
return MetricCollectingHttpResponseHandler.create(CoreMetric.UNMARSHALLING_DURATION, delegate);
}
/**
* Extracts the <Error/> element from the root XML document. Method is protected as EC2 has a slightly
* different location.
*
* @param document Root XML document.
* @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one.
*/
Optional<XmlElement> getErrorRoot(XmlElement document) {
return document.getOptionalElementByName("Error");
}
/**
* EC2 has a few distinct differences from query so we wire things up a bit differently.
*/
boolean isEc2() {
return false;
}
/**
* @return New Builder instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsQueryProtocolFactory}.
*
* @param <SubclassT> Subclass of Builder for fluent method chaining.
*/
public static class Builder<SubclassT extends Builder> {
private final List<ExceptionMetadata> modeledExceptions = new ArrayList<>();
private SdkClientConfiguration clientConfiguration;
private Supplier<SdkPojo> defaultServiceExceptionSupplier;
Builder() {
}
/**
* Sets the {@link SdkClientConfiguration} which contains the service endpoint.
*
* @param clientConfiguration Configuration of the client.
* @return This builder for method chaining.
*/
public final SubclassT clientConfiguration(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
return getSubclass();
}
/**
* Registers a new modeled exception by the error code.
*
* @param errorMetadata metadata for unmarshalling the exceptions
* @return This builder for method chaining.
*/
public final SubclassT registerModeledException(ExceptionMetadata errorMetadata) {
modeledExceptions.add(errorMetadata);
return getSubclass();
}
/**
* A supplier for the services base exception builder. This is used when we can't identify any modeled
* exception to unmarshall into.
*
* @param exceptionBuilderSupplier Suppplier of the base service exceptions Builder.
* @return This builder for method chaining.
*/
public final SubclassT defaultServiceExceptionSupplier(Supplier<SdkPojo> exceptionBuilderSupplier) {
this.defaultServiceExceptionSupplier = exceptionBuilderSupplier;
return getSubclass();
}
@SuppressWarnings("unchecked")
private SubclassT getSubclass() {
return (SubclassT) this;
}
/**
* @return New instance of {@link AwsQueryProtocolFactory}.
*/
public AwsQueryProtocolFactory build() {
return new AwsQueryProtocolFactory(this);
}
}
}
| 2,491 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/AwsEc2ProtocolFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
/**
* Protocol factory for the AWS/EC2 protocol.
*/
@SdkProtectedApi
public final class AwsEc2ProtocolFactory extends AwsQueryProtocolFactory {
private AwsEc2ProtocolFactory(Builder builder) {
super(builder);
}
@Override
boolean isEc2() {
return true;
}
/**
* EC2 has a slightly different location for the <Error/> element than traditional AWS/Query.
*
* @param document Root XML document.
* @return If error root is found than a fulfilled {@link Optional}, otherwise an empty one.
*/
@Override
Optional<XmlElement> getErrorRoot(XmlElement document) {
return document.getOptionalElementByName("Errors")
.flatMap(e -> e.getOptionalElementByName("Error"));
}
/**
* @return New builder instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link AwsEc2ProtocolFactory}.
*/
public static final class Builder extends AwsQueryProtocolFactory.Builder<Builder> {
private Builder() {
}
@Override
public AwsEc2ProtocolFactory build() {
return new AwsEc2ProtocolFactory(this);
}
}
}
| 2,492 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/MapQueryUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import static java.util.Collections.singletonList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.traits.MapTrait;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
@SdkInternalApi
public final class MapQueryUnmarshaller implements QueryUnmarshaller<Map<String, ?>> {
@Override
public Map<String, ?> unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<Map<String, ?>> field) {
Map<String, Object> map = new HashMap<>();
MapTrait mapTrait = field.getTrait(MapTrait.class);
SdkField mapValueSdkField = mapTrait.valueFieldInfo();
getEntries(content, mapTrait).forEach(entry -> {
XmlElement key = entry.getElementByName(mapTrait.keyLocationName());
XmlElement value = entry.getElementByName(mapTrait.valueLocationName());
QueryUnmarshaller unmarshaller = context.getUnmarshaller(mapValueSdkField.location(),
mapValueSdkField.marshallingType());
map.put(key.textContent(),
unmarshaller.unmarshall(context, singletonList(value), mapValueSdkField));
});
return map;
}
private List<XmlElement> getEntries(List<XmlElement> content, MapTrait mapTrait) {
return mapTrait.isFlattened() ?
content :
content.get(0).getElementsByName("entry");
}
}
| 2,493 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshallerRegistry.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.core.AbstractMarshallingRegistry;
/**
* Registry of {@link QueryUnmarshaller} implementations by location and type.
*/
@SdkInternalApi
public final class QueryUnmarshallerRegistry extends AbstractMarshallingRegistry {
private QueryUnmarshallerRegistry(Builder builder) {
super(builder);
}
@SuppressWarnings("unchecked")
public <T> QueryUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) {
return (QueryUnmarshaller<Object>) super.get(marshallLocation, marshallingType);
}
/**
* @return Builder instance to construct a {@link QueryUnmarshallerRegistry}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for a {@link QueryUnmarshallerRegistry}.
*/
public static final class Builder extends AbstractMarshallingRegistry.Builder {
private Builder() {
}
public <T> Builder unmarshaller(MarshallingType<T> marshallingType,
QueryUnmarshaller<T> marshaller) {
register(MarshallLocation.PAYLOAD, marshallingType, marshaller);
return this;
}
/**
* @return An immutable {@link QueryUnmarshallerRegistry} object.
*/
public QueryUnmarshallerRegistry build() {
return new QueryUnmarshallerRegistry(this);
}
}
}
| 2,494 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
@SdkInternalApi
public interface QueryUnmarshaller<T> {
/**
* @param context Context containing dependencies and unmarshaller registry.
* @param content Parsed JSON content of body. May be null for REST JSON based services that don't have payload members.
* @param field {@link SdkField} of member being unmarshalled.
* @return Unmarshalled value.
*/
T unmarshall(QueryUnmarshallerContext context,
List<XmlElement> content,
SdkField<T> field);
}
| 2,495 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/AwsXmlErrorUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller;
/**
* Unmarshalls an AWS XML exception from parsed XML.
*/
@SdkInternalApi
public final class AwsXmlErrorUnmarshaller {
private static final String X_AMZ_ID_2_HEADER = "x-amz-id-2";
private final List<ExceptionMetadata> exceptions;
private final Supplier<SdkPojo> defaultExceptionSupplier;
private final XmlErrorUnmarshaller errorUnmarshaller;
private AwsXmlErrorUnmarshaller(Builder builder) {
this.exceptions = builder.exceptions;
this.errorUnmarshaller = builder.errorUnmarshaller;
this.defaultExceptionSupplier = builder.defaultExceptionSupplier;
}
/**
* @return New Builder instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Unmarshal an AWS XML exception
* @param documentRoot The parsed payload document
* @param errorRoot The specific element of the parsed payload document that contains the error to be marshalled
* or empty if it could not be located.
* @param documentBytes The raw bytes of the original payload document if they are available
* @param response The HTTP response object
* @param executionAttributes {@link ExecutionAttributes} for the current execution
* @return An {@link AwsServiceException} unmarshalled from the XML.
*/
public AwsServiceException unmarshall(XmlElement documentRoot,
Optional<XmlElement> errorRoot,
Optional<SdkBytes> documentBytes,
SdkHttpFullResponse response,
ExecutionAttributes executionAttributes) {
String errorCode = getErrorCode(errorRoot);
AwsServiceException.Builder builder = errorRoot
.map(e -> invokeSafely(() -> unmarshallFromErrorCode(response, e, errorCode)))
.orElseGet(this::defaultException);
AwsErrorDetails awsErrorDetails =
AwsErrorDetails.builder()
.errorCode(errorCode)
.errorMessage(builder.message())
.rawResponse(documentBytes.orElse(null))
.sdkHttpResponse(response)
.serviceName(executionAttributes.getAttribute(AwsExecutionAttribute.SERVICE_NAME))
.build();
builder.requestId(getRequestId(response, documentRoot))
.extendedRequestId(getExtendedRequestId(response))
.statusCode(response.statusCode())
.clockSkew(getClockSkew(executionAttributes))
.awsErrorDetails(awsErrorDetails);
return builder.build();
}
private Duration getClockSkew(ExecutionAttributes executionAttributes) {
Integer timeOffset = executionAttributes.getAttribute(SdkExecutionAttribute.TIME_OFFSET);
return timeOffset == null ? null : Duration.ofSeconds(timeOffset);
}
/**
* @return Builder for the default service exception. Used when the error code doesn't match
* any known modeled exception or when we can't determine the error code.
*/
private AwsServiceException.Builder defaultException() {
return (AwsServiceException.Builder) defaultExceptionSupplier.get();
}
/**
* Unmarshalls the XML into the appropriate modeled exception based on the error code. If the error code
* is not present or does not match any known exception we unmarshall into the base service exception.
*
* @param errorRoot Root of <Error/> element. Contains any modeled fields of the exception.
* @param errorCode Error code identifying the modeled exception.
* @return Unmarshalled exception builder.
*/
private AwsServiceException.Builder unmarshallFromErrorCode(SdkHttpFullResponse response,
XmlElement errorRoot,
String errorCode) {
SdkPojo sdkPojo = exceptions.stream()
.filter(e -> e.errorCode().equals(errorCode))
.map(ExceptionMetadata::exceptionBuilderSupplier)
.findAny()
.orElse(defaultExceptionSupplier)
.get();
AwsServiceException.Builder builder =
((AwsServiceException) errorUnmarshaller.unmarshall(sdkPojo, errorRoot, response)).toBuilder();
builder.message(getMessage(errorRoot));
return builder;
}
/**
* Extracts the error code (used to identify the modeled exception) from the <Error/>
* element.
*
* @param errorRoot Error element root.
* @return Error code or null if not present.
*/
private String getErrorCode(Optional<XmlElement> errorRoot) {
return errorRoot.map(e -> e.getOptionalElementByName("Code")
.map(XmlElement::textContent)
.orElse(null))
.orElse(null);
}
/**
* Extracts the error message from the XML document. The message is in the <Error/>
* element for all services.
*
* @param errorRoot Error element root.
* @return Error message or null if not present.
*/
private String getMessage(XmlElement errorRoot) {
return errorRoot.getOptionalElementByName("Message")
.map(XmlElement::textContent)
.orElse(null);
}
/**
* Extracts the request ID from the XML document. Request ID is a top level element
* for all protocols, it may be RequestId or RequestID depending on the service.
*
* @param document Root XML document.
* @return Request ID string or null if not present.
*/
private String getRequestId(SdkHttpFullResponse response, XmlElement document) {
XmlElement requestId = document.getOptionalElementByName("RequestId")
.orElseGet(() -> document.getElementByName("RequestID"));
return requestId != null ?
requestId.textContent() :
matchRequestIdHeaders(response);
}
private String matchRequestIdHeaders(SdkHttpFullResponse response) {
return HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS.stream()
.map(h -> response.firstMatchingHeader(h))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElse(null);
}
/**
* Extracts the extended request ID from the response headers.
*
* @param response The HTTP response object.
* @return Extended Request ID string or null if not present.
*/
private String getExtendedRequestId(SdkHttpFullResponse response) {
return response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(null);
}
/**
* Builder for {@link AwsXmlErrorUnmarshaller}.
*/
public static final class Builder {
private List<ExceptionMetadata> exceptions;
private Supplier<SdkPojo> defaultExceptionSupplier;
private XmlErrorUnmarshaller errorUnmarshaller;
private Builder() {
}
/**
* List of {@link ExceptionMetadata} to represent the modeled exceptions for the service.
* For AWS services the error type is a string representing the type of the modeled exception.
*
* @return This builder for method chaining.
*/
public Builder exceptions(List<ExceptionMetadata> exceptions) {
this.exceptions = exceptions;
return this;
}
/**
* Default exception type if "error code" does not match any known modeled exception. This is the generated
* base exception for the service (i.e. DynamoDbException).
*
* @return This builder for method chaining.
*/
public Builder defaultExceptionSupplier(Supplier<SdkPojo> defaultExceptionSupplier) {
this.defaultExceptionSupplier = defaultExceptionSupplier;
return this;
}
/**
* The unmarshaller to use. The unmarshaller only unmarshalls any modeled fields of the exception,
* additional metadata is extracted by {@link AwsXmlErrorUnmarshaller}.
*
* @param errorUnmarshaller Error unmarshaller to use.
* @return This builder for method chaining.
*/
public Builder errorUnmarshaller(XmlErrorUnmarshaller errorUnmarshaller) {
this.errorUnmarshaller = errorUnmarshaller;
return this;
}
/**
* @return New instance of {@link AwsXmlErrorUnmarshaller}.
*/
public AwsXmlErrorUnmarshaller build() {
return new AwsXmlErrorUnmarshaller(this);
}
}
}
| 2,496 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/ListQueryUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import static java.util.Collections.singletonList;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.traits.ListTrait;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
@SdkInternalApi
public final class ListQueryUnmarshaller implements QueryUnmarshaller<List<?>> {
@Override
public List<?> unmarshall(QueryUnmarshallerContext context, List<XmlElement> content, SdkField<List<?>> field) {
ListTrait listTrait = field.getTrait(ListTrait.class);
List<Object> list = new ArrayList<>();
getMembers(content, listTrait).forEach(member -> {
QueryUnmarshaller unmarshaller = context.getUnmarshaller(listTrait.memberFieldInfo().location(),
listTrait.memberFieldInfo().marshallingType());
list.add(unmarshaller.unmarshall(context, singletonList(member), listTrait.memberFieldInfo()));
});
return list;
}
private List<XmlElement> getMembers(List<XmlElement> content, ListTrait listTrait) {
return listTrait.isFlattened() ?
content :
// There have been cases in EC2 where the member name is not modeled correctly so we just grab all
// direct children instead and don't care about member name. See TT0124273367 for more information.
content.get(0).children();
}
}
| 2,497 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryProtocolUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID;
import static software.amazon.awssdk.protocols.query.internal.marshall.SimpleTypeQueryMarshaller.defaultTimestampFormats;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.core.traits.PayloadTrait;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.protocols.core.StringToInstant;
import software.amazon.awssdk.protocols.core.StringToValueConverter;
import software.amazon.awssdk.protocols.query.unmarshall.XmlDomParser;
import software.amazon.awssdk.protocols.query.unmarshall.XmlElement;
import software.amazon.awssdk.protocols.query.unmarshall.XmlErrorUnmarshaller;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.builder.Buildable;
/**
* Unmarshaller implementation for AWS/Query and EC2 services.
*/
@SdkInternalApi
public final class QueryProtocolUnmarshaller implements XmlErrorUnmarshaller {
private static final QueryUnmarshallerRegistry UNMARSHALLER_REGISTRY = QueryUnmarshallerRegistry
.builder()
.unmarshaller(MarshallingType.STRING, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_STRING))
.unmarshaller(MarshallingType.INTEGER, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_INTEGER))
.unmarshaller(MarshallingType.LONG, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_LONG))
.unmarshaller(MarshallingType.SHORT, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_SHORT))
.unmarshaller(MarshallingType.FLOAT, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_FLOAT))
.unmarshaller(MarshallingType.DOUBLE, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_DOUBLE))
.unmarshaller(MarshallingType.BOOLEAN, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_BOOLEAN))
.unmarshaller(MarshallingType.DOUBLE, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_DOUBLE))
.unmarshaller(MarshallingType.INSTANT,
new SimpleTypeQueryUnmarshaller<>(StringToInstant.create(defaultTimestampFormats())))
.unmarshaller(MarshallingType.SDK_BYTES, new SimpleTypeQueryUnmarshaller<>(StringToValueConverter.TO_SDK_BYTES))
.unmarshaller(MarshallingType.LIST, new ListQueryUnmarshaller())
.unmarshaller(MarshallingType.MAP, new MapQueryUnmarshaller())
.unmarshaller(MarshallingType.NULL, (context, content, field) -> null)
.unmarshaller(MarshallingType.SDK_POJO, (context, content, field) ->
context.protocolUnmarshaller().unmarshall(context, field.constructor().get(), content.get(0)))
.build();
private final boolean hasResultWrapper;
private QueryProtocolUnmarshaller(Builder builder) {
this.hasResultWrapper = builder.hasResultWrapper;
}
public <TypeT extends SdkPojo> Pair<TypeT, Map<String, String>> unmarshall(SdkPojo sdkPojo,
SdkHttpFullResponse response) {
if (responsePayloadIsBlob(sdkPojo)) {
XmlElement document = XmlElement.builder()
.textContent(response.content()
.map(s -> invokeSafely(() -> IoUtils.toUtf8String(s)))
.orElse(""))
.build();
return Pair.of(unmarshall(sdkPojo, document, response), new HashMap<>());
}
XmlElement document = response.content().map(XmlDomParser::parse).orElseGet(XmlElement::empty);
XmlElement resultRoot = hasResultWrapper ? document.getFirstChild() : document;
return Pair.of(unmarshall(sdkPojo, resultRoot, response), parseMetadata(document));
}
private boolean responsePayloadIsBlob(SdkPojo sdkPojo) {
return sdkPojo.sdkFields().stream()
.anyMatch(field -> field.marshallingType() == MarshallingType.SDK_BYTES &&
field.containsTrait(PayloadTrait.class));
}
/**
* This method is also used to unmarshall exceptions. We use this since we've already parsed the XML
* and the result root is in a different location depending on the protocol/service.
*/
@Override
public <TypeT extends SdkPojo> TypeT unmarshall(SdkPojo sdkPojo,
XmlElement resultRoot,
SdkHttpFullResponse response) {
QueryUnmarshallerContext unmarshallerContext = QueryUnmarshallerContext.builder()
.registry(UNMARSHALLER_REGISTRY)
.protocolUnmarshaller(this)
.build();
return (TypeT) unmarshall(unmarshallerContext, sdkPojo, resultRoot);
}
private Map<String, String> parseMetadata(XmlElement document) {
XmlElement responseMetadata = document.getElementByName("ResponseMetadata");
Map<String, String> metadata = new HashMap<>();
if (responseMetadata != null) {
responseMetadata.children().forEach(c -> metadata.put(metadataKeyName(c), c.textContent()));
}
XmlElement requestId = document.getElementByName("requestId");
if (requestId != null) {
metadata.put(AWS_REQUEST_ID, requestId.textContent());
}
return metadata;
}
private String metadataKeyName(XmlElement c) {
return c.elementName().equals("RequestId") ? AWS_REQUEST_ID : c.elementName();
}
private SdkPojo unmarshall(QueryUnmarshallerContext context, SdkPojo sdkPojo, XmlElement root) {
if (root != null) {
for (SdkField<?> field : sdkPojo.sdkFields()) {
if (field.containsTrait(PayloadTrait.class) && field.marshallingType() == MarshallingType.SDK_BYTES) {
field.set(sdkPojo, SdkBytes.fromUtf8String(root.textContent()));
}
List<XmlElement> element = root.getElementsByName(field.unmarshallLocationName());
if (!CollectionUtils.isNullOrEmpty(element)) {
QueryUnmarshaller<Object> unmarshaller =
UNMARSHALLER_REGISTRY.getUnmarshaller(field.location(), field.marshallingType());
Object unmarshalled = unmarshaller.unmarshall(context, element, (SdkField<Object>) field);
field.set(sdkPojo, unmarshalled);
}
}
}
return (SdkPojo) ((Buildable) sdkPojo).build();
}
/**
* @return New {@link Builder} instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link QueryProtocolUnmarshaller}.
*/
public static final class Builder {
private boolean hasResultWrapper;
private Builder() {
}
/**
* <h3>Example response with result wrapper</h3>
* <pre>
* {@code
* <ListQueuesResponse>
* <ListQueuesResult>
* <QueueUrl>https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue</QueueUrl>
* </ListQueuesResult>
* <ResponseMetadata>
* <RequestId>725275ae-0b9b-4762-b238-436d7c65a1ac</RequestId>
* </ResponseMetadata>
* </ListQueuesResponse>
* }
* </pre>
*
* <h3>Example response without result wrapper</h3>
* <pre>
* {@code
* <DescribeAddressesResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/">
* <requestId>f7de5e98-491a-4c19-a92d-908d6EXAMPLE</requestId>
* <addressesSet>
* <item>
* <publicIp>203.0.113.41</publicIp>
* <allocationId>eipalloc-08229861</allocationId>
* <domain>vpc</domain>
* <instanceId>i-0598c7d356eba48d7</instanceId>
* <associationId>eipassoc-f0229899</associationId>
* <networkInterfaceId>eni-ef229886</networkInterfaceId>
* <networkInterfaceOwnerId>053230519467</networkInterfaceOwnerId>
* <privateIpAddress>10.0.0.228</privateIpAddress>
* </item>
* </addressesSet>
* </DescribeAddressesResponse>
* }
* </pre>
*
* @param hasResultWrapper True if the response has a result wrapper, false if the result is in the top level
* XML document.
* @return This builder for method chaining.
*/
public Builder hasResultWrapper(boolean hasResultWrapper) {
this.hasResultWrapper = hasResultWrapper;
return this;
}
/**
* @return New instance of {@link QueryProtocolUnmarshaller}.
*/
public QueryProtocolUnmarshaller build() {
return new QueryProtocolUnmarshaller(this);
}
}
}
| 2,498 |
0 | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal | Create_ds/aws-sdk-java-v2/core/protocols/aws-query-protocol/src/main/java/software/amazon/awssdk/protocols/query/internal/unmarshall/QueryUnmarshallerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.protocols.query.internal.unmarshall;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.protocol.MarshallLocation;
import software.amazon.awssdk.core.protocol.MarshallingType;
/**
* Container for dependencies used during AWS/Query unmarshalling.
*/
@SdkInternalApi
public final class QueryUnmarshallerContext {
private final QueryUnmarshallerRegistry registry;
private final QueryProtocolUnmarshaller protocolUnmarshaller;
private QueryUnmarshallerContext(Builder builder) {
this.registry = builder.registry;
this.protocolUnmarshaller = builder.protocolUnmarshaller;
}
/**
* @return Protocol unmarshaller used for unmarshalling nested structs.
*/
public QueryProtocolUnmarshaller protocolUnmarshaller() {
return protocolUnmarshaller;
}
/**
* Conveience method to get an unmarshaller from the registry.
*
* @param marshallLocation Location of field being unmarshalled.
* @param marshallingType Type of field being unmarshalled.
* @param <T> Type of field being unmarshalled.
* @return Unmarshaller implementation.
*/
public <T> QueryUnmarshaller<Object> getUnmarshaller(MarshallLocation marshallLocation, MarshallingType<T> marshallingType) {
return registry.getUnmarshaller(marshallLocation, marshallingType);
}
/**
* @return New {@link Builder} instance.
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder for {@link QueryUnmarshallerContext}.
*/
public static final class Builder {
private QueryUnmarshallerRegistry registry;
private QueryProtocolUnmarshaller protocolUnmarshaller;
private Builder() {
}
public Builder registry(QueryUnmarshallerRegistry registry) {
this.registry = registry;
return this;
}
public Builder protocolUnmarshaller(QueryProtocolUnmarshaller protocolUnmarshaller) {
this.protocolUnmarshaller = protocolUnmarshaller;
return this;
}
public QueryUnmarshallerContext build() {
return new QueryUnmarshallerContext(this);
}
}
}
| 2,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.