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/test/test-utils/src/test/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/hamcrest/CollectionContainsOnlyInOrderTest.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.testutils.hamcrest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static software.amazon.awssdk.testutils.hamcrest.Matchers.containsOnlyInOrder; import java.util.Arrays; import java.util.List; import org.junit.Test; public class CollectionContainsOnlyInOrderTest { private final List<String> list = Arrays.asList("hello", "world"); private final List<String> listWithDuplicates = Arrays.asList("hello", "world", "hello"); @Test public void matchesIfAllElementsArePresentInOrder() { assertThat(list, containsOnlyInOrder("hello", "world")); } @Test(expected = AssertionError.class) public void failsIfElementsAreOutOfOrder() { assertThat(list, containsOnlyInOrder("world", "hello")); } @Test(expected = AssertionError.class) public void failsIfElementIsMissing() { assertThat(list, containsOnlyInOrder("hello", "world", "yay")); } @Test(expected = AssertionError.class) public void failsIfElementCollectionHasUnexpectedElement() { assertThat(list, containsOnlyInOrder("hello")); } @Test public void worksWithMatchers() { assertThat(list, containsOnlyInOrder(endsWith("lo"), endsWith("ld"))); } @Test public void canHandleDuplicateElementsInCollectionUnderTest() { assertThat(listWithDuplicates, containsOnlyInOrder("hello", "world", "hello")); } @Test(expected = AssertionError.class) public void missingDuplicatesAreConsideredAFailure() { assertThat(listWithDuplicates, containsOnlyInOrder("hello", "world")); } @Test(expected = AssertionError.class) public void orderIsImportantWithDuplicatesToo() { assertThat(listWithDuplicates, containsOnlyInOrder("hello", "hello", "world")); } }
2,700
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/hamcrest/CollectionContainsOnlyTest.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.testutils.hamcrest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; import static software.amazon.awssdk.testutils.hamcrest.Matchers.containsOnly; import java.util.Arrays; import java.util.List; import org.junit.Test; public class CollectionContainsOnlyTest { private final List<String> list = Arrays.asList("hello", "world"); private final List<String> listWithDuplicates = Arrays.asList("hello", "world", "hello"); @Test public void matchesIfAllElementsArePresent() { assertThat(list, containsOnly("hello", "world")); } @Test public void matchesIfAllElementsArePresentInAnyOrder() { assertThat(list, containsOnly("world", "hello")); } @Test(expected = AssertionError.class) public void failsIfElementIsMissing() { assertThat(list, containsOnly("hello", "world", "yay")); } @Test(expected = AssertionError.class) public void failsIfElementCollectionHasUnexpectedElement() { assertThat(list, containsOnly("hello")); } @Test public void worksWithMatchers() { assertThat(list, containsOnly(endsWith("lo"), endsWith("ld"))); } @Test public void canHandleDuplicateElementsInCollectionUnderTest() { assertThat(listWithDuplicates, containsOnly("hello", "hello", "world")); } @Test(expected = AssertionError.class) public void missingDuplicatesAreConsideredAFailure() { assertThat(listWithDuplicates, containsOnly("hello", "world")); } }
2,701
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/retry/RetryableActionTest.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.testutils.retry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import java.util.concurrent.Callable; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class RetryableActionTest { @Mock private Callable<String> callable; @Test public void actionFailsWithRetryableError_RetriesUpToMaxAttempts() throws Exception { when(callable.call()).thenThrow(new RetryableError(new SomeError())); try { doRetryableAction(); fail("Expected SomeError"); } catch (SomeError expected) { } Mockito.verify(callable, Mockito.times(3)).call(); } @Test public void actionFailsWithNonRetryableException_DoesNotRetry() throws Exception { when(callable.call()).thenThrow(new NonRetryableException(new SomeException())); try { doRetryableAction(); fail("Expected SomeException"); } catch (SomeException expected) { } Mockito.verify(callable, Mockito.times(1)).call(); } @Test public void actionFailsWithException_RetriesUpToMaxAttempts() throws Exception { when(callable.call()).thenThrow(new SomeException()); try { doRetryableAction(); fail("Expected SomeException"); } catch (SomeException expected) { } Mockito.verify(callable, Mockito.times(3)).call(); } @Test public void actionFailsOnceWithExceptionThenSucceeds_RetriesOnceThenReturns() throws Exception { // Throw on the first and return on the second when(callable.call()) .thenThrow(new SomeException()) .thenReturn("foo"); assertEquals("foo", doRetryableAction()); Mockito.verify(callable, Mockito.times(2)).call(); } @Test public void actionSucceedsOnFirstAttempt_DoesNotRetry() throws Exception { when(callable.call()).thenReturn("foo"); assertEquals("foo", doRetryableAction()); Mockito.verify(callable, Mockito.times(1)).call(); } private String doRetryableAction() throws Exception { return RetryableAction.doRetryableAction(callable, new RetryableParams() .withMaxAttempts(3) .withDelayInMs(10)); } private static class SomeError extends Error { } private static class SomeException extends Exception { } }
2,702
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/retry/RetryableAssertionTest.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.testutils.retry; import static org.junit.Assert.fail; import java.io.IOException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class RetryableAssertionTest { @Mock private AssertCallable callable; @Test public void assertAlwaysFails_RetriesUpToMaxAttempts() throws Exception { Mockito.when(callable.call()).thenThrow(new AssertionError("Assertion failed")); try { doRetryableAssert(); fail("Expected AssertionError"); } catch (AssertionError expected) { } Mockito.verify(callable, Mockito.times(3)).call(); } @Test public void assertFailsOnce_RetriesOnceThenReturns() throws Exception { // Throw on the first and return on the second Mockito.doThrow(new AssertionError("Assertion failed")) .doNothing() .when(callable).call(); doRetryableAssert(); Mockito.verify(callable, Mockito.times(2)).call(); } @Test public void assertCallableThrowsException_DoesNotContinueRetrying() throws Exception { Mockito.when(callable.call()) .thenThrow(new IOException("Unexpected exception in assert logic")); try { doRetryableAssert(); fail("Expected IOException"); } catch (IOException expected) { } Mockito.verify(callable, Mockito.times(1)).call(); } private void doRetryableAssert() throws Exception { RetryableAssertion.doRetryableAssert(callable, new RetryableParams() .withMaxAttempts(3) .withDelayInMs(10)); } }
2,703
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/smoketest/ReflectionUtilsTest.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.testutils.smoketest; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import org.junit.jupiter.api.Test; @SuppressWarnings("unused") public class ReflectionUtilsTest { @Test public void canSetAllNonStaticFields() { TestClass instance = ReflectionUtils.newInstanceWithAllFieldsSet(TestClass.class); assertThat(instance.stringProperty, is(notNullValue())); assertThat(instance.booleanProperty, is(notNullValue())); assertThat(instance.longProperty, is(notNullValue())); assertThat(instance.intProperty, is(notNullValue())); assertThat(instance.primitiveBooleanProperty, is(true)); } @Test public void canGiveSupplierForCustomType() { final TestClass complex = mock(TestClass.class); ClassWithComplexClass instance = ReflectionUtils.newInstanceWithAllFieldsSet(ClassWithComplexClass.class, new ReflectionUtils.RandomSupplier<TestClass>() { @Override public TestClass getNext() { return complex; } @Override public Class<TestClass> targetClass() { return TestClass.class; } }); assertThat(instance.complexClass, is(sameInstance(complex))); } public static class ClassWithComplexClass { private TestClass complexClass; } public static class TestClass { private String stringProperty; private Boolean booleanProperty; private Integer intProperty; private Long longProperty; private boolean primitiveBooleanProperty; } }
2,704
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Statement.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.core.auth.policy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * A statement is the formal description of a single permission, and is always * contained within a policy object. * <p> * A statement describes a rule for allowing or denying access to a specific AWS * resource based on how the resource is being accessed, and who is attempting * to access the resource. Statements can also optionally contain a list of * conditions that specify when a statement is to be honored. * <p> * For example, consider a statement that: * <ul> * <li>allows access (the effect) * <li>for a list of specific AWS account IDs (the principals) * <li>when accessing an SQS queue (the resource) * <li>using the SendMessage operation (the action) * <li>and the request occurs before a specific date (a condition) * </ul> * * <p> * Statements takes the form: "A has permission to do B to C where D applies". * <ul> * <li>A is the <b>principal</b> - the AWS account that is making a request to * access or modify one of your AWS resources. * <li>B is the <b>action</b> - the way in which your AWS resource is being accessed or modified, such * as sending a message to an Amazon SQS queue, or storing an object in an Amazon S3 bucket. * <li>C is the <b>resource</b> - your AWS entity that the principal wants to access, such * as an Amazon SQS queue, or an object stored in Amazon S3. * <li>D is the set of <b>conditions</b> - optional constraints that specify when to allow or deny * access for the principal to access your resource. Many expressive conditions are available, * some specific to each service. For example you can use date conditions to allow access to * your resources only after or before a specific time. * </ul> * * <p> * There are many resources and conditions available for use in statements, and * you can combine them to form fine grained custom access control polices. */ public class Statement { private String id; private Effect effect; private List<Principal> principals = new ArrayList<>(); private List<Action> actions = new ArrayList<>(); private List<Resource> resources; private List<Condition> conditions = new ArrayList<>(); /** * Constructs a new access control policy statement with the specified * effect. * <p> * Before a statement is valid and can be sent to AWS, callers must set the * principals, resources, and actions (as well as any optional conditions) * involved in the statement. * * @param effect * The effect this statement has (allowing access or denying * access) when all conditions, resources, principals, and * actions are matched. */ public Statement(Effect effect) { this.effect = effect; this.id = null; } /** * Returns the ID for this statement. Statement IDs serve to help keep track * of multiple statements, and are often used to give the statement a * meaningful, human readable name. * <p> * Statement IDs must be unique within a policy, but are not required to be * globally unique. * <p> * If you do not explicitly assign an ID to a statement, a unique ID will be * automatically assigned when the statement is added to a policy. * <p> * Developers should be careful to not use the same statement ID for * multiple statements in the same policy. Reusing the same statement ID in * different policies is not a problem. * * @return The statement ID. */ public String getId() { return id; } /** * Sets the ID for this statement. Statement IDs serve to help keep track of * multiple statements, and are often used to give the statement a * meaningful, human readable name. * <p> * Statement IDs must be unique within a policy, but are not required to be * globally unique. * <p> * If you do not explicitly assign an ID to a statement, a unique ID will be * automatically assigned when the statement is added to a policy. * <p> * Developers should be careful to not use the same statement ID for * multiple statements in the same policy. Reusing the same statement ID in * different policies is not a problem. * * @param id * The new statement ID for this statement. */ public void setId(String id) { this.id = id; } /** * Sets the ID for this statement and returns the updated statement so * multiple calls can be chained together. * <p> * Statement IDs serve to help keep track of multiple statements, and are * often used to give the statement a meaningful, human readable name. * <p> * If you do not explicitly assign an ID to a statement, a unique ID will be * automatically assigned when the statement is added to a policy. * <p> * Developers should be careful to not use the same statement ID for * multiple statements in the same policy. Reusing the same statement ID in * different policies is not a problem. * * @param id * The new statement ID for this statement. */ public Statement withId(String id) { setId(id); return this; } /** * Returns the result effect of this policy statement when it is evaluated. * A policy statement can either allow access or explicitly * * @return The result effect of this policy statement. */ public Effect getEffect() { return effect; } /** * Sets the result effect of this policy statement when it is evaluated. A * policy statement can either allow access or explicitly * * @param effect * The result effect of this policy statement. */ public void setEffect(Effect effect) { this.effect = effect; } /** * Returns the list of actions to which this policy statement applies. * Actions limit a policy statement to specific service operations that are * being allowed or denied by the policy statement. For example, you might * want to allow any AWS user to post messages to your SQS queue using the * SendMessage action, but you don't want to allow those users other actions * such as ReceiveMessage or DeleteQueue. * * @return The list of actions to which this policy statement applies. */ public List<Action> getActions() { return actions; } /** * Sets the list of actions to which this policy statement applies. Actions * limit a policy statement to specific service operations that are being * allowed or denied by the policy statement. For example, you might want to * allow any AWS user to post messages to your SQS queue using the * SendMessage action, but you don't want to allow those users other actions * such as ReceiveMessage or DeleteQueue. * * @param actions * The list of actions to which this policy statement applies. */ public void setActions(Collection<Action> actions) { this.actions = new ArrayList<>(actions); } /** * Sets the list of actions to which this policy statement applies and * returns this updated Statement object so that additional method calls can * be chained together. * <p> * Actions limit a policy statement to specific service operations that are * being allowed or denied by the policy statement. For example, you might * want to allow any AWS user to post messages to your SQS queue using the * SendMessage action, but you don't want to allow those users other actions * such as ReceiveMessage or DeleteQueue. * * @param actions * The list of actions to which this statement applies. * * @return The updated Statement object so that additional method calls can * be chained together. */ public Statement withActions(Action... actions) { setActions(Arrays.asList(actions)); return this; } /** * Returns the resources associated with this policy statement. Resources * are what a policy statement is allowing or denying access to, such as an * Amazon SQS queue or an Amazon SNS topic. * <p> * Note that some services allow only one resource to be specified per * policy statement. * * @return The resources associated with this policy statement. */ public List<Resource> getResources() { return resources; } /** * Sets the resources associated with this policy statement. Resources are * what a policy statement is allowing or denying access to, such as an * Amazon SQS queue or an Amazon SNS topic. * <p> * Note that some services allow only one resource to be specified per * policy statement. * * @param resources * The resources associated with this policy statement. */ public void setResources(Collection<Resource> resources) { this.resources = new ArrayList<>(resources); } /** * Sets the resources associated with this policy statement and returns this * updated Statement object so that additional method calls can be chained * together. * <p> * Resources are what a policy statement is allowing or denying access to, * such as an Amazon SQS queue or an Amazon SNS topic. * <p> * Note that some services allow only one resource to be specified per * policy statement. * * @param resources * The resources associated with this policy statement. * * @return The updated Statement object so that additional method calls can * be chained together. */ public Statement withResources(Resource... resources) { setResources(Arrays.asList(resources)); return this; } /** * Returns the conditions associated with this policy statement. Conditions * allow policy statements to be conditionally evaluated based on the many * available condition types. * <p> * For example, a statement that allows access to an Amazon SQS queue could * use a condition to only apply the effect of that statement for requests * that are made before a certain date, or that originate from a range of IP * addresses. * <p> * When multiple conditions are included in a single statement, all * conditions must evaluate to true in order for the statement to take * effect. * * @return The conditions associated with this policy statement. */ public List<Condition> getConditions() { return conditions; } /** * Sets the conditions associated with this policy statement. Conditions * allow policy statements to be conditionally evaluated based on the many * available condition types. * <p> * For example, a statement that allows access to an Amazon SQS queue could * use a condition to only apply the effect of that statement for requests * that are made before a certain date, or that originate from a range of IP * addresses. * <p> * Multiple conditions can be included in a single statement, and all * conditions must evaluate to true in order for the statement to take * effect. * * @param conditions * The conditions associated with this policy statement. */ public void setConditions(List<Condition> conditions) { this.conditions = conditions; } /** * Sets the conditions associated with this policy statement, and returns * this updated Statement object so that additional method calls can be * chained together. * <p> * Conditions allow policy statements to be conditionally evaluated based on * the many available condition types. * <p> * For example, a statement that allows access to an Amazon SQS queue could * use a condition to only apply the effect of that statement for requests * that are made before a certain date, or that originate from a range of IP * addresses. * <p> * Multiple conditions can be included in a single statement, and all * conditions must evaluate to true in order for the statement to take * effect. * * @param conditions * The conditions associated with this policy statement. * * @return The updated Statement object so that additional method calls can * be chained together. */ public Statement withConditions(Condition... conditions) { setConditions(Arrays.asList(conditions)); return this; } /** * Returns the principals associated with this policy statement, indicating * which AWS accounts are affected by this policy statement. * * @return The list of principals associated with this policy statement. */ public List<Principal> getPrincipals() { return principals; } /** * Sets the principals associated with this policy statement, indicating * which AWS accounts are affected by this policy statement. * <p> * If you don't want to restrict your policy to specific users, you can use * {@link Principal#ALL_USERS} to apply the policy to any user trying to * access your resource. * * @param principals * The list of principals associated with this policy statement. */ public void setPrincipals(Collection<Principal> principals) { this.principals = new ArrayList<>(principals); } /** * Sets the principals associated with this policy statement, indicating * which AWS accounts are affected by this policy statement. * <p> * If you don't want to restrict your policy to specific users, you can use * {@link Principal#ALL_USERS} to apply the policy to any user trying to * access your resource. * * @param principals * The list of principals associated with this policy statement. */ public void setPrincipals(Principal... principals) { setPrincipals(new ArrayList<>(Arrays.asList(principals))); } /** * Sets the principals associated with this policy statement, and returns * this updated Statement object. Principals control which AWS accounts are * affected by this policy statement. * <p> * If you don't want to restrict your policy to specific users, you can use * {@link Principal#ALL_USERS} to apply the policy to any user trying to * access your resource. * * @param principals * The list of principals associated with this policy statement. * * @return The updated Statement object so that additional method calls can * be chained together. */ public Statement withPrincipals(Principal... principals) { setPrincipals(principals); return this; } /** * The effect is the result that you want a policy statement to return at * evaluation time. A policy statement can either allow access or explicitly * deny access. */ public enum Effect { Allow(), Deny(); } }
2,705
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Resource.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.core.auth.policy; /** * Represents a resource involved in an AWS access control policy statement. * Resources are the service specific AWS entities owned by your account. Amazon * SQS queues, Amazon S3 buckets and objects, and Amazon SNS topics are all * examples of AWS resources. * <p> * The standard way of specifying an AWS resource is with an Amazon Resource * Name (ARN). * <p> * The resource is C in the statement * "A has permission to do B to C where D applies." */ public class Resource { private final String resource; /** * Constructs a new AWS access control policy resource. Resources are * typically specified as Amazon Resource Names (ARNs). * <p> * You specify the resource using the following Amazon Resource Name (ARN) * format: * <b>{@code arn:aws:<vendor>:<region>:<namespace>:<relative-id>}</b> * <p> * <ul> * <li>vendor identifies the AWS product (e.g., sns)</li> * <li>region is the AWS Region the resource resides in (e.g., us-east-1), * if any * <li>namespace is the AWS account ID with no hyphens (e.g., 123456789012) * <li>relative-id is the service specific portion that identifies the * specific resource * </ul> * <p> * For example, an Amazon SQS queue might be addressed with the following * ARN: <b>arn:aws:sqs:us-east-1:987654321000:MyQueue</b> * <p> * Some resources may not use every field in an ARN. For example, resources * in Amazon S3 are global, so they omit the region field: * <b>arn:aws:s3:::bucket/*</b> * * @param resource * The Amazon Resource Name (ARN) uniquely identifying the * desired AWS resource. */ public Resource(String resource) { this.resource = resource; } /** * Returns the resource ID, typically an Amazon Resource Name (ARN), * identifying this resource. * * @return The resource ID, typically an Amazon Resource Name (ARN), * identifying this resource. */ public String getId() { return resource; } }
2,706
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Condition.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.core.auth.policy; import java.util.Arrays; import java.util.List; /** * AWS access control policy conditions are contained in {@link Statement} * objects, and affect when a statement is applied. For example, a statement * that allows access to an Amazon SQS queue could use a condition to only apply * the effect of that statement for requests that are made before a certain * date, or that originate from a range of IP addresses. * <p> * Multiple conditions can be included in a single statement, and all conditions * must evaluate to true in order for the statement to take effect. * <p> * The set of conditions is D in the statement * "A has permission to do B to C where D applies." * <p> * A condition is composed of three parts: * <ul> * <li><b>Condition Key</b> - The condition key declares which value of a * request to pull in and compare against when a policy is evaluated by AWS. For * example, using {@link software.amazon.awssdk.core.auth.policy.conditions.ConditionFactory#SOURCE_IP_CONDITION_KEY} will cause * AWS to pull in the current request's source IP as the first value to compare * against every time your policy is evaluated. * <li><b>Comparison Type</b> - Most condition types allow several ways to * compare the value obtained from the condition key and the comparison value. * <li><b>Comparison Value</b> - This is a static value used as the second value * in the comparison when your policy is evaluated. Depending on the comparison * type, this value can optionally use wildcards. See the documentation for * individual comparison types for more information. * </ul> * <p> * There are many expressive conditions available in the * <code>software.amazon.awssdk.core.auth.policy.conditions</code> package to use in access * control policy statements. * <p> * This class is not intended to be directly subclassed by users, instead users * should use the many available conditions and condition factories in the * software.amazon.awssdk.core.auth.policy.conditions package. */ //TODO Remove or clean this up along with its subclasses. public class Condition { protected String type; protected String conditionKey; protected List<String> values; /** * Returns the type of this condition. * * @return The type of this condition. */ public String getType() { return type; } /** * Sets the type of this condition. * * @param type * The type of this condition. */ public void setType(String type) { this.type = type; } /** * Returns the name of the condition key involved in this condition. * Condition keys are predefined values supported by AWS that provide input * to a condition's evaluation, such as the current time, or the IP address * of the incoming request. * <p> * Your policy is evaluated for each incoming request, and condition keys * specify what information to pull out of those incoming requests and plug * into the conditions in your policy. * * @return The name of the condition key involved in this condition. */ public String getConditionKey() { return conditionKey; } /** * Sets the name of the condition key involved in this condition. * Condition keys are predefined values supported by AWS that provide * input to a condition's evaluation, such as the current time, or the IP * address of the incoming request. * <p> * Your policy is evaluated for each incoming request, and condition keys * specify what information to pull out of those incoming requests and plug * into the conditions in your policy. * * @param conditionKey * The name of the condition key involved in this condition. */ public void setConditionKey(String conditionKey) { this.conditionKey = conditionKey; } /** * Returns the values specified for this access control policy condition. * For example, in a condition that compares the incoming IP address of a * request to a specified range of IP addresses, the range of IP addresses * is the single value in the condition. * <p> * Most conditions accept only one value, but multiple values are possible. * * @return The values specified for this access control policy condition. */ public List<String> getValues() { return values; } /** * Sets the values specified for this access control policy condition. For * example, in a condition that compares the incoming IP address of a * request to a specified range of IP addresses, the range of IP addresses * is the single value in the condition. * <p> * Most conditions accept only one value, but multiple values are possible. * * @param values * The values specified for this access control policy condition. */ public void setValues(List<String> values) { this.values = values; } /** * Fluent version of {@link Condition#setType(String)} * @return this */ public Condition withType(String type) { setType(type); return this; } /** * Fluent version of {@link Condition#setConditionKey(String)} * @return this */ public Condition withConditionKey(String key) { setConditionKey(key); return this; } /** * Fluent version of {@link Condition#setValues(List)} * @return this */ public Condition withValues(String... values) { setValues(Arrays.asList(values)); return this; } /** * Fluent version of {@link Condition#setValues(List)} * @return this */ public Condition withValues(List<String> values) { setValues(values); return this; } }
2,707
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Principal.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.core.auth.policy; /** * A principal is an AWS account or AWS web service, which is being allowed or denied access to a * resource through an access control policy. The principal is a property of the * {@link Statement} object, not directly the {@link Policy} object. * <p> * The principal is A in the statement * "A has permission to do B to C where D applies." * <p> * In an access control policy statement, you can set the principal to all * authenticated AWS users through the {@link Principal#ALL_USERS} member. This * is useful when you don't want to restrict access based on the identity of the * requester, but instead on other identifying characteristics such as the * requester's IP address. */ public class Principal { /** * Principal instance that includes all users, including anonymous users. * <p> * This is useful when you don't want to restrict access based on the * identity of the requester, but instead on other identifying * characteristics such as the requester's IP address. */ public static final Principal ALL_USERS = new Principal("AWS", "*"); /** * Principal instance that includes all AWS web services. */ public static final Principal ALL_SERVICES = new Principal("Service", "*"); /** * Principal instance that includes all the web identity providers. */ public static final Principal ALL_WEB_PROVIDERS = new Principal("Federated", "*"); /** * Principal instance that includes all the AWS accounts, AWS web services and web identity providers. */ public static final Principal ALL = new Principal("*", "*"); private final String id; private final String provider; /** * Constructs a new principal with the specified AWS web service which * is being allowed or denied access to a resource through an access control * policy. * * @param service * An AWS service. */ public Principal(Service service) { if (service == null) { throw new IllegalArgumentException("Null AWS service name specified"); } id = service.getServiceId(); provider = "Service"; } /** * Constructs a new principal with the specified AWS account ID. This method * automatically strips hyphen characters found in the account Id. * * @param accountId * An AWS account ID. */ public Principal(String accountId) { this("AWS", accountId); if (accountId == null) { throw new IllegalArgumentException("Null AWS account ID specified"); } } /** * Constructs a new principal with the specified id and provider. This * method automatically strips hyphen characters found in the account ID if * the provider is "AWS". */ public Principal(String provider, String id) { this(provider, id, provider.equals("AWS")); } /** * Constructs a new principal with the specified id and provider. This * method optionally strips hyphen characters found in the account Id. */ public Principal(String provider, String id, boolean stripHyphen) { this.provider = provider; this.id = stripHyphen ? id.replace("-", "") : id; } /** * Constructs a new principal with the specified web identity provider. * * @param webIdentityProvider * An web identity provider. */ public Principal(WebIdentityProvider webIdentityProvider) { if (webIdentityProvider == null) { throw new IllegalArgumentException("Null web identity provider specified"); } this.id = webIdentityProvider.getWebIdentityProvider(); provider = "Federated"; } /** * Returns the provider for this principal, which indicates in what group of * users this principal resides. * * @return The provider for this principal. */ public String getProvider() { return provider; } /** * Returns the unique ID for this principal. * * @return The unique ID for this principal. */ public String getId() { return id; } @Override public int hashCode() { int prime = 31; int hashCode = 1; hashCode = prime * hashCode + provider.hashCode(); hashCode = prime * hashCode + id.hashCode(); return hashCode; } @Override public boolean equals(Object principal) { if (this == principal) { return true; } if (principal == null) { return false; } if (principal instanceof Principal == false) { return false; } Principal other = (Principal) principal; if (this.getProvider().equals(other.getProvider()) && this.getId().equals(other.getId())) { return true; } return false; } /** * The services who have the right to do the assume the role * action. The AssumeRole action returns a set of temporary security * credentials that you can use to access resources that are defined in the * role's policy. The returned credentials consist of an Access Key ID, a * Secret Access Key, and a security token. */ public enum Service { AWSDataPipeline("datapipeline.amazonaws.com"), AmazonElasticTranscoder("elastictranscoder.amazonaws.com"), AmazonEC2("ec2.amazonaws.com"), AWSOpsWorks("opsworks.amazonaws.com"), AWSCloudHSM("cloudhsm.amazonaws.com"), AllServices("*"); private String serviceId; /** * The service which has the right to assume the role. */ Service(String serviceId) { this.serviceId = serviceId; } /** * Construct the Services object from a string representing the service id. */ public static Service fromString(String serviceId) { if (serviceId != null) { for (Service s : Service.values()) { if (s.getServiceId().equalsIgnoreCase(serviceId)) { return s; } } } return null; } public String getServiceId() { return serviceId; } } /** * Web identity providers, such as Login with Amazon, Facebook, or Google. */ public enum WebIdentityProvider { Facebook("graph.facebook.com"), Google("accounts.google.com"), Amazon("www.amazon.com"), AllProviders("*"); private String webIdentityProvider; /** * The web identity provider which has the right to assume the role. */ WebIdentityProvider(String webIdentityProvider) { this.webIdentityProvider = webIdentityProvider; } /** * Construct the Services object from a string representing web identity provider. */ public static WebIdentityProvider fromString(String webIdentityProvider) { if (webIdentityProvider != null) { for (WebIdentityProvider provider : WebIdentityProvider.values()) { if (provider.getWebIdentityProvider().equalsIgnoreCase(webIdentityProvider)) { return provider; } } } return null; } public String getWebIdentityProvider() { return webIdentityProvider; } } }
2,708
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Action.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.core.auth.policy; /** * An access control policy action identifies a specific action in a service * that can be performed on a resource. For example, sending a message to a * queue. * <p> * Actions allow you to limit what your access control policy statement affects. * For example, you could create a policy statement that enables a certain group * of users to send messages to your queue, but not allow them to perform any * other actions on your queue. * <p> * The action is B in the statement * "A has permission to do B to C where D applies." * <p> * Free form access control policy actions may include a wildcard (*) to match * multiple actions. */ public class Action { private final String name; public Action(String name) { this.name = name; } /** * Returns the name of this action. For example, 'sqs:SendMessage' is the * name corresponding to the SQS action that enables users to send a message * to an SQS queue. * * @return The name of this action. */ public String getActionName() { return name; } }
2,709
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/Policy.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.core.auth.policy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import software.amazon.awssdk.core.auth.policy.internal.JsonPolicyReader; import software.amazon.awssdk.core.auth.policy.internal.JsonPolicyWriter; /** * An AWS access control policy is a object that acts as a container for one or * more statements, which specify fine grained rules for allowing or denying * various types of actions from being performed on your AWS resources. * <p> * By default, all requests to use your resource coming from anyone but you are * denied. Access control polices can override that by allowing different types * of access to your resources, or by explicitly denying different types of * access. * <p> * Each statement in an AWS access control policy takes the form: * "A has permission to do B to C where D applies". * <ul> * <li>A is the <b>principal</b> - the AWS account that is making a request to * access or modify one of your AWS resources. * <li>B is the <b>action</b> - the way in which your AWS resource is being accessed or modified, such * as sending a message to an Amazon SQS queue, or storing an object in an Amazon S3 bucket. * <li>C is the <b>resource</b> - your AWS entity that the principal wants to access, such * as an Amazon SQS queue, or an object stored in Amazon S3. * <li>D is the set of <b>conditions</b> - optional constraints that specify when to allow or deny * access for the principal to access your resource. Many expressive conditions are available, * some specific to each service. For example you can use date conditions to allow access to * your resources only after or before a specific time. * </ul> * <p> * Note that an AWS access control policy should not be confused with the * similarly named "POST form policy" concept used in Amazon S3. */ public class Policy { /** The default policy version. */ private static final String DEFAULT_POLICY_VERSION = "2012-10-17"; private String id; private String version = DEFAULT_POLICY_VERSION; private List<Statement> statements = new ArrayList<>(); /** * Constructs an empty AWS access control policy ready to be populated with * statements. */ public Policy() { } /** * Constructs a new AWS access control policy with the specified policy ID. * The policy ID is a user specified string that serves to help developers * keep track of multiple polices. Policy IDs are often used as a human * readable name for a policy. * * @param id * The policy ID for the new policy object. Policy IDs serve to * help developers keep track of multiple policies, and are often * used to give the policy a meaningful, human readable name. */ public Policy(String id) { this.id = id; } /** * Constructs a new AWS access control policy with the specified policy ID * and collection of statements. The policy ID is a user specified string * that serves to help developers keep track of multiple polices. Policy IDs * are often used as a human readable name for a policy. * <p> * Any statements that don't have a statement ID yet will automatically be * assigned a unique ID within this policy. * * @param id * The policy ID for the new policy object. Policy IDs serve to * help developers keep track of multiple policies, and are often * used to give the policy a meaningful, human readable name. * @param statements * The statements to include in the new policy. */ public Policy(String id, Collection<Statement> statements) { this(id); setStatements(statements); } /** * Returns an AWS access control policy object generated from JSON string. * * @param jsonString * The JSON string representation of this AWS access control policy. * * @return An AWS access control policy object. * * @throws IllegalArgumentException * If the specified JSON string is null or invalid and cannot be * converted to an AWS policy object. */ public static Policy fromJson(String jsonString) { return new JsonPolicyReader().createPolicyFromJsonString(jsonString); } /** * Returns the policy ID for this policy. Policy IDs serve to help * developers keep track of multiple policies, and are often used as human * readable name for a policy. * * @return The policy ID for this policy. */ public String getId() { return id; } /** * Sets the policy ID for this policy. Policy IDs serve to help developers * keep track of multiple policies, and are often used as human readable * name for a policy. * * @param id * The policy ID for this policy. */ public void setId(String id) { this.id = id; } /** * Sets the policy ID for this policy and returns the updated policy so that * multiple calls can be chained together. * <p> * Policy IDs serve to help developers keep track of multiple policies, and * are often used as human readable name for a policy. * * @param id * The policy ID for this policy. * * @return The updated Policy object so that additional calls can be chained * together. */ public Policy withId(String id) { setId(id); return this; } /** * Returns the version of this AWS policy. * * @return The version of this AWS policy. */ public String getVersion() { return version; } /** * Returns the collection of statements contained by this policy. Individual * statements in a policy are what specify the rules that enable or disable * access to your AWS resources. * * @return The collection of statements contained by this policy. */ public Collection<Statement> getStatements() { return statements; } /** * Sets the collection of statements contained by this policy. Individual * statements in a policy are what specify the rules that enable or disable * access to your AWS resources. * <p> * Any statements that don't have a statement ID yet will automatically be * assigned a unique ID within this policy. * * @param statements * The collection of statements included in this policy. */ public void setStatements(Collection<Statement> statements) { this.statements = new ArrayList<>(statements); assignUniqueStatementIds(); } /** * Sets the collection of statements contained by this policy and returns * this policy object so that additional method calls can be chained * together. * <p> * Individual statements in a policy are what specify the rules that enable * or disable access to your AWS resources. * <p> * Any statements that don't have a statement ID yet will automatically be * assigned a unique ID within this policy. * * @param statements * The collection of statements included in this policy. * * @return The updated policy object, so that additional method calls can be * chained together. */ public Policy withStatements(Statement... statements) { setStatements(Arrays.asList(statements)); return this; } /** * Returns a JSON string representation of this AWS access control policy, * suitable to be sent to an AWS service as part of a request to set an * access control policy. * * @return A JSON string representation of this AWS access control policy. */ public String toJson() { return new JsonPolicyWriter().writePolicyToString(this); } private void assignUniqueStatementIds() { Set<String> usedStatementIds = new HashSet<>(); for (Statement statement : statements) { if (statement.getId() != null) { usedStatementIds.add(statement.getId()); } } int counter = 0; for (Statement statement : statements) { if (statement.getId() != null) { continue; } while (usedStatementIds.contains(Integer.toString(++counter))) { ; } statement.setId(Integer.toString(counter)); } } }
2,710
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/internal/JsonPolicyReader.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.core.auth.policy.internal; import com.fasterxml.jackson.databind.JsonNode; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import software.amazon.awssdk.core.auth.policy.Action; import software.amazon.awssdk.core.auth.policy.Condition; import software.amazon.awssdk.core.auth.policy.Policy; import software.amazon.awssdk.core.auth.policy.Principal; import software.amazon.awssdk.core.auth.policy.Resource; import software.amazon.awssdk.core.auth.policy.Statement; /** * Generate an AWS policy object by parsing the given JSON string. */ public class JsonPolicyReader { private static final String PRINCIPAL_SCHEMA_USER = "AWS"; private static final String PRINCIPAL_SCHEMA_SERVICE = "Service"; private static final String PRINCIPAL_SCHEMA_FEDERATED = "Federated"; /** * Converts the specified JSON string to an AWS policy object. * * For more information see, @see * http://docs.aws.amazon.com/AWSSdkDocsJava/latest * /DeveloperGuide/java-dg-access-control.html * * @param jsonString * the specified JSON string representation of this AWS access * control policy. * * @return An AWS policy object. * * @throws IllegalArgumentException * If the specified JSON string is null or invalid and cannot be * converted to an AWS policy object. */ public Policy createPolicyFromJsonString(String jsonString) { if (jsonString == null) { throw new IllegalArgumentException("JSON string cannot be null"); } JsonNode policyNode; JsonNode idNode; JsonNode statementNodes; Policy policy = new Policy(); List<Statement> statements = new LinkedList<>(); try { policyNode = JacksonUtils.jsonNodeOf(jsonString); idNode = policyNode.get(JsonDocumentField.POLICY_ID); if (isNotNull(idNode)) { policy.setId(idNode.asText()); } statementNodes = policyNode.get(JsonDocumentField.STATEMENT); if (isNotNull(statementNodes)) { for (JsonNode node : statementNodes) { statements.add(statementOf(node)); } } } catch (Exception e) { String message = "Unable to generate policy object fron JSON string " + e.getMessage(); throw new IllegalArgumentException(message, e); } policy.setStatements(statements); return policy; } /** * Creates a <code>Statement</code> instance from the statement node. * * A statement consists of an Effect, id (optional), principal, action, resource, * and conditions. * <p> * principal is the AWS account that is making a request to access or modify one of your AWS resources. * <p> * action is the way in which your AWS resource is being accessed or modified, such as sending a message to an Amazon * SQS queue, or storing an object in an Amazon S3 bucket. * <p> * resource is the AWS entity that the principal wants to access, such as an Amazon SQS queue, or an object stored in * Amazon S3. * <p> * conditions are the optional constraints that specify when to allow or deny access for the principal to access your * resource. Many expressive conditions are available, some specific to each service. For example, you can use date * conditions to allow access to your resources only after or before a specific time. * * @param jStatement * JsonNode representing the statement. * @return a reference to the statement instance created. */ private Statement statementOf(JsonNode jStatement) { JsonNode effectNode = jStatement.get(JsonDocumentField.STATEMENT_EFFECT); Statement.Effect effect = isNotNull(effectNode) ? Statement.Effect.valueOf(effectNode.asText()) : Statement.Effect.Deny; Statement statement = new Statement(effect); JsonNode id = jStatement.get(JsonDocumentField.STATEMENT_ID); if (isNotNull(id)) { statement.setId(id.asText()); } JsonNode actionNodes = jStatement.get(JsonDocumentField.ACTION); if (isNotNull(actionNodes)) { statement.setActions(actionsOf(actionNodes)); } JsonNode resourceNodes = jStatement.get(JsonDocumentField.RESOURCE); if (isNotNull(resourceNodes)) { statement.setResources(resourcesOf(resourceNodes)); } JsonNode conditionNodes = jStatement.get(JsonDocumentField.CONDITION); if (isNotNull(conditionNodes)) { statement.setConditions(conditionsOf(conditionNodes)); } JsonNode principalNodes = jStatement.get(JsonDocumentField.PRINCIPAL); if (isNotNull(principalNodes)) { statement.setPrincipals(principalOf(principalNodes)); } return statement; } /** * Generates a list of actions from the Action Json Node. * * @param actionNodes * the action Json node to be parsed. * @return the list of actions. */ private List<Action> actionsOf(JsonNode actionNodes) { List<Action> actions = new LinkedList<>(); if (actionNodes.isArray()) { for (JsonNode action : actionNodes) { actions.add(new Action(action.asText())); } } else { actions.add(new Action(actionNodes.asText())); } return actions; } /** * Generates a list of resources from the Resource Json Node. * * @param resourceNodes * the resource Json node to be parsed. * @return the list of resources. */ private List<Resource> resourcesOf(JsonNode resourceNodes) { List<Resource> resources = new LinkedList<>(); if (resourceNodes.isArray()) { for (JsonNode resource : resourceNodes) { resources.add(new Resource(resource.asText())); } } else { resources.add(new Resource(resourceNodes.asText())); } return resources; } /** * Generates a list of principals from the Principal Json Node * * @param principalNodes * the principal Json to be parsed * @return a list of principals */ private List<Principal> principalOf(JsonNode principalNodes) { List<Principal> principals = new LinkedList<>(); if (principalNodes.asText().equals("*")) { principals.add(Principal.ALL); return principals; } Iterator<Map.Entry<String, JsonNode>> mapOfPrincipals = principalNodes .fields(); String schema; JsonNode principalNode; Entry<String, JsonNode> principal; Iterator<JsonNode> elements; while (mapOfPrincipals.hasNext()) { principal = mapOfPrincipals.next(); schema = principal.getKey(); principalNode = principal.getValue(); if (principalNode.isArray()) { elements = principalNode.elements(); while (elements.hasNext()) { principals.add(createPrincipal(schema, elements.next())); } } else { principals.add(createPrincipal(schema, principalNode)); } } return principals; } /** * Creates a new principal instance for the given schema and the Json node. * * @param schema * the schema for the principal instance being created. * @param principalNode * the node indicating the AWS account that is making the * request. * @return a principal instance. */ private Principal createPrincipal(String schema, JsonNode principalNode) { if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_USER)) { return new Principal(principalNode.asText()); } else if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_SERVICE)) { return new Principal(schema, principalNode.asText()); } else if (schema.equalsIgnoreCase(PRINCIPAL_SCHEMA_FEDERATED)) { if (Principal.WebIdentityProvider.fromString(principalNode.asText()) != null) { return new Principal( Principal.WebIdentityProvider.fromString(principalNode.asText())); } else { return new Principal(PRINCIPAL_SCHEMA_FEDERATED, principalNode.asText()); } } throw new IllegalArgumentException("Schema " + schema + " is not a valid value for the principal."); } /** * Generates a list of condition from the Json node. * * @param conditionNodes * the condition Json node to be parsed. * @return the list of conditions. */ private List<Condition> conditionsOf(JsonNode conditionNodes) { List<Condition> conditionList = new LinkedList<>(); Iterator<Map.Entry<String, JsonNode>> mapOfConditions = conditionNodes .fields(); Entry<String, JsonNode> condition; while (mapOfConditions.hasNext()) { condition = mapOfConditions.next(); convertConditionRecord(conditionList, condition.getKey(), condition.getValue()); } return conditionList; } /** * Generates a condition instance for each condition type under the * Condition Json node. * * @param conditions * the complete list of conditions * @param conditionType * the condition type for the condition being created. * @param conditionNode * each condition node to be parsed. */ private void convertConditionRecord(List<Condition> conditions, String conditionType, JsonNode conditionNode) { Iterator<Map.Entry<String, JsonNode>> mapOfFields = conditionNode .fields(); List<String> values; Entry<String, JsonNode> field; JsonNode fieldValue; Iterator<JsonNode> elements; while (mapOfFields.hasNext()) { values = new LinkedList<>(); field = mapOfFields.next(); fieldValue = field.getValue(); if (fieldValue.isArray()) { elements = fieldValue.elements(); while (elements.hasNext()) { values.add(elements.next().asText()); } } else { values.add(fieldValue.asText()); } conditions.add(new Condition().withType(conditionType) .withConditionKey(field.getKey()).withValues(values)); } } /** * Checks if the given object is not null. * * @param object * the object compared to null. * @return true if the object is not null else false */ private boolean isNotNull(Object object) { return null != object; } }
2,711
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/internal/JacksonUtils.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.core.auth.policy.internal; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.Writer; public final class JacksonUtils { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static { OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true); OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private JacksonUtils() { } /** * Returns the deserialized object from the given json string and target * class; or null if the given json string is null. */ public static <T> T fromJsonString(String json, Class<T> clazz) { if (json == null) { return null; } return invokeSafely(() -> OBJECT_MAPPER.readValue(json, clazz)); } public static JsonNode jsonNodeOf(String json) { return fromJsonString(json, JsonNode.class); } public static JsonGenerator jsonGeneratorOf(Writer writer) throws IOException { return new JsonFactory().createGenerator(writer); } }
2,712
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/internal/JsonPolicyWriter.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.core.auth.policy.internal; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import com.fasterxml.jackson.core.JsonGenerator; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.auth.policy.Action; import software.amazon.awssdk.core.auth.policy.Condition; import software.amazon.awssdk.core.auth.policy.Policy; import software.amazon.awssdk.core.auth.policy.Principal; import software.amazon.awssdk.core.auth.policy.Resource; import software.amazon.awssdk.core.auth.policy.Statement; import software.amazon.awssdk.utils.IoUtils; /** * Serializes an AWS policy object to a JSON string, suitable for sending to an * AWS service. */ public class JsonPolicyWriter { private static final Logger log = LoggerFactory.getLogger(JsonPolicyWriter.class); /** The JSON Generator to generator a JSON string.*/ private JsonGenerator generator = null; /** The output writer to which the JSON String is written.*/ private Writer writer; /** * Constructs a new instance of JSONPolicyWriter. */ public JsonPolicyWriter() { writer = new StringWriter(); generator = invokeSafely(() -> JacksonUtils.jsonGeneratorOf(writer)); } /** * Converts the specified AWS policy object to a JSON string, suitable for * passing to an AWS service. * * @param policy * The AWS policy object to convert to a JSON string. * * @return The JSON string representation of the specified policy object. * * @throws IllegalArgumentException * If the specified policy is null or invalid and cannot be * serialized to a JSON string. */ public String writePolicyToString(Policy policy) { if (!isNotNull(policy)) { throw new IllegalArgumentException("Policy cannot be null"); } try { return jsonStringOf(policy); } catch (Exception e) { String message = "Unable to serialize policy to JSON string: " + e.getMessage(); throw new IllegalArgumentException(message, e); } finally { IoUtils.closeQuietly(writer, log); } } /** * Converts the given <code>Policy</code> into a JSON String. * * @param policy * the policy to be converted. * @return a JSON String of the specified policy object. */ private String jsonStringOf(Policy policy) throws IOException { generator.writeStartObject(); writeJsonKeyValue(JsonDocumentField.VERSION, policy.getVersion()); if (isNotNull(policy.getId())) { writeJsonKeyValue(JsonDocumentField.POLICY_ID, policy.getId()); } writeJsonArrayStart(JsonDocumentField.STATEMENT); for (Statement statement : policy.getStatements()) { generator.writeStartObject(); if (isNotNull(statement.getId())) { writeJsonKeyValue(JsonDocumentField.STATEMENT_ID, statement.getId()); } writeJsonKeyValue(JsonDocumentField.STATEMENT_EFFECT, statement .getEffect().toString()); List<Principal> principals = statement.getPrincipals(); if (isNotNull(principals) && !principals.isEmpty()) { writePrincipals(principals); } List<Action> actions = statement.getActions(); if (isNotNull(actions) && !actions.isEmpty()) { writeActions(actions); } List<Resource> resources = statement.getResources(); if (isNotNull(resources) && !resources.isEmpty()) { writeResources(resources); } List<Condition> conditions = statement.getConditions(); if (isNotNull(conditions) && !conditions.isEmpty()) { writeConditions(conditions); } generator.writeEndObject(); } writeJsonArrayEnd(); generator.writeEndObject(); generator.flush(); return writer.toString(); } /** * Writes the list of conditions to the JSONGenerator. * * @param conditions * the conditions to be written. */ private void writeConditions(List<Condition> conditions) throws IOException { Map<String, ConditionsByKey> conditionsByType = groupConditionsByTypeAndKey(conditions); writeJsonObjectStart(JsonDocumentField.CONDITION); ConditionsByKey conditionsByKey; for (Map.Entry<String, ConditionsByKey> entry : conditionsByType .entrySet()) { conditionsByKey = conditionsByType.get(entry.getKey()); writeJsonObjectStart(entry.getKey()); for (String key : conditionsByKey.keySet()) { writeJsonArray(key, conditionsByKey.getConditionsByKey(key)); } writeJsonObjectEnd(); } writeJsonObjectEnd(); } /** * Writes the list of <code>Resource</code>s to the JSONGenerator. * * @param resources * the list of resources to be written. */ private void writeResources(List<Resource> resources) throws IOException { List<String> resourceStrings = new ArrayList<>(); for (Resource resource : resources) { resourceStrings.add(resource.getId()); } writeJsonArray(JsonDocumentField.RESOURCE, resourceStrings); } /** * Writes the list of <code>Action</code>s to the JSONGenerator. * * @param actions * the list of the actions to be written. */ private void writeActions(List<Action> actions) throws IOException { List<String> actionStrings = new ArrayList<>(); for (Action action : actions) { actionStrings.add(action.getActionName()); } writeJsonArray(JsonDocumentField.ACTION, actionStrings); } /** * Writes the list of <code>Principal</code>s to the JSONGenerator. * * @param principals * the list of principals to be written. */ private void writePrincipals(List<Principal> principals) throws IOException { if (principals.size() == 1 && principals.get(0).equals(Principal.ALL)) { writeJsonKeyValue(JsonDocumentField.PRINCIPAL, Principal.ALL.getId()); } else { writeJsonObjectStart(JsonDocumentField.PRINCIPAL); Map<String, List<String>> principalsByScheme = groupPrincipalByScheme(principals); List<String> principalValues; for (Map.Entry<String, List<String>> entry : principalsByScheme.entrySet()) { principalValues = principalsByScheme.get(entry.getKey()); if (principalValues.size() == 1) { writeJsonKeyValue(entry.getKey(), principalValues.get(0)); } else { writeJsonArray(entry.getKey(), principalValues); } } writeJsonObjectEnd(); } } /** * Groups the list of <code>Principal</code>s by the Scheme. * * @param principals * the list of <code>Principal</code>s * @return a map grouped by scheme of the principal. */ private Map<String, List<String>> groupPrincipalByScheme( List<Principal> principals) { Map<String, List<String>> principalsByScheme = new LinkedHashMap<>(); String provider; List<String> principalValues; for (Principal principal : principals) { provider = principal.getProvider(); if (!principalsByScheme.containsKey(provider)) { principalsByScheme.put(provider, new ArrayList<>()); } principalValues = principalsByScheme.get(provider); principalValues.add(principal.getId()); } return principalsByScheme; } /** * Groups the list of <code>Condition</code>s by the condition type and * condition key. * * @param conditions * the list of conditions to be grouped * @return a map of conditions grouped by type and then key. */ private Map<String, ConditionsByKey> groupConditionsByTypeAndKey( List<Condition> conditions) { Map<String, ConditionsByKey> conditionsByType = new LinkedHashMap<>(); String type; String key; ConditionsByKey conditionsByKey; for (Condition condition : conditions) { type = condition.getType(); key = condition.getConditionKey(); if (!(conditionsByType.containsKey(type))) { conditionsByType.put(type, new ConditionsByKey()); } conditionsByKey = conditionsByType.get(type); conditionsByKey.addValuesToKey(key, condition.getValues()); } return conditionsByType; } /** * Writes an array along with its values to the JSONGenerator. * * @param arrayName * name of the JSON array. * @param values * values of the JSON array. */ private void writeJsonArray(String arrayName, List<String> values) throws IOException { writeJsonArrayStart(arrayName); for (String value : values) { generator.writeString(value); } writeJsonArrayEnd(); } /** * Writes the Start of Object String to the JSONGenerator along with Object * Name. * * @param fieldName * name of the JSON Object. */ private void writeJsonObjectStart(String fieldName) throws IOException { generator.writeObjectFieldStart(fieldName); } /** * Writes the End of Object String to the JSONGenerator. */ private void writeJsonObjectEnd() throws IOException { generator.writeEndObject(); } /** * Writes the Start of Array String to the JSONGenerator along with Array * Name. * * @param fieldName * name of the JSON array */ private void writeJsonArrayStart(String fieldName) throws IOException { generator.writeArrayFieldStart(fieldName); } /** * Writes the End of Array String to the JSONGenerator. */ private void writeJsonArrayEnd() throws IOException { generator.writeEndArray(); } /** * Writes the given field and the value to the JsonGenerator * * @param fieldName * the JSON field name * @param value * value for the field */ private void writeJsonKeyValue(String fieldName, String value) throws IOException { generator.writeStringField(fieldName, value); } /** * Checks if the given object is not null. * * @param object * the object compared to null. * @return true if the object is not null else false */ private boolean isNotNull(Object object) { return null != object; } /** * Inner class to hold condition values for each key under a condition type. */ static class ConditionsByKey { private Map<String, List<String>> conditionsByKey; ConditionsByKey() { conditionsByKey = new LinkedHashMap<>(); } public Map<String, List<String>> getConditionsByKey() { return conditionsByKey; } public void setConditionsByKey(Map<String, List<String>> conditionsByKey) { this.conditionsByKey = conditionsByKey; } public boolean containsKey(String key) { return conditionsByKey.containsKey(key); } public List<String> getConditionsByKey(String key) { return conditionsByKey.get(key); } public Set<String> keySet() { return conditionsByKey.keySet(); } public void addValuesToKey(String key, List<String> values) { List<String> conditionValues = getConditionsByKey(key); if (conditionValues == null) { conditionsByKey.put(key, new ArrayList<>(values)); } else { conditionValues.addAll(values); } } } }
2,713
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/internal/JsonDocumentField.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.core.auth.policy.internal; public final class JsonDocumentField { public static final String VERSION = "Version"; public static final String POLICY_ID = "Id"; public static final String STATEMENT = "Statement"; public static final String STATEMENT_EFFECT = "Effect"; public static final String EFFECT_VALUE_ALLOW = "Allow"; public static final String STATEMENT_ID = "Sid"; public static final String PRINCIPAL = "Principal"; public static final String ACTION = "Action"; public static final String RESOURCE = "Resource"; public static final String CONDITION = "Condition"; private JsonDocumentField() { } }
2,714
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/conditions/StringCondition.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.core.auth.policy.conditions; import java.util.Arrays; import software.amazon.awssdk.core.auth.policy.Condition; /** * String conditions let you constrain AWS access control policy statements * using string matching rules. */ public class StringCondition extends Condition { /** * Constructs a new access control policy condition that compares two * strings. * * @param type * The type of comparison to perform. * @param key * The access policy condition key specifying where to get the * first string for the comparison (ex: aws:UserAgent). See * {@link ConditionFactory} for a list of the condition keys * available for all services. * @param value * The second string to compare against. When using * {@link StringComparisonType#StringLike} or * {@link StringComparisonType#StringNotLike} this may contain * the multi-character wildcard (*) or the single-character * wildcard (?). */ public StringCondition(StringComparisonType type, String key, String value) { super.type = type.toString(); super.conditionKey = key; super.values = Arrays.asList(value); } /** * Enumeration of the supported ways a string comparison can be evaluated. */ public enum StringComparisonType { /** Case-sensitive exact string matching. */ StringEquals, /** Case-insensitive string matching. */ StringEqualsIgnoreCase, /** * Loose case-insensitive matching. The values can include a * multi-character match wildcard (*) or a single-character match * wildcard (?) anywhere in the string. */ StringLike, /** * Negated form of {@link #StringEquals} */ StringNotEquals, /** * Negated form of {@link #StringEqualsIgnoreCase} */ StringNotEqualsIgnoreCase, /** * Negated form of {@link #StringLike} */ StringNotLike; } }
2,715
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/conditions/ConditionFactory.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.core.auth.policy.conditions; import software.amazon.awssdk.core.auth.policy.Condition; import software.amazon.awssdk.core.auth.policy.conditions.ArnCondition.ArnComparisonType; /** * Factory for creating common AWS access control policy conditions. These * conditions are common for AWS services and can be expected to work across any * service that supports AWS access control policies. */ public final class ConditionFactory { /** * Condition key for the current time. * <p> * This condition key should only be used with {@link DateCondition} * objects. */ public static final String CURRENT_TIME_CONDITION_KEY = "aws:CurrentTime"; /** * Condition key for the source IP from which a request originates. * <p> * This condition key should only be used with {@link IpAddressCondition} * objects. */ public static final String SOURCE_IP_CONDITION_KEY = "aws:SourceIp"; /** * Condition key for the Amazon Resource Name (ARN) of the source specified * in a request. The source ARN indicates which resource is affecting the * resource listed in your policy. For example, an SNS topic is the source * ARN when publishing messages from the topic to an SQS queue. * <p> * This condition key should only be used with {@link ArnCondition} objects. */ public static final String SOURCE_ARN_CONDITION_KEY = "aws:SourceArn"; private ConditionFactory() { } /** * Constructs a new access policy condition that compares the Amazon * Resource Name (ARN) of the source of an AWS resource that is modifying * another AWS resource with the specified pattern. * <p> * For example, the source ARN could be an Amazon SNS topic ARN that is * sending messages to an Amazon SQS queue. In that case, the SNS topic ARN * would be compared the ARN pattern specified here. * <p> * The endpoint pattern may optionally contain the multi-character wildcard * (*) or the single-character wildcard (?). Each of the six colon-delimited * components of the ARN is checked separately and each can include a * wildcard. * * <pre class="brush: java"> * Policy policy = new Policy(&quot;MyQueuePolicy&quot;); * policy.withStatements(new Statement(&quot;AllowSNSMessages&quot;, Effect.Allow) * .withPrincipals(new Principal(&quot;*&quot;)).withActions(SQSActions.SendMessage) * .withResources(new Resource(myQueueArn)) * .withConditions(ConditionFactory.newSourceArnCondition(myTopicArn))); * </pre> * * @param arnPattern * The ARN pattern against which the source ARN will be compared. * Each of the six colon-delimited components of the ARN is * checked separately and each can include a wildcard. * * @return A new access control policy condition that compares the ARN of * the source specified in an incoming request with the ARN pattern * specified here. */ public static Condition newSourceArnCondition(String arnPattern) { return new ArnCondition(ArnComparisonType.ArnLike, SOURCE_ARN_CONDITION_KEY, arnPattern); } }
2,716
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/conditions/IpAddressCondition.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.core.auth.policy.conditions; import java.util.Arrays; import software.amazon.awssdk.core.auth.policy.Condition; /** * AWS access control policy condition that allows an access control statement * to be conditionally applied based on the comparison of the the incoming * source IP address at the time of a request against a CIDR IP range. * <p> * For more information about CIDR IP ranges, see <a * href="http://en.wikipedia.org/wiki/CIDR_notation"> * http://en.wikipedia.org/wiki/CIDR_notation</a> */ public class IpAddressCondition extends Condition { /** * Constructs a new access policy condition that compares the source IP * address of the incoming request to an AWS service against the specified * CIDR range. The condition evaluates to true (meaning the policy statement * containing it will be applied) if the incoming source IP address is * within that range. * <p> * To achieve the opposite effect (i.e. cause the condition to evaluate to * true when the incoming source IP is <b>not</b> in the specified CIDR * range) use the alternate constructor form and specify * {@link IpAddressComparisonType#NotIpAddress} * <p> * For more information about CIDR IP ranges, see <a * href="http://en.wikipedia.org/wiki/CIDR_notation"> * http://en.wikipedia.org/wiki/CIDR_notation</a> * * @param ipAddressRange * The CIDR IP range involved in the policy condition. */ public IpAddressCondition(String ipAddressRange) { this(IpAddressComparisonType.IpAddress, ipAddressRange); } /** * Constructs a new access policy condition that compares the source IP * address of the incoming request to an AWS service against the specified * CIDR range. When the condition evaluates to true (i.e. when the incoming * source IP address is within the CIDR range or not) depends on the * specified {@link IpAddressComparisonType}. * <p> * For more information about CIDR IP ranges, see <a * href="http://en.wikipedia.org/wiki/CIDR_notation"> * http://en.wikipedia.org/wiki/CIDR_notation</a> * * @param type * The type of comparison to to perform. * @param ipAddressRange * The CIDR IP range involved in the policy condition. */ public IpAddressCondition(IpAddressComparisonType type, String ipAddressRange) { super.type = type.toString(); super.conditionKey = ConditionFactory.SOURCE_IP_CONDITION_KEY; super.values = Arrays.asList(ipAddressRange); } /** * Enumeration of the supported ways an IP address comparison can be evaluated. */ public enum IpAddressComparisonType { /** * Matches an IP address against a CIDR IP range, evaluating to true if * the IP address being tested is in the condition's specified CIDR IP * range. * <p> * For more information about CIDR IP ranges, see <a * href="http://en.wikipedia.org/wiki/CIDR_notation"> * http://en.wikipedia.org/wiki/CIDR_notation</a> */ IpAddress, /** * Negated form of {@link #IpAddress} */ NotIpAddress, } }
2,717
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/conditions/DateCondition.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.core.auth.policy.conditions; import static java.time.format.DateTimeFormatter.ISO_INSTANT; import java.util.Collections; import java.util.Date; import software.amazon.awssdk.core.auth.policy.Condition; /** * AWS access control policy condition that allows an access control statement * to be conditionally applied based on the comparison of the current time at * which a request is received, and a specific date. */ public class DateCondition extends Condition { /** * Constructs a new access policy condition that compares the current time * (on the AWS servers) to the specified date. * * @param type * The type of comparison to perform. For example, * {@link DateComparisonType#DateLessThan} will cause this policy * condition to evaluate to true if the current date is less than * the date specified in the second argument. * @param date * The date to compare against. */ public DateCondition(DateComparisonType type, Date date) { super.type = type.toString(); super.conditionKey = ConditionFactory.CURRENT_TIME_CONDITION_KEY; super.values = Collections.singletonList(ISO_INSTANT.format(date.toInstant())); } ; /** * Enumeration of the supported ways a date comparison can be evaluated. */ public enum DateComparisonType { DateEquals, DateGreaterThan, DateGreaterThanEquals, DateLessThan, DateLessThanEquals, DateNotEquals; } }
2,718
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/core/auth/policy/conditions/ArnCondition.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.core.auth.policy.conditions; import java.util.Arrays; import software.amazon.awssdk.core.auth.policy.Condition; /** * AWS access control policy condition that allows an access control statement * to be conditionally applied based on the comparison of an Amazon Resource * Name (ARN). * <p> * An Amazon Resource Name (ARN) takes the following format: * <b>{@code arn:aws:<vendor>:<region>:<namespace>:<relative-id>}</b> * <p> * <ul> * <li>vendor identifies the AWS product (e.g., sns)</li> * <li>region is the AWS Region the resource resides in (e.g., us-east-1), if * any * <li>namespace is the AWS account ID with no hyphens (e.g., 123456789012) * <li>relative-id is the service specific portion that identifies the specific * resource * </ul> * <p> * For example, an Amazon SQS queue might be addressed with the following ARN: * <b>arn:aws:sqs:us-east-1:987654321000:MyQueue</b> * <p> * <p> * Currently the only valid condition key to use in an ARN condition is * {@link ConditionFactory#SOURCE_ARN_CONDITION_KEY}, which indicates the * source resource that is modifying another resource, for example, an SNS topic * is the source ARN when publishing messages from the topic to an SQS queue. */ public class ArnCondition extends Condition { /** * Constructs a new access control policy condition that compares ARNs * (Amazon Resource Names). * * @param type * The type of comparison to perform. * @param key * The access policy condition key specifying where to get the * first ARN for the comparison (ex: * {@link ConditionFactory#SOURCE_ARN_CONDITION_KEY}). * @param value * The second ARN to compare against. When using * {@link ArnComparisonType#ArnLike} or * {@link ArnComparisonType#ArnNotLike} this may contain the * multi-character wildcard (*) or the single-character wildcard * (?). */ public ArnCondition(ArnComparisonType type, String key, String value) { super.type = type.toString(); super.conditionKey = key; super.values = Arrays.asList(value); } ; /** * Enumeration of the supported ways an ARN comparison can be evaluated. */ public enum ArnComparisonType { /** * Exact matching. */ ArnEquals, /** * Loose case-insensitive matching of the ARN. Each of the six * colon-delimited components of the ARN is checked separately and each * can include a multi-character match wildcard (*) or a * single-character match wildcard (?). */ ArnLike, /** * Negated form of {@link #ArnEquals} */ ArnNotEquals, /** * Negated form of {@link #ArnLike} */ ArnNotLike } }
2,719
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/Waiter.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.testutils; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletionException; import java.util.function.Predicate; import java.util.function.Supplier; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * This retries a particular function multiple times until it returns an expected result (or fails with an exception). Certain * expected exception types can be ignored. */ public final class Waiter<T> { private static final Logger log = Logger.loggerFor(Waiter.class); private final Supplier<T> thingToTry; private Predicate<T> whenToStop = t -> true; private Predicate<T> whenToFail = t -> false; private Set<Class<? extends Throwable>> whatExceptionsToStopOn = Collections.emptySet(); private Set<Class<? extends Throwable>> whatExceptionsToIgnore = Collections.emptySet(); /** * @see #run(Supplier) */ private Waiter(Supplier<T> thingToTry) { Validate.paramNotNull(thingToTry, "thingToTry"); this.thingToTry = thingToTry; } /** * Create a waiter that attempts executing the provided function until the condition set with {@link #until(Predicate)} is * met or until it throws an exception. Expected exception types can be ignored with {@link #ignoringException(Class[])}. */ public static <T> Waiter<T> run(Supplier<T> thingToTry) { return new Waiter<>(thingToTry); } /** * Define the condition on the response under which the thing we are trying is complete. * * If this isn't set, it will always be true. ie. if the function call succeeds, we stop waiting. */ public Waiter<T> until(Predicate<T> whenToStop) { this.whenToStop = whenToStop; return this; } /** * Define the condition on the response under which the thing we are trying has already failed and further * attempts are pointless. * * If this isn't set, it will always be false. */ public Waiter<T> failOn(Predicate<T> whenToFail) { this.whenToFail = whenToFail; return this; } /** * Define the condition on an exception thrown under which the thing we are trying is complete. * * If this isn't set, it will always be false. ie. never stop on any particular exception. */ @SafeVarargs public final Waiter<T> untilException(Class<? extends Throwable>... whenToStopOnException) { this.whatExceptionsToStopOn = new HashSet<>(Arrays.asList(whenToStopOnException)); return this; } /** * Define the exception types that should be ignored if the thing we are trying throws them. */ @SafeVarargs public final Waiter<T> ignoringException(Class<? extends Throwable>... whatToIgnore) { this.whatExceptionsToIgnore = new HashSet<>(Arrays.asList(whatToIgnore)); return this; } /** * Execute the function, returning true if the thing we're trying does not succeed after 30 seconds. */ public boolean orReturnFalse() { try { orFail(); return true; } catch (AssertionError e) { return false; } } /** * Execute the function, throwing an assertion error if the thing we're trying does not succeed after 30 seconds. */ public T orFail() { return orFailAfter(Duration.ofMinutes(1)); } /** * Execute the function, throwing an assertion error if the thing we're trying does not succeed after the provided duration. */ public T orFailAfter(Duration howLongToTry) { Validate.paramNotNull(howLongToTry, "howLongToTry"); Instant start = Instant.now(); int attempt = 0; while (Duration.between(start, Instant.now()).compareTo(howLongToTry) < 0) { ++attempt; try { if (attempt > 1) { wait(attempt); } T result = thingToTry.get(); if (whenToStop.test(result)) { log.info(() -> "Got expected response: " + result); return result; } else if (whenToFail.test(result)) { throw new AssertionError("Received a response that matched the failOn predicate: " + result); } int unsuccessfulAttempt = attempt; log.info(() -> "Attempt " + unsuccessfulAttempt + " failed predicate."); } catch (RuntimeException e) { Throwable t = e instanceof CompletionException ? e.getCause() : e; if (whatExceptionsToStopOn.contains(t.getClass())) { log.info(() -> "Got expected exception: " + t.getClass().getSimpleName()); return null; } if (whatExceptionsToIgnore.contains(t.getClass())) { int unsuccessfulAttempt = attempt; log.info(() -> "Attempt " + unsuccessfulAttempt + " failed with an expected exception (" + t.getClass() + ")"); } else { throw e; } } } throw new AssertionError("Condition was not met after " + attempt + " attempts (" + Duration.between(start, Instant.now()).getSeconds() + " seconds)"); } private void wait(int attempt) { int howLongToWaitMs = 250 << Math.min(attempt - 1, 4); // Max = 250 * 2^4 = 4_000. try { Thread.sleep(howLongToWaitMs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(e); } } }
2,720
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/RandomInputStream.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.testutils; import java.io.IOException; import java.io.InputStream; import java.util.Random; /** * Test utility InputStream implementation that generates random ASCII data when * read, up to the size specified when constructed. */ public class RandomInputStream extends InputStream { /** Shared Random number generator to generate data. */ private static final Random RANDOM = new Random(); /** The minimum ASCII code contained in the data in this stream. */ private static final int MIN_CHAR_CODE = 32; /** The maximum ASCII code contained in the data in this stream. */ private static final int MAX_CHAR_CODE = 125; /** The number of bytes of data remaining in this random stream. */ protected long remainingBytes; /** The requested amount of data contained in this random stream. */ protected final long lengthInBytes; /** Flag controlling whether binary or character data is used. */ private final boolean binaryData; /** * Constructs a new InputStream, which will return the specified amount * of bytes of random ASCII characters. * * @param lengthInBytes * The size in bytes of the total data returned by this * stream. */ public RandomInputStream(long lengthInBytes) { this(lengthInBytes, false); } /** * Creates a new random input stream of specified length, and specifies * whether the stream should be full on binary or character data. * * @param lengthInBytes * The number of bytes in the stream. * @param binaryData * Whether binary or character data should be generated. */ public RandomInputStream(long lengthInBytes, boolean binaryData) { this.lengthInBytes = lengthInBytes; this.remainingBytes = lengthInBytes; this.binaryData = binaryData; } @Override public int read(byte[] b, int off, int len) throws IOException { // Signal that we're out of data if we've hit our limit if (remainingBytes <= 0) { return -1; } int bytesToRead = len; if (bytesToRead > remainingBytes) { bytesToRead = (int) remainingBytes; } remainingBytes -= bytesToRead; if (binaryData) { byte[] bytes = new byte[bytesToRead]; RANDOM.nextBytes(bytes); System.arraycopy(bytes, 0, b, off, bytesToRead); } else { for (int i = 0; i < bytesToRead; i++) { b[off + i] = (byte) (RANDOM.nextInt(MAX_CHAR_CODE - MIN_CHAR_CODE) + MIN_CHAR_CODE); } } return bytesToRead; } @Override public int read() throws IOException { // Signal that we're out of data if we've hit our limit if (remainingBytes <= 0) { return -1; } remainingBytes--; if (binaryData) { byte[] bytes = new byte[1]; RANDOM.nextBytes(bytes); return (int) bytes[0]; } else { return RANDOM.nextInt(MAX_CHAR_CODE - MIN_CHAR_CODE) + MIN_CHAR_CODE; } } public long getBytesRead() { return lengthInBytes - remainingBytes; } }
2,721
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/FileUtils.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.testutils; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.CopyOption; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; import java.util.stream.Stream; import software.amazon.awssdk.utils.StringUtils; public final class FileUtils { private FileUtils() { } public static void cleanUpTestDirectory(Path directory) { if (directory == null) { return; } try { try (Stream<Path> paths = Files.walk(directory, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)) { paths.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } } catch (IOException e) { // ignore e.printStackTrace(); } } public static void copyDirectory(Path source, Path destination, CopyOption... options) { try { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Files.createDirectories(mirror(dir)); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, mirror(file), options); return FileVisitResult.CONTINUE; } private Path mirror(Path path) { Path relativePath = source.relativize(path); return destination.resolve(relativePath); } }); } catch (IOException e) { throw new UncheckedIOException(String.format("Failed to copy %s to %s", source, destination), e); } } /** * Convert a given directory into a visual file tree. E.g., given an input structure of: * <pre> * /tmp/testdir * /tmp/testdir/CHANGELOG.md * /tmp/testdir/README.md * /tmp/testdir/notes * /tmp/testdir/notes/2022 * /tmp/testdir/notes/2022/1.txt * /tmp/testdir/notes/important.txt * /tmp/testdir/notes/2021 * /tmp/testdir/notes/2021/2.txt * /tmp/testdir/notes/2021/1.txt * </pre> * Calling this method on {@code /tmp/testdir} will yield the following output: * <pre> * - testdir * - CHANGELOG.md * - README.md * - notes * - 2022 * - 1.txt * - important.txt * - 2021 * - 2.txt * - 1.txt * </pre> */ public static String toFileTreeString(Path root) { int rootDepth = root.getNameCount(); String tab = StringUtils.repeat(" ", 4); StringBuilder sb = new StringBuilder(); try (Stream<Path> files = Files.walk(root)) { files.forEach(p -> { int indentLevel = p.getNameCount() - rootDepth; String line = String.format("%s- %s", StringUtils.repeat(tab, indentLevel), p.getFileName()); sb.append(line); sb.append(System.lineSeparator()); }); } catch (IOException e) { throw new UncheckedIOException(String.format("Failed to convert %s to file tree", root), e); } return sb.toString(); } }
2,722
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/UnorderedCollectionComparator.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.testutils; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * This class includes some utility methods for comparing two unordered * collections. */ public final class UnorderedCollectionComparator { private UnorderedCollectionComparator() { } /** * Compares two unordered lists of the same type. */ public static <T> boolean equalUnorderedCollections( Collection<T> colA, Collection<T> colB) { return equalUnorderedCollections(colA, colB, (a, b) -> (a == b) || a != null && a.equals(b)); } /** * Compares two unordered lists of different types, using the specified * cross-type comparator. Null collections are treated as empty ones. * Naively implemented using N(n^2) algorithm. */ public static <A, B> boolean equalUnorderedCollections( Collection<A> colA, Collection<B> colB, final CrossTypeComparator<A, B> comparator) { if (colA == null || colB == null) { if ((colA == null || colA.isEmpty()) && (colB == null || colB.isEmpty())) { return true; } else { return false; } } // Add all elements into sets to remove duplicates. Set<A> setA = new HashSet<>(colA); Set<B> setB = new HashSet<>(colB); if (setA.size() != setB.size()) { return false; } for (A a : setA) { boolean foundA = false; for (B b : setB) { if (comparator.equals(a, b)) { foundA = true; break; } } if (!foundA) { return false; } } return true; } /** * A simple interface that attempts to compare objects of two different types */ public interface CrossTypeComparator<A, B> { /** * @return True if a and b should be treated as equal. */ boolean equals(A a, B b); } }
2,723
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/RandomTempFile.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.testutils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.utils.JavaSystemSetting; /** * Extension of File that creates a temporary file with a specified name in * Java's temporary directory, as declared in the JRE's system properties. The * file is immediately filled with a specified amount of random ASCII data. * * @see RandomInputStream */ public class RandomTempFile extends File { private static final Logger log = LoggerFactory.getLogger(RandomTempFile.class); private static final long serialVersionUID = -8232143353692832238L; /** Java temp dir where all temp files will be created. */ private static final String TEMP_DIR = JavaSystemSetting.TEMP_DIRECTORY.getStringValueOrThrow(); /** Flag controlling whether binary or character data is used. */ private final boolean binaryData; /** * Creates, and fills, a temp file with a randomly generated name and specified size of random ASCII data. * * @param sizeInBytes The amount of random ASCII data, in bytes, for the new temp * file. * @throws IOException If any problems were encountered creating the new temp file. */ public RandomTempFile(long sizeInBytes) throws IOException { this(UUID.randomUUID().toString(), sizeInBytes, false); } /** * Creates, and fills, a temp file with the specified name and specified * size of random ASCII data. * * @param filename * The name for the new temporary file, within the Java temp * directory as declared in the JRE's system properties. * @param sizeInBytes * The amount of random ASCII data, in bytes, for the new temp * file. * * @throws IOException * If any problems were encountered creating the new temp file. */ public RandomTempFile(String filename, int sizeInBytes) throws IOException { this(filename, sizeInBytes, false); } /** * Creates, and fills, a temp file with the specified name and specified * size of random ASCII data. * * @param filename * The name for the new temporary file, within the Java temp * directory as declared in the JRE's system properties. * @param sizeInBytes * The amount of random ASCII data, in bytes, for the new temp * file. * * @throws IOException * If any problems were encountered creating the new temp file. */ public RandomTempFile(String filename, long sizeInBytes) throws IOException { this(filename, sizeInBytes, false); } /** * Creates, and fills, a temp file with the specified name and specified * size of random binary or character data. * * @param filename * The name for the new temporary file, within the Java temp * directory as declared in the JRE's system properties. * @param sizeInBytes * The amount of random ASCII data, in bytes, for the new temp * file. * @param binaryData Whether to fill the file with binary or character data. * * @throws IOException * If any problems were encountered creating the new temp file. */ public RandomTempFile(String filename, long sizeInBytes, boolean binaryData) throws IOException { super(TEMP_DIR + File.separator + System.currentTimeMillis() + "-" + filename); this.binaryData = binaryData; createFile(sizeInBytes); log.debug("RandomTempFile {} created", this); } public RandomTempFile(File root, String filename, long sizeInBytes) throws IOException { super(root, filename); this.binaryData = false; createFile(sizeInBytes); } public void createFile(long sizeInBytes) throws IOException { deleteOnExit(); try (FileOutputStream outputStream = new FileOutputStream(this); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); InputStream inputStream = new RandomInputStream(sizeInBytes, binaryData)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) > -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } } } @Override public boolean delete() { if (!super.delete()) { throw new RuntimeException("Could not delete: " + getAbsolutePath()); } return true; } public static File randomUncreatedFile() { File random = new File(TEMP_DIR, UUID.randomUUID().toString()); random.deleteOnExit(); return random; } @Override public boolean equals(Object obj) { return this == obj; } }
2,724
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/EnvironmentVariableHelper.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.testutils; import java.util.function.Consumer; import org.junit.rules.ExternalResource; import software.amazon.awssdk.utils.SystemSetting; import software.amazon.awssdk.utils.internal.SystemSettingUtilsTestBackdoor; /** * A utility that can temporarily forcibly set environment variables and then allows resetting them to the original values. * * This only works for environment variables read by the SDK. */ public class EnvironmentVariableHelper extends ExternalResource { public void remove(SystemSetting setting) { remove(setting.environmentVariable()); } public void remove(String key) { SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, null); } public void set(SystemSetting setting, String value) { set(setting.environmentVariable(), value); } public void set(String key, String value) { SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, value); } public void reset() { SystemSettingUtilsTestBackdoor.clearEnvironmentVariableOverrides(); } @Override protected void after() { reset(); } /** * Static run method that allows for "single-use" environment variable modification. * * Example use: * <pre> * {@code * EnvironmentVariableHelper.run(helper -> { * helper.set("variable", "value"); * //run some test that uses "variable" * }); * } * </pre> * * Will call {@link #reset} at the end of the block (even if the block exits exceptionally). * * @param helperConsumer a code block to run that gets an {@link EnvironmentVariableHelper} as an argument */ public static void run(Consumer<EnvironmentVariableHelper> helperConsumer) { EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); try { helperConsumer.accept(helper); } finally { helper.reset(); } } }
2,725
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/SdkAsserts.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.testutils; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import org.junit.Assert; import software.amazon.awssdk.utils.IoUtils; public final class SdkAsserts { private SdkAsserts() { } /** * Asserts that the specified String is not null and not empty. * * @param str * The String to test. * @deprecated Use Hamcrest Matchers instead */ @Deprecated public static void assertNotEmpty(String str) { assertNotNull(str); assertTrue(str.length() > 0); } /** * Asserts that the contents in the specified file are exactly equal to the contents read from * the specified input stream. The input stream will be closed at the end of this method. If any * problems are encountered, or the stream's contents don't match up exactly with the file's * contents, then this method will fail the current test. * * @param expected * The file containing the expected contents. * @param actual * The stream that will be read, compared to the expected file contents, and finally * closed. */ public static void assertFileEqualsStream(File expected, InputStream actual) { assertFileEqualsStream(null, expected, actual); } /** * Asserts that the contents in the specified file are exactly equal to the contents read from * the specified input stream. The input stream will be closed at the end of this method. If any * problems are encountered, or the stream's contents don't match up exactly with the file's * contents, then this method will fail the current test. * * @param errmsg * error message to be thrown when the assertion fails. * @param expected * The file containing the expected contents. * @param actual * The stream that will be read, compared to the expected file contents, and finally * closed. */ public static void assertFileEqualsStream(String errmsg, File expected, InputStream actual) { try { InputStream expectedInputStream = new FileInputStream(expected); assertStreamEqualsStream(errmsg, expectedInputStream, actual); } catch (FileNotFoundException e) { fail("Expected file " + expected.getAbsolutePath() + " doesn't exist: " + e.getMessage()); } } /** * Asserts that the contents in the specified input streams are same. The input streams will be * closed at the end of this method. If any problems are encountered, or the stream's contents * don't match up exactly with the file's contents, then this method will fail the current test. * * @param expected * expected input stream. The stream will be closed at the end. * @param actual * The stream that will be read, compared to the expected file contents, and finally * closed. */ public static void assertStreamEqualsStream(InputStream expected, InputStream actual) { assertStreamEqualsStream(null, expected, actual); } /** * Asserts that the contents in the specified input streams are same. The input streams will be * closed at the end of this method. If any problems are encountered, or the stream's contents * don't match up exactly with the file's contents, then this method will fail the current test. * * @param errmsg * error message to be thrown when the assertion fails. * @param expectedInputStream * expected input stream. The stream will be closed at the end. * @param inputStream * The stream that will be read, compared to the expected file contents, and finally * closed. */ public static void assertStreamEqualsStream(String errmsg, InputStream expectedInputStream, InputStream inputStream) { try { assertTrue(errmsg, doesStreamEqualStream(expectedInputStream, inputStream)); } catch (IOException e) { fail("Error reading from stream: " + e.getMessage()); } } /** * Asserts that the contents of the two files are same. * * @param expected * expected file. * @param actual * actual file. */ public static void assertFileEqualsFile(File expected, File actual) { if (expected == null || !expected.exists()) { fail("Expected file doesn't exist"); } if (actual == null || !actual.exists()) { fail("Actual file doesn't exist"); } long expectedFileLen = expected.length(); long fileLen = actual.length(); Assert.assertTrue("expectedFileLen=" + expectedFileLen + ", fileLen=" + fileLen + ", expectedFile=" + expected + ", file=" + actual, expectedFileLen == fileLen); try (InputStream expectedIs = new FileInputStream(expected); InputStream actualIs = new FileInputStream(actual)) { assertStreamEqualsStream("expected file: " + expected + " vs. actual file: " + actual, expectedIs, actualIs); } catch (IOException e) { fail("Unable to compare files: " + e.getMessage()); } } /** * Asserts that the contents in the specified string are exactly equal to the contents read from * the specified input stream. The input stream will be closed at the end of this method. If any * problems are encountered, or the stream's contents don't match up exactly with the string's * contents, then this method will fail the current test. * * @param expected * The string containing the expected data. * @param actual * The stream that will be read, compared to the expected string data, and finally * closed. */ public static void assertStringEqualsStream(String expected, InputStream actual) { try { InputStream expectedInputStream = new ByteArrayInputStream(expected.getBytes(StandardCharsets.UTF_8)); assertTrue(doesStreamEqualStream(expectedInputStream, actual)); } catch (IOException e) { fail("Error reading from stream: " + e.getMessage()); } } /** * Returns true if, and only if, the contents read from the specified input streams are exactly * equal. Both input streams will be closed at the end of this method. * * @param expected * The input stream containing the expected contents. * @param actual * The stream that will be read, compared to the expected file contents, and finally * closed. * @return True if the two input streams contain the same data. * @throws IOException * If any problems are encountered comparing the file and stream. */ public static boolean doesStreamEqualStream(InputStream expected, InputStream actual) throws IOException { try { byte[] expectedDigest = InputStreamUtils.calculateMD5Digest(expected); byte[] actualDigest = InputStreamUtils.calculateMD5Digest(actual); return Arrays.equals(expectedDigest, actualDigest); } catch (NoSuchAlgorithmException nse) { throw new RuntimeException(nse.getMessage(), nse); } finally { IoUtils.closeQuietly(expected, null); IoUtils.closeQuietly(actual, null); } } /** * Returns true if, and only if, the contents in the specified file are exactly equal to the * contents read from the specified input stream. The input stream will be closed at the end of * this method. * * @param expectedFile * The file containing the expected contents. * @param inputStream * The stream that will be read, compared to the expected file contents, and finally * closed. * @throws IOException * If any problems are encountered comparing the file and stream. */ public static boolean doesFileEqualStream(File expectedFile, InputStream inputStream) throws IOException { InputStream expectedInputStream = new FileInputStream(expectedFile); return doesStreamEqualStream(expectedInputStream, inputStream); } }
2,726
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/Memory.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.testutils; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.lang.management.MemoryUsage; /** * Used to retrieve information about the JVM memory. */ public final class Memory { private Memory() { } /** * Returns a summary information about the heap memory. */ public static String heapSummary() { Runtime rt = Runtime.getRuntime(); long totalMem = rt.totalMemory(); long freeMem = rt.freeMemory(); long usedMem = totalMem - freeMem; long spareMem = rt.maxMemory() - usedMem; return String.format( "Heap usedMem=%d (KB), freeMem=%d (KB), spareMem=%d (KB)%n", usedMem / 1024, freeMem / 1024, spareMem / 1024); } /** * Returns a summary information about the memory pools. */ public static String poolSummaries() { // Why ? list-archive?4273859 // How ? http://stackoverflow.com/questions/697336/how-do-i-programmatically-find-out-my-permgen-space-usage // http://stackoverflow.com/questions/8356416/xxmaxpermsize-with-or-without-xxpermsize StringBuilder sb = new StringBuilder(); for (MemoryPoolMXBean item : ManagementFactory.getMemoryPoolMXBeans()) { String name = item.getName(); MemoryType type = item.getType(); MemoryUsage usage = item.getUsage(); MemoryUsage peak = item.getPeakUsage(); MemoryUsage collections = item.getCollectionUsage(); sb.append("Memory pool name: " + name + ", type: " + type + ", usage: " + usage + ", peak: " + peak + ", collections: " + collections + "\n"); } return sb.toString(); } }
2,727
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/DateUtils.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.testutils; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatterBuilder; public final class DateUtils { private DateUtils() { } /** * Returns the current time in yyMMdd-hhmmss format. */ public static String yyMMddhhmmss() { return new DateTimeFormatterBuilder().appendPattern("yyMMdd-hhmmss").toFormatter().format(ZonedDateTime.now()); } }
2,728
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/InputStreamUtils.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.testutils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import software.amazon.awssdk.utils.IoUtils; public final class InputStreamUtils { private InputStreamUtils() { } /** * Calculates the MD5 digest for the given input stream and returns it. */ public static byte[] calculateMD5Digest(InputStream is) throws NoSuchAlgorithmException, IOException { int bytesRead = 0; byte[] buffer = new byte[2048]; MessageDigest md5 = MessageDigest.getInstance("MD5"); while ((bytesRead = is.read(buffer)) != -1) { md5.update(buffer, 0, bytesRead); } return md5.digest(); } /** * Reads to the end of the inputStream returning a byte array of the contents * * @param inputStream * InputStream to drain * @return Remaining data in stream as a byte array */ public static byte[] drainInputStream(InputStream inputStream) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; long bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) { byteArrayOutputStream.write(buffer, 0, (int) bytesRead); } return byteArrayOutputStream.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { IoUtils.closeQuietly(byteArrayOutputStream, null); } } }
2,729
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/UnreliableRandomInputStream.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.testutils; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Subclass of RandomInputStream that, in addition to spitting out a set length * of random characters, throws an IOException. Intended for testing error * recovery in the client library. */ public class UnreliableRandomInputStream extends RandomInputStream { private static final Logger log = LoggerFactory.getLogger(UnreliableRandomInputStream.class); private static final boolean DEBUG = false; /** True if this stream has already triggered an exception. */ private boolean hasTriggeredAnException = false; /** * Constructs a new unreliable random data input stream of the specified * number of bytes. * * @param lengthInBytes * The number of bytes of data contained in the new stream. */ public UnreliableRandomInputStream(long lengthInBytes) { super(lengthInBytes); } /** * @see RandomInputStream#read() */ @Override public int read() throws IOException { triggerException(); return super.read(); } /* * If we're more than half way through the bogus data, and we * haven't fired an exception yet, go ahead and fire one. */ private void triggerException() throws IOException { if (remainingBytes <= (lengthInBytes / 2) && !hasTriggeredAnException) { hasTriggeredAnException = true; String msg = "UnreliableBogusInputStream fired an IOException after reading " + getBytesRead() + " bytes."; if (DEBUG) { log.error(msg); } throw new IOException(msg); } } @Override public int read(byte[] b, int off, int len) throws IOException { triggerException(); int read = super.read(b, off, len); if (DEBUG) { log.debug("read={}, off={}, len={}, b.length={}", read, off, len, b.length); } return read; } }
2,730
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/LogCaptor.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.testutils; import static org.apache.logging.log4j.core.config.Configurator.setRootLevel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Property; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * A test utility that allows inspection of log statements * during testing. * <p> * Can either be used stand-alone for example * <pre><code> * try (LogCaptor logCaptor = new LogCaptor.DefaultLogCaptor(Level.INFO)) { * // Do stuff that you expect to log things * assertThat(logCaptor.loggedEvents(), is(not(empty()))); * } * </code></pre> * <p> * Or can extend it to make use of @Before / @After test annotations * <p> * <pre><code> * class MyTestClass extends LogCaptor.LogCaptorTestBase { * {@literal @}Test * public void someTestThatWeExpectToLog() { * // Do stuff that you expect to log things * assertThat(loggedEvents(), is(not(empty()))); * } * } * </code></pre> */ public interface LogCaptor extends SdkAutoCloseable { static LogCaptor create() { return new DefaultLogCaptor(); } static LogCaptor create(Level level) { return new DefaultLogCaptor(level); } List<LogEvent> loggedEvents(); void clear(); class LogCaptorTestBase extends DefaultLogCaptor { public LogCaptorTestBase() { } public LogCaptorTestBase(Level level) { super(level); } @Override @BeforeEach public void startCapturing() { super.startCapturing(); } @Override @AfterEach public void stopCapturing() { super.stopCapturing(); } } class DefaultLogCaptor extends AbstractAppender implements LogCaptor { private final List<LogEvent> loggedEvents = new ArrayList<>(); private final Level originalLoggingLevel = rootLogger().getLevel(); private final Level levelToCapture; private DefaultLogCaptor() { this(Level.ALL); } private DefaultLogCaptor(Level level) { super(/* name */ getCallerClassName(), /* filter */ null, /* layout */ null, /* ignoreExceptions */ false, /* properties */ Property.EMPTY_ARRAY); this.levelToCapture = level; startCapturing(); } @Override public List<LogEvent> loggedEvents() { return new ArrayList<>(loggedEvents); } @Override public void clear() { loggedEvents.clear(); } protected void startCapturing() { loggedEvents.clear(); rootLogger().addAppender(this); this.start(); setRootLevel(levelToCapture); } protected void stopCapturing() { rootLogger().removeAppender(this); this.stop(); setRootLevel(originalLoggingLevel); } @Override public void append(LogEvent event) { loggedEvents.add(event.toImmutable()); } @Override public void close() { stopCapturing(); } private static org.apache.logging.log4j.core.Logger rootLogger() { return (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); } static String getCallerClassName() { return Arrays.stream(Thread.currentThread().getStackTrace()) .map(StackTraceElement::getClassName) .filter(className -> !className.equals(Thread.class.getName())) .filter(className -> !className.equals(DefaultLogCaptor.class.getName())) .filter(className -> !className.equals(LogCaptor.class.getName())) .findFirst() .orElseThrow(NoSuchElementException::new); } } }
2,731
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/hamcrest/Matchers.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.testutils.hamcrest; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; public final class Matchers { private Matchers() { } /** * Creates a matcher that matches if the examined collection matches the specified matchers in order * * <p> * For example: * <pre>assertThat(Arrays.asList("foo", "bar"), containsOnlyInOrder(startsWith("f"), endsWith("ar")))</pre> */ public static <T> Matcher<Collection<T>> containsOnlyInOrder(Matcher<? extends T>... matchers) { return CollectionContainsOnlyInOrder.containsOnlyInOrder(Arrays.asList(matchers)); } /*** * Creates a matcher that matches if the examined collection matches the specified items in order * * <p> * For example: * <pre>assertThat(Arrays.asList("foo", "bar"), containsOnlyInOrder("foo", "bar"))</pre> */ public static <T> Matcher<Collection<T>> containsOnlyInOrder(T... items) { return CollectionContainsOnlyInOrder.containsOnlyInOrder(convertToMatchers(Arrays.asList(items))); } /*** * Creates a matcher that matches if the examined collection matches the specified items in any order * * <p> * For example: * <pre>assertThat(Arrays.asList("bar", "foo"), containsOnly(startsWith("f"), endsWith("ar")))</pre> */ public static <T> Matcher<Collection<T>> containsOnly(Matcher<? extends T>... matchers) { return CollectionContainsOnly.containsOnly(Arrays.asList(matchers)); } /*** * Creates a matcher that matches if the examined collection matches the specified items in any order * * <p> * For example: * <pre>assertThat(Arrays.asList("bar", "foo"), containsOnly("foo", "bar"))</pre> */ public static <T> Matcher<Collection<T>> containsOnly(T... items) { return CollectionContainsOnly.containsOnly(convertToMatchers(Arrays.asList(items))); } private static <T> List<Matcher<? extends T>> convertToMatchers(List<T> items) { List<Matcher<? extends T>> matchers = new ArrayList<>(); for (T item : items) { matchers.add(CoreMatchers.equalTo(item)); } return matchers; } }
2,732
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/hamcrest/CollectionContainsOnlyInOrder.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.testutils.hamcrest; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public final class CollectionContainsOnlyInOrder<T> extends TypeSafeMatcher<Collection<T>> { private final List<Matcher<? extends T>> matchers; private CollectionContainsOnlyInOrder(List<Matcher<? extends T>> matchers) { this.matchers = matchers; } static <T> TypeSafeMatcher<Collection<T>> containsOnlyInOrder(List<Matcher<? extends T>> matchers) { return new CollectionContainsOnlyInOrder<>(matchers); } @Override protected boolean matchesSafely(Collection<T> actualItems) { Queue<Matcher<? extends T>> copyOfMatchers = new LinkedList<>(matchers); for (T item : actualItems) { if (copyOfMatchers.isEmpty() || !copyOfMatchers.remove().matches(item)) { return false; } } return copyOfMatchers.isEmpty(); } @Override public void describeTo(Description description) { description.appendText("collection containing ").appendList("[", ", ", "]", matchers).appendText(" in order "); } }
2,733
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/hamcrest/CollectionContainsOnly.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.testutils.hamcrest; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; public final class CollectionContainsOnly<T> extends TypeSafeMatcher<Collection<T>> { private final List<Matcher<? extends T>> matchers; private CollectionContainsOnly(List<Matcher<? extends T>> matchers) { this.matchers = matchers; } static <T> TypeSafeMatcher<Collection<T>> containsOnly(List<Matcher<? extends T>> matchers) { return new CollectionContainsOnly<>(matchers); } @Override protected boolean matchesSafely(Collection<T> actualItems) { List<Matcher<? extends T>> copyOfExpected = new ArrayList<>(matchers); for (T item : actualItems) { boolean match = false; for (Matcher<? extends T> m : copyOfExpected) { if (m.matches(item)) { copyOfExpected.remove(m); match = true; break; } } if (!match) { return false; } } return copyOfExpected.isEmpty(); } @Override public void describeTo(Description description) { description.appendText("collection containing ").appendList("[", ", ", "]", matchers); } }
2,734
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/NonRetryableException.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.testutils.retry; import software.amazon.awssdk.utils.Validate; /** * Normally all exceptions are retried by {@link RetryableAction}. This is a special exception to * communicate the intent that a certain exception should not be retried. */ public class NonRetryableException extends Exception { public NonRetryableException(Exception e) { super(e); } @Override public Exception getCause() { return Validate.isInstanceOf(Exception.class, super.getCause(), "Unexpected cause type."); } }
2,735
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/RetryableError.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.testutils.retry; import software.amazon.awssdk.utils.Validate; /** * Normally {@link Error}'s are not retried by {@link RetryableAction}. This is a special error that * communicates retry intent to {@link RetryableAction}. */ public class RetryableError extends Error { public RetryableError(Error cause) { super(cause); } @Override public Error getCause() { return Validate.isInstanceOf(Error.class, super.getCause(), "Unexpected cause type."); } }
2,736
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/RetryableAssertion.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.testutils.retry; /** * Utility to repeatedly invoke assertion logic until it succeeds or the max allowed attempts is * reached. */ public final class RetryableAssertion { private RetryableAssertion() { } /** * Static method to repeatedly call assertion logic until it succeeds or the max allowed * attempts is reached. * * @param callable Callable implementing assertion logic * @param params Retry related parameters */ public static void doRetryableAssert(AssertCallable callable, RetryableParams params) throws Exception { RetryableAction.doRetryableAction(callable, params); } }
2,737
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/RetryRule.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.testutils.retry; import java.util.concurrent.TimeUnit; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.utils.Validate; public class RetryRule implements TestRule { private static final Logger log = LoggerFactory.getLogger(RetryRule.class); private int maxRetryAttempts; private long delay; private TimeUnit timeUnit; public RetryRule(int maxRetryAttempts) { this(maxRetryAttempts, 0, TimeUnit.SECONDS); } public RetryRule(int maxRetryAttempts, long delay, TimeUnit timeUnit) { this.maxRetryAttempts = maxRetryAttempts; this.delay = delay; this.timeUnit = Validate.paramNotNull(timeUnit, "timeUnit"); } @Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { retry(base, 1); } void retry(final Statement base, int attempts) throws Throwable { try { base.evaluate(); } catch (Exception e) { if (attempts > maxRetryAttempts) { throw e; } log.warn("Test failed. Retrying with delay of: {} {}", delay, timeUnit); timeUnit.sleep(delay); retry(base, ++attempts); } } }; } }
2,738
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/RetryableParams.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.testutils.retry; /** * Parameters for {@link RetryableAssertion}. */ public class RetryableParams { private final int maxAttempts; private final int delayInMs; public RetryableParams() { this.maxAttempts = 0; this.delayInMs = 0; } private RetryableParams(int maxAttempts, int delayInMs) { this.maxAttempts = maxAttempts; this.delayInMs = delayInMs; } public int getMaxAttempts() { return maxAttempts; } public RetryableParams withMaxAttempts(int maxAttempts) { return new RetryableParams(maxAttempts, this.delayInMs); } public int getDelayInMs() { return delayInMs; } public RetryableParams withDelayInMs(int delayInMs) { return new RetryableParams(this.maxAttempts, delayInMs); } }
2,739
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/RetryableAction.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.testutils.retry; import java.util.concurrent.Callable; import software.amazon.awssdk.utils.Validate; /** * Utility to repeatedly invoke an action that returns a result until it succeeds or the max allowed * attempts is reached. All Exceptions except for those wrapped in {@link NonRetryableException} are * retried. Only errors wrapped in {@link RetryableError} are retried. */ public final class RetryableAction<T> { private final Callable<T> delegate; private final RetryableParams params; private RetryableAction(Callable<T> delegate, RetryableParams params) { this.delegate = delegate; this.params = params; } /** * Static method to repeatedly call action until it succeeds or the max allowed attempts is * reached. * * @param callable Callable implementing assertion logic * @param params Retry related parameters * @return Successful result */ public static <T> T doRetryableAction(Callable<T> callable, RetryableParams params) throws Exception { Validate.isTrue(params.getMaxAttempts() > 0, "maxAttempts"); return new RetryableAction<>(callable, params).call(); } private T call() throws Exception { return call(params.getMaxAttempts()); } private T call(final int remainingAttempts) throws Exception { try { // Don't delay before the first attempt if (params.getMaxAttempts() != remainingAttempts) { delay(); } return delegate.call(); } catch (RetryableError e) { if (shouldNotRetry(remainingAttempts - 1)) { throw e.getCause(); } return call(remainingAttempts - 1); } catch (NonRetryableException e) { throw e.getCause(); } catch (Exception e) { if (shouldNotRetry(remainingAttempts - 1)) { throw e; } return call(remainingAttempts - 1); } } private boolean shouldNotRetry(int remainingAttempts) { return remainingAttempts <= 0; } private void delay() throws InterruptedException { if (params.getDelayInMs() > 0) { Thread.sleep(params.getDelayInMs()); } } }
2,740
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/retry/AssertCallable.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.testutils.retry; import java.util.concurrent.Callable; /** * Base class for assertion logic, used by {@link RetryableAssertion}. */ public abstract class AssertCallable implements Callable<Void> { @Override public final Void call() throws Exception { try { doAssert(); } catch (AssertionError e) { throw new RetryableError(e); } catch (Exception e) { throw new NonRetryableException(e); } return null; } public abstract void doAssert() throws Exception; }
2,741
0
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils
Create_ds/aws-sdk-java-v2/test/test-utils/src/main/java/software/amazon/awssdk/testutils/smoketest/ReflectionUtils.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.testutils.smoketest; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.UUID; import org.slf4j.LoggerFactory; /** * Utility methods for doing reflection. */ public final class ReflectionUtils { private static final Random RANDOM = new Random(); private ReflectionUtils() { } public static <T> Class<T> loadClass(Class<?> base, String name) { return loadClass(base.getClassLoader(), name); } public static <T> Class<T> loadClass(ClassLoader classloader, String name) { try { @SuppressWarnings("unchecked") Class<T> loaded = (Class<T>) classloader.loadClass(name); return loaded; } catch (ClassNotFoundException exception) { throw new IllegalStateException( "Cannot find class " + name, exception); } } public static <T> T newInstance(Class<T> clazz, Object... params) { Constructor<T> constructor = findConstructor(clazz, params); try { return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalStateException( "Could not invoke " + constructor.toGenericString(), ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new IllegalStateException( "Unexpected checked exception thrown from " + constructor.toGenericString(), ex); } } private static <T> Constructor<T> findConstructor( Class<T> clazz, Object[] params) { for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (matches(paramTypes, params)) { @SuppressWarnings("unchecked") Constructor<T> rval = (Constructor<T>) constructor; return rval; } } throw new IllegalStateException( "No appropriate constructor found for " + clazz.getCanonicalName()); } private static boolean matches(Class<?>[] paramTypes, Object[] params) { if (paramTypes.length != params.length) { return false; } for (int i = 0; i < params.length; ++i) { if (!paramTypes[i].isAssignableFrom(params[i].getClass())) { return false; } } return true; } /** * Evaluates the given path expression on the given object and returns the * object found. * * @param target the object to reflect on * @param path the path to evaluate * @return the result of evaluating the path against the given object */ public static Object getByPath(Object target, List<String> path) { Object obj = target; for (String field : path) { if (obj == null) { return null; } obj = evaluate(obj, trimType(field)); } return obj; } /** * Evaluates the given path expression and returns the list of all matching * objects. If the path expression does not contain any wildcards, this * will return a list of at most one item. If the path contains one or more * wildcards, the returned list will include the full set of values * obtained by evaluating the expression with all legal value for the * given wildcard. * * @param target the object to evaluate the expression against * @param path the path expression to evaluate * @return the list of matching values */ public static List<Object> getAllByPath(Object target, List<String> path) { List<Object> results = new LinkedList<>(); // TODO: Can we unroll this and do it iteratively? getAllByPath(target, path, 0, results); return results; } private static void getAllByPath( Object target, List<String> path, int depth, List<Object> results) { if (target == null) { return; } if (depth == path.size()) { results.add(target); return; } String field = trimType(path.get(depth)); if (field.equals("*")) { if (!(target instanceof Iterable)) { throw new IllegalStateException( "Cannot evaluate '*' on object " + target); } Iterable<?> collection = (Iterable<?>) target; for (Object obj : collection) { getAllByPath(obj, path, depth + 1, results); } } else { Object obj = evaluate(target, field); getAllByPath(obj, path, depth + 1, results); } } private static String trimType(String field) { int index = field.indexOf(':'); if (index == -1) { return field; } return field.substring(0, index); } /** * Uses reflection to evaluate a single element of a path expression on * the given object. If the object is a list and the expression is a * number, this returns the expression'th element of the list. Otherwise, * this looks for a method named "get${expression}" and returns the result * of calling it. * * @param target the object to evaluate the expression against * @param expression the expression to evaluate * @return the result of evaluating the expression */ private static Object evaluate(Object target, String expression) { try { if (target instanceof List) { List<?> list = (List<?>) target; int index = Integer.parseInt(expression); if (index < 0) { index += list.size(); } return list.get(index); } else { Method getter = findAccessor(target, expression); if (getter == null) { return null; } return getter.invoke(target); } } catch (IllegalAccessException exception) { throw new IllegalStateException("BOOM", exception); } catch (InvocationTargetException exception) { Throwable cause = exception.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException("BOOM", exception); } } /** * Sets the value of the attribute at the given path in the target object, * creating any intermediate values (using the default constructor for the * type) if need be. * * @param target the object to modify * @param value the value to add * @param path the path into the target object at which to add the value */ public static void setByPath( Object target, Object value, List<String> path) { Object obj = target; Iterator<String> iter = path.iterator(); while (iter.hasNext()) { String field = iter.next(); if (iter.hasNext()) { obj = digIn(obj, field); } else { setValue(obj, trimType(field), value); } } } /** * Uses reflection to dig into a chain of objects in preparation for * setting a value somewhere within the tree. Gets the value of the given * property of the target object and, if it is null, creates a new instance * of the appropriate type and sets it on the target object. Returns the * gotten or created value. * * @param target the target object to reflect on * @param field the field to dig into * @return the gotten or created value */ private static Object digIn(Object target, String field) { if (target instanceof List) { // The 'field' will tell us what type of objects belong in the list. @SuppressWarnings("unchecked") List<Object> list = (List<Object>) target; return digInList(list, field); } else if (target instanceof Map) { // The 'field' will tell us what type of objects belong in the map. @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) target; return digInMap(map, field); } else { return digInObject(target, field); } } private static Object digInList(List<Object> target, String field) { int index = field.indexOf(':'); if (index == -1) { throw new IllegalStateException("Invalid path expression: cannot " + "evaluate '" + field + "' on a List"); } String offset = field.substring(0, index); String type = field.substring(index + 1); if (offset.equals("*")) { throw new UnsupportedOperationException( "What does this even mean?"); } int intOffset = Integer.parseInt(offset); if (intOffset < 0) { // Offset from the end of the list intOffset += target.size(); if (intOffset < 0) { throw new IndexOutOfBoundsException( Integer.toString(intOffset)); } } if (intOffset < target.size()) { return target.get(intOffset); } // Extend with default instances if need be. while (intOffset > target.size()) { target.add(createDefaultInstance(type)); } Object result = createDefaultInstance(type); target.add(result); return result; } private static Object digInMap(Map<String, Object> target, String field) { int index = field.indexOf(':'); if (index == -1) { throw new IllegalStateException("Invalid path expression: cannot " + "evaluate '" + field + "' on a List"); } String member = field.substring(0, index); String type = field.substring(index + 1); Object result = target.get(member); if (result != null) { return result; } result = createDefaultInstance(type); target.put(member, result); return result; } public static Object createDefaultInstance(String type) { try { return ReflectionUtils.class.getClassLoader() .loadClass(type) .newInstance(); } catch (Exception e) { throw new IllegalStateException("BOOM", e); } } private static Object digInObject(Object target, String field) { Method getter = findAccessor(target, field); if (getter == null) { throw new IllegalStateException( "No accessor found for '" + field + "' found in class " + target.getClass().getName()); } try { Object obj = getter.invoke(target); if (obj == null) { obj = getter.getReturnType().newInstance(); Method setter = findMethod(target, "set" + field, obj.getClass()); setter.invoke(target, obj); } return obj; } catch (InstantiationException exception) { throw new IllegalStateException( "Unable to create a new instance", exception); } catch (IllegalAccessException exception) { throw new IllegalStateException( "Unable to access getter, setter, or constructor", exception); } catch (InvocationTargetException exception) { Throwable cause = exception.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new IllegalStateException( "Checked exception thrown from getter or setter method", exception); } } /** * Uses reflection to set the value of the given property on the target * object. * * @param target the object to reflect on * @param field the name of the property to set * @param value the new value of the property */ private static void setValue(Object target, String field, Object value) { // TODO: Should we do this for all numbers, not just '0'? if ("0".equals(field)) { if (!(target instanceof Collection)) { throw new IllegalArgumentException( "Cannot evaluate '0' on object " + target); } @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) target; collection.add(value); } else { Method setter = findMethod(target, "set" + field, value.getClass()); try { setter.invoke(target, value); } catch (IllegalAccessException exception) { throw new IllegalStateException( "Unable to access setter method", exception); } catch (InvocationTargetException exception) { Throwable cause = exception.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new IllegalStateException( "Checked exception thrown from setter method", exception); } } } /** * Returns the accessor method for the specified member property. * For example, if the member property is "Foo", this method looks * for a "getFoo()" method and an "isFoo()" method. * * If no accessor is found, this method throws an IllegalStateException. * * @param target the object to reflect on * @param propertyName the name of the property to search for * @return the accessor method * @throws IllegalStateException if no matching method is found */ public static Method findAccessor(Object target, String propertyName) { propertyName = propertyName.substring(0, 1).toUpperCase(Locale.ENGLISH) + propertyName.substring(1); try { return target.getClass().getMethod("get" + propertyName); } catch (NoSuchMethodException nsme) { // Ignored or expected. } try { return target.getClass().getMethod("is" + propertyName); } catch (NoSuchMethodException nsme) { // Ignored or expected. } LoggerFactory.getLogger(ReflectionUtils.class).warn("No accessor for property '{}' found in class {}", propertyName, target.getClass().getName()); return null; } /** * Finds a method of the given name that will accept a parameter of the * given type. If more than one method matches, returns the first such * method found. * * @param target the object to reflect on * @param name the name of the method to search for * @param parameterType the type of the parameter to be passed * @return the matching method * @throws IllegalStateException if no matching method is found */ public static Method findMethod( Object target, String name, Class<?> parameterType) { for (Method method : target.getClass().getMethods()) { if (!method.getName().equals(name)) { continue; } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 1) { continue; } if (parameters[0].isAssignableFrom(parameterType)) { return method; } } throw new IllegalStateException( "No method '" + name + "(" + parameterType + ") on type " + target.getClass()); } public static Class<?> getParameterTypes(Object target, List<String> path) { Object obj = target; Iterator<String> iter = path.iterator(); while (iter.hasNext()) { String field = iter.next(); if (iter.hasNext()) { obj = digIn(obj, field); } else { return findAccessor(obj, field).getReturnType(); } } return null; } public static void setField(Object instance, Field field, Object arg) { try { field.set(instance, arg); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static <T> Object getField(T instance, Field field) { try { return field.get(instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public static <T> T newInstanceWithAllFieldsSet(Class<T> clz) { List<RandomSupplier<?>> emptyRandomSuppliers = new ArrayList<>(); return newInstanceWithAllFieldsSet(clz, emptyRandomSuppliers); } public static <T> T newInstanceWithAllFieldsSet(Class<T> clz, RandomSupplier<?>... suppliers) { return newInstanceWithAllFieldsSet(clz, Arrays.asList(suppliers)); } public static <T> T newInstanceWithAllFieldsSet(Class<T> clz, List<RandomSupplier<?>> suppliers) { T instance = newInstance(clz); for (Field field : clz.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers())) { continue; } Class<?> type = field.getType(); AccessController.doPrivileged((PrivilegedAction<?>) () -> { field.setAccessible(true); return null; }); RandomSupplier<?> supplier = findSupplier(suppliers, type); if (supplier != null) { setField(instance, field, supplier.getNext()); } else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) { setField(instance, field, RANDOM.nextInt(Integer.MAX_VALUE)); } else if (type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) { setField(instance, field, (long) RANDOM.nextInt(Integer.MAX_VALUE)); } else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) { Object bool = getField(instance, field); if (bool == null) { setField(instance, field, RANDOM.nextBoolean()); } else { setField(instance, field, !Boolean.parseBoolean(bool.toString())); } } else if (type.isAssignableFrom(String.class)) { setField(instance, field, UUID.randomUUID().toString()); } else { throw new RuntimeException(String.format("Could not set value for type %s no supplier available.", type)); } } return instance; } private static RandomSupplier<?> findSupplier(List<RandomSupplier<?>> suppliers, Class<?> type) { for (RandomSupplier<?> supplier : suppliers) { if (type.isAssignableFrom(supplier.targetClass())) { return supplier; } } return null; } interface RandomSupplier<T> { T getNext(); Class<T> targetClass(); } }
2,742
0
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/test
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/test/java/S3AnonymousTest.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. */ import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; /** * Ensure that we can make anonymous requests using S3. */ public class S3AnonymousTest { private MockSyncHttpClient httpClient; private MockAsyncHttpClient asyncHttpClient; private S3Client s3; private S3AsyncClient s3Async; @BeforeEach public void setup() { this.httpClient = new MockSyncHttpClient(); this.httpClient.stubNextResponse200(); this.asyncHttpClient = new MockAsyncHttpClient(); this.asyncHttpClient.stubNextResponse200(); this.s3 = S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(httpClient) .build(); this.s3Async = S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(asyncHttpClient) .build(); } @AfterEach public void teardown() { httpClient.close(); asyncHttpClient.close(); s3.close(); s3Async.close(); } @Test public void nonStreamingOperations_canBeAnonymous() { s3.listBuckets(); assertThat(httpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } @Test public void nonStreamingOperations_async_canBeAnonymous() { s3Async.listBuckets().join(); assertThat(asyncHttpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } @Test public void streamingWriteOperations_canBeAnonymous() { s3.putObject(r -> r.bucket("bucket").key("key"), RequestBody.fromString("foo")); assertThat(httpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } @Test public void streamingWriteOperations_async_canBeAnonymous() { s3Async.putObject(r -> r.bucket("bucket").key("key"), AsyncRequestBody.fromString("foo")).join(); assertThat(asyncHttpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } @Test public void streamingReadOperations_canBeAnonymous() { s3.getObject(r -> r.bucket("bucket").key("key"), ResponseTransformer.toBytes()); assertThat(httpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } @Test public void streamingReadOperations_async_canBeAnonymous() { s3Async.getObject(r -> r.bucket("bucket").key("key"), AsyncResponseTransformer.toBytes()).join(); assertThat(asyncHttpClient.getLastRequest().firstMatchingHeader("Authorization")).isEmpty(); } }
2,743
0
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/test
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/test/java/InterceptorSignerAttributeTest.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. */ import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; /** * Ensure that attributes set in execution interceptors are passed to custom signers. These are protected APIs, but code * searches show that customers are using them as if they aren't. We should push customers onto supported paths. */ public class InterceptorSignerAttributeTest { private static final AwsCredentials CREDS = AwsBasicCredentials.create("akid", "skid"); @Test public void canSetSignerExecutionAttributes_beforeExecution() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }, AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, // Endpoint rules override signing name AwsSignerExecutionAttribute.SIGNING_REGION, // Endpoint rules override signing region AwsSignerExecutionAttribute.AWS_CREDENTIALS, // Legacy auth strategy overrides credentials AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE); // Endpoint rules override double-url-encode } @Test public void canSetSignerExecutionAttributes_modifyRequest() { test(attributeModifications -> new ExecutionInterceptor() { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); return context.request(); } }, AwsSignerExecutionAttribute.AWS_CREDENTIALS); // Legacy auth strategy overrides credentials } @Test public void canSetSignerExecutionAttributes_beforeMarshalling() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }); } @Test public void canSetSignerExecutionAttributes_afterMarshalling() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }); } @Test public void canSetSignerExecutionAttributes_modifyHttpRequest() { test(attributeModifications -> new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); return context.httpRequest(); } }); } private void test(Function<Consumer<ExecutionAttributes>, ExecutionInterceptor> interceptorFactory, ExecutionAttribute<?>... attributesToExcludeFromTest) { Set<ExecutionAttribute<?>> attributesToExclude = new HashSet<>(Arrays.asList(attributesToExcludeFromTest)); ExecutionInterceptor interceptor = interceptorFactory.apply(executionAttributes -> { executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "signing-name"); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of("signing-region")); executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDS); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, true); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, true); }); ClientOverrideConfiguration.Builder configBuilder = ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor); try (MockSyncHttpClient httpClient = new MockSyncHttpClient(); MockAsyncHttpClient asyncHttpClient = new MockAsyncHttpClient()) { stub200Responses(httpClient, asyncHttpClient); S3ClientBuilder s3Builder = createS3Builder(configBuilder, httpClient); S3AsyncClientBuilder s3AsyncBuilder = createS3AsyncBuilder(configBuilder, asyncHttpClient); CapturingSigner signer1 = new CapturingSigner(); try (S3Client s3 = s3Builder.overrideConfiguration(configBuilder.putAdvancedOption(SdkAdvancedClientOption.SIGNER, signer1) .build()) .build()) { callS3(s3); validateLegacySignRequest(attributesToExclude, signer1); } CapturingSigner signer2 = new CapturingSigner(); try (S3AsyncClient s3 = s3AsyncBuilder.overrideConfiguration(configBuilder.putAdvancedOption(SdkAdvancedClientOption.SIGNER, signer2) .build()) .build()) { callS3(s3); validateLegacySignRequest(attributesToExclude, signer2); } } } private static void stub200Responses(MockSyncHttpClient httpClient, MockAsyncHttpClient asyncHttpClient) { HttpExecuteResponse response = HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); httpClient.stubResponses(response); asyncHttpClient.stubResponses(response); } private static S3ClientBuilder createS3Builder(ClientOverrideConfiguration.Builder configBuilder, MockSyncHttpClient httpClient) { return S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(httpClient) .overrideConfiguration(configBuilder.build()); } private static S3AsyncClientBuilder createS3AsyncBuilder(ClientOverrideConfiguration.Builder configBuilder, MockAsyncHttpClient asyncHttpClient) { return S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(asyncHttpClient) .overrideConfiguration(configBuilder.build()); } private static void callS3(S3Client s3) { s3.putObject(r -> r.bucket("foo") .key("bar") .checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString("text")); } private void callS3(S3AsyncClient s3) { s3.putObject(r -> r.bucket("foo") .key("bar") .checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString("text")) .join(); } private void validateLegacySignRequest(Set<ExecutionAttribute<?>> attributesToExclude, CapturingSigner signer) { if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)) { assertThat(signer.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)) .isEqualTo("signing-name"); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNING_REGION)) { assertThat(signer.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)) .isEqualTo(Region.of("signing-region")); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.AWS_CREDENTIALS)) { assertThat(signer.executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)) .isEqualTo(CREDS); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)) { assertThat(signer.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)) .isEqualTo(true); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH)) { assertThat(signer.executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH)) .isEqualTo(true); } } private static class CapturingSigner implements Signer { private ExecutionAttributes executionAttributes; @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { this.executionAttributes = executionAttributes.copy(); return request; } } }
2,744
0
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/it/java/software/amazon/awssdk/services/oldclient/TestUtils.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.services.oldclient; import java.util.Iterator; import java.util.List; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.testutils.Waiter; public class TestUtils { public static void deleteBucketAndAllContents(S3Client s3, String bucketName) { try { System.out.println("Deleting S3 bucket: " + bucketName); ListObjectsResponse response = Waiter.run(() -> s3.listObjects(r -> r.bucket(bucketName))) .ignoringException(NoSuchBucketException.class) .orFail(); List<S3Object> objectListing = response.contents(); if (objectListing != null) { while (true) { for (Iterator<?> iterator = objectListing.iterator(); iterator.hasNext(); ) { S3Object objectSummary = (S3Object) iterator.next(); s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build()); } if (response.isTruncated()) { objectListing = s3.listObjects(ListObjectsRequest.builder() .bucket(bucketName) .marker(response.marker()) .build()) .contents(); } else { break; } } } ListObjectVersionsResponse versions = s3 .listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build()); if (versions.deleteMarkers() != null) { versions.deleteMarkers().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder() .versionId(v.versionId()) .bucket(bucketName) .key(v.key()) .build())); } if (versions.versions() != null) { versions.versions().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder() .versionId(v.versionId()) .bucket(bucketName) .key(v.key()) .build())); } s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build()); } catch (Exception e) { System.err.println("Failed to delete bucket: " + bucketName); e.printStackTrace(); } } }
2,745
0
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/test/old-client-version-compatibility-test/src/it/java/software/amazon/awssdk/services/oldclient/S3PutGetIntegrationTest.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.services.oldclient; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.util.UUID; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.signer.AwsS3V4Signer; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.ChecksumMode; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.testutils.service.AwsTestBase; public class S3PutGetIntegrationTest extends AwsTestBase { private static final S3Client S3 = s3ClientBuilder().build(); private static final S3Client S3_CUSTOM_SIGNER = s3ClientBuilder().overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER, AwsS3V4Signer.create())) .build(); private static final S3Client S3_NO_CREDS = s3ClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .build(); private static final S3AsyncClient S3_ASYNC = getS3AsyncClientBuilder().build(); private static final S3AsyncClient S3_ASYNC_CUSTOM_SIGNER = getS3AsyncClientBuilder().overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER, AwsS3V4Signer.create())) .build(); private static final S3AsyncClient S3_ASYNC_NO_CREDS = getS3AsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .build(); private static final String BUCKET = "sra-get-put-integ-" + System.currentTimeMillis(); private static final String BODY = "foo"; private static final String BODY_CRC32 = "jHNlIQ=="; private String key; @BeforeAll public static void setup() { S3.createBucket(r -> r.bucket(BUCKET)); } @BeforeEach public void setupTest() { key = UUID.randomUUID().toString(); } @AfterAll public static void teardown() { TestUtils.deleteBucketAndAllContents(S3, BUCKET); } @Test public void putGet() { S3.putObject(r -> r.bucket(BUCKET).key(key), RequestBody.fromString(BODY)); assertThat(S3.getObjectAsBytes(r -> r.bucket(BUCKET).key(key)).asUtf8String()).isEqualTo(BODY); } @Test public void putGet_async() { S3_ASYNC.putObject(r -> r.bucket(BUCKET).key(key), AsyncRequestBody.fromString(BODY)).join(); assertThat(S3_ASYNC.getObject(r -> r.bucket(BUCKET).key(key), AsyncResponseTransformer.toBytes()) .join() .asUtf8String()).isEqualTo(BODY); } @Test public void putGet_requestLevelCreds() { S3_NO_CREDS.putObject(r -> r.bucket(BUCKET) .key(key) .overrideConfiguration(c -> c.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)), RequestBody.fromString(BODY)); assertThat(S3_NO_CREDS.getObjectAsBytes(r -> r.bucket(BUCKET) .key(key) .overrideConfiguration(c -> c.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN))) .asUtf8String()).isEqualTo(BODY); } @Test public void putGet_async_requestLevelCreds() { S3_ASYNC_NO_CREDS.putObject(r -> r.bucket(BUCKET) .key(key) .overrideConfiguration(c -> c.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)), AsyncRequestBody.fromString(BODY)) .join(); assertThat(S3_ASYNC_NO_CREDS.getObject(r -> r.bucket(BUCKET) .key(key) .overrideConfiguration(c -> c.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)), AsyncResponseTransformer.toBytes()) .join() .asUtf8String()).isEqualTo(BODY); } @Test public void putGet_flexibleChecksums() { S3.putObject(r -> r.bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString(BODY)); ResponseBytes<GetObjectResponse> response = S3.getObjectAsBytes(r -> r.bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED)); assertThat(response.asUtf8String()).isEqualTo(BODY); assertThat(response.response().checksumCRC32()).isEqualTo(BODY_CRC32); } @Test public void putGet_async_flexibleChecksums() { S3_ASYNC.putObject(r -> r.bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString(BODY)).join(); ResponseBytes<GetObjectResponse> response = S3_ASYNC.getObject(r -> r.bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()) .join(); assertThat(response.asUtf8String()).isEqualTo(BODY); assertThat(response.response().checksumCRC32()).isEqualTo(BODY_CRC32); } @Test public void putGet_customSigner_flexibleChecksums() { S3_CUSTOM_SIGNER.putObject(r -> r.bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString(BODY)); ResponseBytes<GetObjectResponse> response = S3_CUSTOM_SIGNER.getObjectAsBytes(r -> r.bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED)); assertThat(response.asUtf8String()).isEqualTo(BODY); assertThat(response.response().checksumCRC32()).isEqualTo(BODY_CRC32); } @Test public void putGet_async_customSigner_flexibleChecksums() { S3_ASYNC_CUSTOM_SIGNER.putObject(r -> r.bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString(BODY)) .join(); ResponseBytes<GetObjectResponse> response = S3_ASYNC_CUSTOM_SIGNER.getObject(r -> r.bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()) .join(); assertThat(response.asUtf8String()).isEqualTo(BODY); assertThat(response.response().checksumCRC32()).isEqualTo(BODY_CRC32); } private static S3ClientBuilder s3ClientBuilder() { return S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN); } private static S3AsyncClientBuilder getS3AsyncClientBuilder() { return S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN); } }
2,746
0
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk/nativeimagetest/DependencyFactory.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.nativeimagetest; import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.metrics.LoggingMetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; /** * The module containing all dependencies required by the {@link App}. */ public class DependencyFactory { /** Default Properties Credentials file path. */ private static final String TEST_CREDENTIALS_PROFILE_NAME = "aws-test-account"; public static final AwsCredentialsProviderChain CREDENTIALS_PROVIDER_CHAIN = AwsCredentialsProviderChain.of(ProfileCredentialsProvider.builder() .profileName(TEST_CREDENTIALS_PROFILE_NAME) .build(), DefaultCredentialsProvider.create()); private DependencyFactory() { } public static S3Client s3UrlConnectionHttpClient() { return S3Client.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(UrlConnectionHttpClient.builder()) .overrideConfiguration(o -> o.addMetricPublisher(LoggingMetricPublisher.create())) .region(Region.US_WEST_2) .build(); } public static S3Client s3ApacheHttpClient() { return S3Client.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(ApacheHttpClient.builder()) .overrideConfiguration(o -> o.addMetricPublisher(LoggingMetricPublisher.create())) .region(Region.US_WEST_2) .build(); } public static S3AsyncClient s3NettyClient() { return S3AsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .overrideConfiguration(o -> o.addMetricPublisher(LoggingMetricPublisher.create())) .region(Region.US_WEST_2) .build(); } public static DynamoDbClient ddbClient() { return DynamoDbClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(ApacheHttpClient.builder()) .overrideConfiguration(o -> o.addMetricPublisher(LoggingMetricPublisher.create())) .region(Region.US_WEST_2) .build(); } public static DynamoDbEnhancedClient enhancedClient(DynamoDbClient ddbClient) { return DynamoDbEnhancedClient.builder() .dynamoDbClient(ddbClient) .build(); } }
2,747
0
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk/nativeimagetest/TestRunner.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.nativeimagetest; public interface TestRunner { void runTests(); }
2,748
0
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk/nativeimagetest/DynamoDbEnhancedClientTestRunner.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.nativeimagetest; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; public class DynamoDbEnhancedClientTestRunner implements TestRunner { private static final String TABLE_NAME = "native-image" + System.currentTimeMillis(); private static final String ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS = "a*t:t.r-i#bute3"; private static final Logger logger = LoggerFactory.getLogger(DynamoDbEnhancedClientTestRunner.class); private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record::getAttribute) .setter(Record::setAttribute)) .addAttribute(String.class, a -> a.name("attribute2*") .getter(Record::getAttribute2) .setter(Record::setAttribute2) .tags(secondaryPartitionKey("gsi_1"))) .addAttribute(String.class, a -> a.name(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .getter(Record::getAttribute3) .setter(Record::setAttribute3) .tags(secondarySortKey("gsi_1"))) .build(); private static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder() .readCapacityUnits(50L) .writeCapacityUnits(50L) .build(); private final DynamoDbClient dynamoDbClient; private final DynamoDbEnhancedClient enhancedClient; public DynamoDbEnhancedClientTestRunner() { dynamoDbClient = DependencyFactory.ddbClient(); enhancedClient = DependencyFactory.enhancedClient(dynamoDbClient); } @Override public void runTests() { logger.info("starting to run DynamoDbEnhancedClient tests"); try { DynamoDbTable<Record> mappedTable = enhancedClient.table(TABLE_NAME, TABLE_SCHEMA); mappedTable.createTable(r -> r.provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(DEFAULT_PROVISIONED_THROUGHPUT) .build())); dynamoDbClient.waiter().waitUntilTableExists(b -> b.tableName(TABLE_NAME)); Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); } finally { dynamoDbClient.deleteTable(b -> b.tableName(TABLE_NAME)); } } private static final class Record { private String id; private String sort; private String attribute; private String attribute2; private String attribute3; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String getSort() { return sort; } private Record setSort(String sort) { this.sort = sort; return this; } private String getAttribute() { return attribute; } private Record setAttribute(String attribute) { this.attribute = attribute; return this; } private String getAttribute2() { return attribute2; } private Record setAttribute2(String attribute2) { this.attribute2 = attribute2; return this; } private String getAttribute3() { return attribute3; } private Record setAttribute3(String attribute3) { this.attribute3 = attribute3; return this; } } }
2,749
0
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk/nativeimagetest/App.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.nativeimagetest; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); private App() { } public static void main(String... args) { logger.info("Application starts"); List<TestRunner> tests = new ArrayList<>(); tests.add(new S3TestRunner()); tests.add(new DynamoDbEnhancedClientTestRunner()); tests.forEach(t -> t.runTests()); logger.info("Application ends"); } }
2,750
0
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-native-image-test/src/main/java/software/amazon/awssdk/nativeimagetest/S3TestRunner.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.nativeimagetest; import java.nio.charset.StandardCharsets; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CreateBucketResponse; public class S3TestRunner implements TestRunner { private static final String BUCKET_NAME = "v2-native-image-tests-" + UUID.randomUUID(); private static final Logger logger = LoggerFactory.getLogger(S3TestRunner.class); private static final String KEY = "key"; private final S3Client s3ApacheHttpClient; private final S3Client s3UrlConnectionHttpClient; private final S3AsyncClient s3NettyClient; public S3TestRunner() { s3ApacheHttpClient = DependencyFactory.s3ApacheHttpClient(); s3UrlConnectionHttpClient = DependencyFactory.s3UrlConnectionHttpClient(); s3NettyClient = DependencyFactory.s3NettyClient(); } @Override public void runTests() { logger.info("starting to run S3 tests"); CreateBucketResponse bucketResponse = null; try { bucketResponse = s3UrlConnectionHttpClient.createBucket(b -> b.bucket(BUCKET_NAME)); s3UrlConnectionHttpClient.waiter().waitUntilBucketExists(b -> b.bucket(BUCKET_NAME)); RequestBody requestBody = RequestBody.fromBytes("helloworld".getBytes(StandardCharsets.UTF_8)); s3ApacheHttpClient.putObject(b -> b.bucket(BUCKET_NAME).key(KEY), requestBody); s3NettyClient.getObject(b -> b.bucket(BUCKET_NAME).key(KEY), AsyncResponseTransformer.toBytes()).join(); } finally { if (bucketResponse != null) { s3NettyClient.deleteObject(b -> b.bucket(BUCKET_NAME).key(KEY)).join(); s3NettyClient.deleteBucket(b -> b.bucket(BUCKET_NAME)).join(); } } } }
2,751
0
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth/sso/ProfileCredentialProviderTest.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.auth.sso; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.ProfileProviderCredentialsContext; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.sso.auth.SsoProfileCredentialsProviderFactory; import software.amazon.awssdk.utils.StringInputStream; public class ProfileCredentialProviderTest { private static Stream<Arguments> ssoTokenErrorValues() { // Session title is missing return Stream.of(Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_start_url=https//d-abc123.awsapps.com/start\n" + "sso_region=region") , "Unable to load SSO token"), Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_session=foo\n" + "[sso-session foo]\n" + "sso_region=region") , "Property 'sso_start_url' was not configured for profile 'test'"), Arguments.of(configFile("[profile test]\n" + "sso_account_id=accountId\n" + "sso_role_name=roleName\n" + "sso_region=region\n" + "sso_start_url=https//non-existing-Token/start") , "java.nio.file.NoSuchFileException") ); } private static ProfileFile configFile(String configFile) { return ProfileFile.builder() .content(new StringInputStream(configFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); } @ParameterizedTest @MethodSource("ssoTokenErrorValues") void validateSsoFactoryErrorWithIncorrectProfiles(ProfileFile profiles, String expectedValue) { assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { SsoProfileCredentialsProviderFactory factory = new SsoProfileCredentialsProviderFactory(); assertThatThrownBy(() -> factory.create(ProfileProviderCredentialsContext.builder() .profile(profile) .profileFile(profiles) .build())).hasMessageContaining(expectedValue); }); } }
2,752
0
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth/ssooidc/ProfileTokenProviderLoaderTest.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.auth.ssooidc; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.internal.ProfileTokenProviderLoader; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; class ProfileTokenProviderLoaderTest { @Test void profileTokenProviderLoader_noProfileFileSupplier_throwsException() { assertThatThrownBy(() -> new ProfileTokenProviderLoader(null, "sso'")) .hasMessageContaining("profileFile must not be null"); } @Test void profileTokenProviderLoader_noProfileName_throwsException() { assertThatThrownBy(() -> new ProfileTokenProviderLoader(ProfileFile::defaultProfileFile, null)) .hasMessageContaining("profileName must not be null"); } @ParameterizedTest @MethodSource("ssoErrorValues") void incorrectSsoProperties_supplier_delaysThrowingExceptionUntilResolvingToken(String profileContent, String msg) { ProfileFile profileFile = configFile(profileContent); Supplier<ProfileFile> supplier = () -> profileFile; ProfileTokenProviderLoader providerLoader = new ProfileTokenProviderLoader(supplier, "sso"); assertThatNoException().isThrownBy(providerLoader::tokenProvider); assertThat(providerLoader.tokenProvider()).satisfies(tokenProviderOptional -> { assertThat(tokenProviderOptional).isPresent().get().satisfies(tokenProvider-> { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(tokenProvider::resolveToken) .withMessageContaining(msg); }); }); } @Test void correctSsoProperties_createsTokenProvider() { String profileContent = "[profile sso]\n" + "sso_session=admin\n" + "[sso-session admin]\n" + "sso_region=us-east-1\n" + "sso_start_url=https://d-abc123.awsapps.com/start\n"; ProfileTokenProviderLoader providerLoader = new ProfileTokenProviderLoader(() -> configFile(profileContent), "sso"); Optional<SdkTokenProvider> tokenProvider = providerLoader.tokenProvider(); assertThat(tokenProvider).isPresent(); assertThatThrownBy(() -> tokenProvider.get().resolveToken()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load SSO token"); } private static Stream<Arguments> ssoErrorValues() { String ssoProfileConfigError = "Profile sso does not have sso_session property"; String ssoRegionErrorMsg = "Property 'sso_region' was not configured for profile"; String ssoStartUrlErrorMsg = "Property 'sso_start_url' was not configured for profile"; String sectionNotConfiguredError = "Sso-session section not found with sso-session title admin"; return Stream.of(Arguments.of("[profile sso]\n" , ssoProfileConfigError), Arguments.of("[profile sso]\n" + "sso_session=admin\n" + "[sso-session admin]\n" + "sso_start_url=https://d-abc123.awsapps.com/start\n", ssoRegionErrorMsg), Arguments.of("[profile sso]\n" + "sso_session=admin\n" + "[sso-session admin]\n" + "sso_region=us-east-1\n" , ssoStartUrlErrorMsg), Arguments.of("[profile sso]\n" + "sso_session=admin\n" + "[sso-session nonAdmin]\n" + "sso_start_url=https://d-abc123.awsapps.com/start\n", sectionNotConfiguredError)); } private ProfileFile configFile(String configFile) { return ProfileFile.builder() .content(new StringInputStream(configFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
2,753
0
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/test/auth-tests/src/it/java/software/amazon/awssdk/auth/sts/ProfileCredentialsProviderIntegrationTest.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.auth.sts; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.sts.model.StsException; import software.amazon.awssdk.utils.DateUtils; public class ProfileCredentialsProviderIntegrationTest { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private static final String CREDENTIALS_RESOURCE_PATH = "/latest/meta-data/iam/security-credentials/"; private static final String STUB_CREDENTIALS = "{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Expiration\":\"" + DateUtils.formatIso8601Date(Instant.now().plus(Duration.ofDays(1))) + "\"}"; @Test public void profileWithCredentialSourceUsingEc2InstanceMetadataAndCustomEndpoint_usesEndpointInSourceProfile() { String testFileContentsTemplate = "" + "[profile a]\n" + "role_arn=arn:aws:iam::123456789012:role/testRole3\n" + "credential_source = ec2instancemetadata\n" + "ec2_metadata_service_endpoint = http://localhost:%d\n"; WireMockServer mockMetadataEndpoint = new WireMockServer(WireMockConfiguration.options().dynamicPort()); mockMetadataEndpoint.start(); String profileFileContents = String.format(testFileContentsTemplate, mockMetadataEndpoint.port()); ProfileFile profileFile = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(new ByteArrayInputStream(profileFileContents.getBytes(StandardCharsets.UTF_8))) .build(); ProfileCredentialsProvider profileCredentialsProvider = ProfileCredentialsProvider.builder() .profileFile(profileFile) .profileName("a") .build(); String stubToken = "some-token"; mockMetadataEndpoint.stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody(stubToken))); mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).willReturn(aResponse().withBody("some-profile"))); mockMetadataEndpoint.stubFor(get(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).willReturn(aResponse().withBody(STUB_CREDENTIALS))); try { profileCredentialsProvider.resolveCredentials(); } catch (StsException e) { // ignored } finally { mockMetadataEndpoint.stop(); } String userAgentHeader = "User-Agent"; String userAgent = SdkUserAgent.create().userAgent(); mockMetadataEndpoint.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH)).withHeader(userAgentHeader, equalTo(userAgent))); mockMetadataEndpoint.verify(getRequestedFor(urlPathEqualTo(CREDENTIALS_RESOURCE_PATH + "some-profile")).withHeader(userAgentHeader, equalTo(userAgent))); } }
2,754
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/BenchmarkResultProcessor.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.benchmark; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OBJECT_MAPPER; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.compare; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.Statistics; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkParams; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkResult; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkStatistics; import software.amazon.awssdk.benchmark.utils.BenchmarkProcessorOutput; import software.amazon.awssdk.utils.Logger; /** * Process benchmark score, compare the result with the baseline score and return * the names of the benchmarks that exceed the baseline score. */ class BenchmarkResultProcessor { private static final Logger log = Logger.loggerFor(BenchmarkResultProcessor.class); private static final double TOLERANCE_LEVEL = 0.05; private Map<String, SdkBenchmarkResult> baseline; private List<String> failedBenchmarkIds = new ArrayList<>(); BenchmarkResultProcessor() { try { URL file = BenchmarkResultProcessor.class.getResource("baseline.json"); List<SdkBenchmarkResult> baselineResults = OBJECT_MAPPER.readValue(file, new TypeReference<List<SdkBenchmarkResult>>() {}); baseline = baselineResults.stream().collect(Collectors.toMap(SdkBenchmarkResult::getId, b -> b)); } catch (Exception e) { throw new RuntimeException("Not able to retrieve baseline result.", e); } } /** * Process benchmark results * * @param results the results of the benchmark * @return the benchmark results */ BenchmarkProcessorOutput processBenchmarkResult(Collection<RunResult> results) { Map<String, SdkBenchmarkResult> benchmarkResults = new HashMap<>(); for (RunResult result : results) { String benchmarkId = getBenchmarkId(result.getParams()); SdkBenchmarkResult sdkBenchmarkData = constructSdkBenchmarkResult(result); benchmarkResults.put(benchmarkId, sdkBenchmarkData); SdkBenchmarkResult baselineResult = baseline.get(benchmarkId); if (baselineResult == null) { log.warn(() -> { String benchmarkResultJson = null; try { benchmarkResultJson = OBJECT_MAPPER.writeValueAsString(sdkBenchmarkData); } catch (IOException e) { log.error(() -> "Unable to serialize result data to JSON"); } return String.format("Unable to find the baseline for %s. Skipping regression validation. " + "Results were: %s", benchmarkId, benchmarkResultJson); }); continue; } if (!validateBenchmarkResult(sdkBenchmarkData, baselineResult)) { failedBenchmarkIds.add(benchmarkId); } } BenchmarkProcessorOutput output = new BenchmarkProcessorOutput(benchmarkResults, failedBenchmarkIds); log.info(() -> "Current result: " + serializeResult(output)); return output; } private SdkBenchmarkResult constructSdkBenchmarkResult(RunResult runResult) { Statistics statistics = runResult.getPrimaryResult().getStatistics(); SdkBenchmarkStatistics sdkBenchmarkStatistics = new SdkBenchmarkStatistics(statistics); SdkBenchmarkParams sdkBenchmarkParams = new SdkBenchmarkParams(runResult.getParams()); return new SdkBenchmarkResult(getBenchmarkId(runResult.getParams()), sdkBenchmarkParams, sdkBenchmarkStatistics); } /** * Validate benchmark result by comparing it with baseline result statistically. * * @param baseline the baseline result * @param currentResult current result * @return true if current result is equal to or better than the baseline result statistically, false otherwise. */ private boolean validateBenchmarkResult(SdkBenchmarkResult currentResult, SdkBenchmarkResult baseline) { if (!validateBenchmarkParams(currentResult.getParams(), baseline.getParams())) { log.warn(() -> "Baseline result and current result are not comparable due to running from different environments." + "Skipping validation for " + currentResult.getId()); return true; } int comparison = compare(currentResult.getStatistics(), baseline.getStatistics()); log.debug(() -> "comparison result for " + baseline.getId() + " is " + comparison); switch (currentResult.getParams().getMode()) { case Throughput: if (comparison <= 0) { return true; } return withinTolerance(currentResult.getStatistics().getMean(), baseline.getStatistics().getMean()); case SampleTime: case AverageTime: case SingleShotTime: if (comparison >= 0) { return true; } return withinTolerance(currentResult.getStatistics().getMean(), baseline.getStatistics().getMean()); default: log.warn(() -> "Unsupported mode, skipping " + currentResult.getId()); return true; } } private boolean withinTolerance(double current, double baseline) { boolean positive = Math.abs(current - baseline) / baseline < TOLERANCE_LEVEL; log.info(() -> "current: " + current + " baseline: " + baseline + "The relative difference is within tolerance? " + positive); return positive; } private String getBenchmarkId(BenchmarkParams params) { return params.id().replaceFirst("software.amazon.awssdk.benchmark.", ""); } private boolean validateBenchmarkParams(SdkBenchmarkParams current, SdkBenchmarkParams baseline) { if (!Objects.equals(current.getJdkVersion(), baseline.getJdkVersion())) { log.warn(() -> "The current benchmark result was generated from a different Jdk version than the one of the " + "baseline, so the results might not be comparable"); return true; } return current.getMode() == baseline.getMode(); } private String serializeResult(BenchmarkProcessorOutput processorOutput) { try { return OBJECT_MAPPER.writeValueAsString(processorOutput); } catch (JsonProcessingException e) { log.error(() -> "Failed to serialize current result", e); } return null; } }
2,755
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/BenchmarkRunner.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.benchmark; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OBJECT_MAPPER; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.ChainedOptionsBuilder; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.apicall.MetricsEnabledBenchmark; import software.amazon.awssdk.benchmark.apicall.httpclient.async.AwsCrtClientBenchmark; import software.amazon.awssdk.benchmark.apicall.httpclient.async.NettyHttpClientH1Benchmark; import software.amazon.awssdk.benchmark.apicall.httpclient.async.NettyHttpClientH2Benchmark; import software.amazon.awssdk.benchmark.apicall.httpclient.sync.ApacheHttpClientBenchmark; import software.amazon.awssdk.benchmark.apicall.httpclient.sync.UrlConnectionHttpClientBenchmark; import software.amazon.awssdk.benchmark.apicall.protocol.Ec2ProtocolBenchmark; import software.amazon.awssdk.benchmark.apicall.protocol.JsonProtocolBenchmark; import software.amazon.awssdk.benchmark.apicall.protocol.QueryProtocolBenchmark; import software.amazon.awssdk.benchmark.apicall.protocol.XmlProtocolBenchmark; import software.amazon.awssdk.benchmark.coldstart.V2DefaultClientCreationBenchmark; import software.amazon.awssdk.benchmark.coldstart.V2OptimizedClientCreationBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientDeleteV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientGetOverheadBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientGetV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientPutOverheadBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientPutV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientQueryV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientScanV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.enhanced.dynamodb.EnhancedClientUpdateV1MapperComparisonBenchmark; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkResult; import software.amazon.awssdk.benchmark.utils.BenchmarkProcessorOutput; import software.amazon.awssdk.utils.Logger; public class BenchmarkRunner { private static final List<String> PROTOCOL_BENCHMARKS = Arrays.asList( Ec2ProtocolBenchmark.class.getSimpleName(), JsonProtocolBenchmark.class.getSimpleName(), QueryProtocolBenchmark.class.getSimpleName(), XmlProtocolBenchmark.class.getSimpleName()); private static final List<String> ASYNC_BENCHMARKS = Arrays.asList( NettyHttpClientH2Benchmark.class.getSimpleName(), NettyHttpClientH1Benchmark.class.getSimpleName(), AwsCrtClientBenchmark.class.getSimpleName()); private static final List<String> SYNC_BENCHMARKS = Arrays.asList( ApacheHttpClientBenchmark.class.getSimpleName(), UrlConnectionHttpClientBenchmark.class.getSimpleName()); private static final List<String> COLD_START_BENCHMARKS = Arrays.asList( V2OptimizedClientCreationBenchmark.class.getSimpleName(), V2DefaultClientCreationBenchmark.class.getSimpleName()); private static final List<String> MAPPER_BENCHMARKS = Arrays.asList( EnhancedClientGetOverheadBenchmark.class.getSimpleName(), EnhancedClientPutOverheadBenchmark.class.getSimpleName(), EnhancedClientGetV1MapperComparisonBenchmark.class.getSimpleName(), EnhancedClientPutV1MapperComparisonBenchmark.class.getSimpleName(), EnhancedClientUpdateV1MapperComparisonBenchmark.class.getSimpleName(), EnhancedClientDeleteV1MapperComparisonBenchmark.class.getSimpleName(), EnhancedClientScanV1MapperComparisonBenchmark.class.getSimpleName(), EnhancedClientQueryV1MapperComparisonBenchmark.class.getSimpleName() ); private static final List<String> METRIC_BENCHMARKS = Arrays.asList(MetricsEnabledBenchmark.class.getSimpleName()); private static final Logger log = Logger.loggerFor(BenchmarkRunner.class); private final List<String> benchmarksToRun; private final BenchmarkResultProcessor resultProcessor; private final BenchmarkRunnerOptions options; private BenchmarkRunner(List<String> benchmarksToRun, BenchmarkRunnerOptions options) { this.benchmarksToRun = benchmarksToRun; this.resultProcessor = new BenchmarkResultProcessor(); this.options = options; } public static void main(String... args) throws Exception { List<String> benchmarksToRun = new ArrayList<>(); benchmarksToRun.addAll(SYNC_BENCHMARKS); benchmarksToRun.addAll(ASYNC_BENCHMARKS); benchmarksToRun.addAll(PROTOCOL_BENCHMARKS); benchmarksToRun.addAll(COLD_START_BENCHMARKS); log.info(() -> "Skipping tests, to reduce benchmark times: \n" + MAPPER_BENCHMARKS + "\n" + METRIC_BENCHMARKS); BenchmarkRunner runner = new BenchmarkRunner(benchmarksToRun, parseOptions(args)); runner.runBenchmark(); } private void runBenchmark() throws RunnerException { log.info(() -> "Running with options: " + options); ChainedOptionsBuilder optionsBuilder = new OptionsBuilder(); benchmarksToRun.forEach(optionsBuilder::include); log.info(() -> "Starting to run: " + benchmarksToRun); Collection<RunResult> results = new Runner(optionsBuilder.build()).run(); BenchmarkProcessorOutput processedResults = resultProcessor.processBenchmarkResult(results); List<String> failedResults = processedResults.getFailedBenchmarks(); if (options.outputPath != null) { log.info(() -> "Writing results to " + options.outputPath); writeResults(processedResults, options.outputPath); } if (options.check && !failedResults.isEmpty()) { log.info(() -> "Failed perf regression tests: " + failedResults); throw new RuntimeException("Perf regression tests failed: " + failedResults); } } private static BenchmarkRunnerOptions parseOptions(String[] args) throws ParseException { Options cliOptions = new Options(); cliOptions.addOption("o", "output", true, "The path to write the benchmark results to."); cliOptions.addOption("c", "check", false, "If specified, exit with error code 1 if the results are not within the baseline."); CommandLineParser parser = new DefaultParser(); CommandLine cmdLine = parser.parse(cliOptions, args); BenchmarkRunnerOptions options = new BenchmarkRunnerOptions() .check(cmdLine.hasOption("c")); if (cmdLine.hasOption("o")) { options.outputPath(Paths.get(cmdLine.getOptionValue("o"))); } return options; } private static void writeResults(BenchmarkProcessorOutput output, Path outputPath) { List<SdkBenchmarkResult> results = output.getBenchmarkResults().values().stream().collect(Collectors.toList()); try (OutputStream os = Files.newOutputStream(outputPath)) { OBJECT_MAPPER.writeValue(os, results); } catch (IOException e) { log.error(() -> "Failed to write the results to " + outputPath, e); throw new RuntimeException(e); } } private static class BenchmarkRunnerOptions { private Path outputPath; private boolean check; public BenchmarkRunnerOptions outputPath(Path outputPath) { this.outputPath = outputPath; return this; } public BenchmarkRunnerOptions check(boolean check) { this.check = check; return this; } @Override public String toString() { return "BenchmarkRunnerOptions{" + "outputPath=" + outputPath + ", check=" + check + '}'; } } }
2,756
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/MetricsEnabledBenchmark.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.benchmark.apicall; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.client.builder.SdkClientBuilder; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClientBuilder; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClientBuilder; import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationRequest; import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest; /** * Benchmarking comparing metrics-enabled versus metrics-disabled performance. */ @State(Scope.Benchmark) @BenchmarkMode(Mode.Throughput) public class MetricsEnabledBenchmark { private MockServer mockServer; private ProtocolRestJsonClient enabledMetricsSyncClient; private ProtocolRestJsonAsyncClient enabledMetricsAsyncClient; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); enabledMetricsSyncClient = enableMetrics(syncClientBuilder()).build(); enabledMetricsAsyncClient = enableMetrics(asyncClientBuilder()).build(); } private <T extends SdkClientBuilder<T, ?>> T enableMetrics(T syncClientBuilder) { return syncClientBuilder.overrideConfiguration(c -> c.addMetricPublisher(new EnabledPublisher())); } private ProtocolRestJsonClientBuilder syncClientBuilder() { return ProtocolRestJsonClient.builder() .endpointOverride(mockServer.getHttpUri()) .httpClientBuilder(ApacheHttpClient.builder()); } private ProtocolRestJsonAsyncClientBuilder asyncClientBuilder() { return ProtocolRestJsonAsyncClient.builder() .endpointOverride(mockServer.getHttpUri()) .httpClientBuilder(NettyNioAsyncHttpClient.builder()); } @TearDown(Level.Trial) public void tearDown() throws Exception { mockServer.stop(); enabledMetricsSyncClient.close(); enabledMetricsAsyncClient.close(); } @Benchmark public void metricsEnabledSync() { enabledMetricsSyncClient.allTypes(); } @Benchmark public void metricsEnabledAsync() { enabledMetricsAsyncClient.allTypes().join(); } @Benchmark public void metricsEnabledSyncStreamingInput() { enabledMetricsSyncClient.streamingInputOperation(streamingInputRequest(), RequestBody.fromString("")); } @Benchmark public void metricsEnabledAsyncStreamingInput() { enabledMetricsAsyncClient.streamingInputOperation(streamingInputRequest(), AsyncRequestBody.fromString("")).join(); } @Benchmark public void metricsEnabledSyncStreamingOutput() { enabledMetricsSyncClient.streamingOutputOperationAsBytes(streamingOutputRequest()); } @Benchmark public void metricsEnabledAsyncStreamingOutput() { enabledMetricsAsyncClient.streamingOutputOperation(streamingOutputRequest(), AsyncResponseTransformer.toBytes()).join(); } private StreamingInputOperationRequest streamingInputRequest() { return StreamingInputOperationRequest.builder().build(); } private StreamingOutputOperationRequest streamingOutputRequest() { return StreamingOutputOperationRequest.builder().build(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(MetricsEnabledBenchmark.class.getSimpleName()) .build(); new Runner(opt).run(); } private static final class EnabledPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { } @Override public void close() { } } }
2,757
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/SdkHttpClientBenchmark.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.benchmark.apicall.httpclient; import org.openjdk.jmh.infra.Blackhole; /** * Interface to be used for sdk http client benchmark */ public interface SdkHttpClientBenchmark { /** * Benchmark for sequential api calls * * @param blackhole the blackhole */ void sequentialApiCall(Blackhole blackhole); /** * Benchmark for concurrent api calls. * * <p>Not applies to all sdk http clients such as UrlConnectionHttpClient. * Running with UrlConnectionHttpClient has high error rate because it doesn't * support connection pooling. * * @param blackhole the blackhole */ default void concurrentApiCall(Blackhole blackhole) { } }
2,758
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/NettyHttpClientH2Benchmark.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.benchmark.apicall.httpclient.async; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.DEFAULT_JDK_SSL_PROVIDER; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OPEN_SSL_PROVIDER; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.getSslProvider; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.trustAllTlsAttributeMapBuilder; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.PROTOCOL; import io.netty.handler.ssl.SslProvider; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockH2Server; import software.amazon.awssdk.http.Protocol; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; /** * Using netty client to test against local http2 server. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class NettyHttpClientH2Benchmark extends BaseNettyBenchmark { private MockH2Server mockServer; private SdkAsyncHttpClient sdkHttpClient; @Param({DEFAULT_JDK_SSL_PROVIDER, OPEN_SSL_PROVIDER}) private String sslProviderValue; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockH2Server(false); mockServer.start(); SslProvider sslProvider = getSslProvider(sslProviderValue); sdkHttpClient = NettyNioAsyncHttpClient.builder() .sslProvider(sslProvider) .buildWithDefaults(trustAllTlsAttributeMapBuilder() .put(PROTOCOL, Protocol.HTTP2) .build()); client = ProtocolRestJsonAsyncClient.builder() .endpointOverride(mockServer.getHttpsUri()) .httpClient(sdkHttpClient) .build(); // Making sure the request actually succeeds client.allTypes().join(); } @TearDown(Level.Trial) public void tearDown() throws Exception { mockServer.stop(); sdkHttpClient.close(); client.close(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(NettyHttpClientH2Benchmark.class.getSimpleName()) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,759
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/NettyHttpClientH1Benchmark.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.benchmark.apicall.httpclient.async; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.DEFAULT_JDK_SSL_PROVIDER; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OPEN_SSL_PROVIDER; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.getSslProvider; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.trustAllTlsAttributeMapBuilder; import io.netty.handler.ssl.SslProvider; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; /** * Using netty client to test against local mock https server. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class NettyHttpClientH1Benchmark extends BaseNettyBenchmark { private MockServer mockServer; private SdkAsyncHttpClient sdkHttpClient; @Param({DEFAULT_JDK_SSL_PROVIDER, OPEN_SSL_PROVIDER}) private String sslProviderValue; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); SslProvider sslProvider = getSslProvider(sslProviderValue); sdkHttpClient = NettyNioAsyncHttpClient.builder() .sslProvider(sslProvider) .buildWithDefaults(trustAllTlsAttributeMapBuilder().build()); client = ProtocolRestJsonAsyncClient.builder() .endpointOverride(mockServer.getHttpsUri()) .httpClient(sdkHttpClient) .build(); // Making sure the request actually succeeds client.allTypes().join(); } @TearDown(Level.Trial) public void tearDown() throws Exception { mockServer.stop(); sdkHttpClient.close(); client.close(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(NettyHttpClientH1Benchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,760
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/NettyClientH1NonTlsBenchmark.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.benchmark.apicall.httpclient.async; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; /** * Using netty client to test against local mock http server. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class NettyClientH1NonTlsBenchmark extends BaseNettyBenchmark { private MockServer mockServer; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); client = ProtocolRestJsonAsyncClient.builder() .endpointOverride(mockServer.getHttpUri()) .build(); // Making sure the request actually succeeds client.allTypes().join(); } @TearDown(Level.Trial) public void tearDown() throws Exception { mockServer.stop(); client.close(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(NettyClientH1NonTlsBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,761
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/BaseNettyBenchmark.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.benchmark.apicall.httpclient.async; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.CONCURRENT_CALLS; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.awaitCountdownLatchUninterruptibly; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.countDownUponCompletion; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.benchmark.apicall.httpclient.SdkHttpClientBenchmark; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; /** * Base class for netty benchmark */ public abstract class BaseNettyBenchmark implements SdkHttpClientBenchmark { protected ProtocolRestJsonAsyncClient client; @Override @Benchmark @OperationsPerInvocation(CONCURRENT_CALLS) public void concurrentApiCall(Blackhole blackhole) { CountDownLatch countDownLatch = new CountDownLatch(CONCURRENT_CALLS); for (int i = 0; i < CONCURRENT_CALLS; i++) { countDownUponCompletion(blackhole, client.allTypes(), countDownLatch); } awaitCountdownLatchUninterruptibly(countDownLatch, 10, TimeUnit.SECONDS); } @Override @Benchmark public void sequentialApiCall(Blackhole blackhole) { CountDownLatch countDownLatch = new CountDownLatch(1); countDownUponCompletion(blackhole, client.allTypes(), countDownLatch); awaitCountdownLatchUninterruptibly(countDownLatch, 1, TimeUnit.SECONDS); } }
2,762
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/BaseCrtBenchmark.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.benchmark.apicall.httpclient.async; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.CONCURRENT_CALLS; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.awaitCountdownLatchUninterruptibly; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.countDownUponCompletion; import java.net.URI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.benchmark.apicall.httpclient.SdkHttpClientBenchmark; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.crt.AwsCrtAsyncHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient; import software.amazon.awssdk.utils.AttributeMap; /** * Shared code between http and https benchmarks */ public abstract class BaseCrtBenchmark implements SdkHttpClientBenchmark { private MockServer mockServer; private SdkAsyncHttpClient sdkHttpClient; private ProtocolRestJsonAsyncClient client; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); AttributeMap trustAllCerts = AttributeMap.builder() .put(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, Boolean.TRUE) .build(); sdkHttpClient = AwsCrtAsyncHttpClient.builder() .buildWithDefaults(trustAllCerts); client = ProtocolRestJsonAsyncClient.builder() .endpointOverride(getEndpointOverride(mockServer)) .httpClient(sdkHttpClient) .build(); // Making sure the request actually succeeds client.allTypes().join(); } @TearDown(Level.Trial) public void tearDown() throws Exception { mockServer.stop(); client.close(); sdkHttpClient.close(); } @Override @Benchmark @OperationsPerInvocation(CONCURRENT_CALLS) public void concurrentApiCall(Blackhole blackhole) { CountDownLatch countDownLatch = new CountDownLatch(CONCURRENT_CALLS); for (int i = 0; i < CONCURRENT_CALLS; i++) { countDownUponCompletion(blackhole, client.allTypes(), countDownLatch); } awaitCountdownLatchUninterruptibly(countDownLatch, 10, TimeUnit.SECONDS); } @Override @Benchmark public void sequentialApiCall(Blackhole blackhole) { CountDownLatch countDownLatch = new CountDownLatch(1); countDownUponCompletion(blackhole, client.allTypes(), countDownLatch); awaitCountdownLatchUninterruptibly(countDownLatch, 1, TimeUnit.SECONDS); } protected abstract URI getEndpointOverride(MockServer mock); }
2,763
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/AwsCrtClientNonTlsBenchmark.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.benchmark.apicall.httpclient.async; import java.net.URI; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockServer; /** * Using aws-crt-client to test against local mock https server. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class AwsCrtClientNonTlsBenchmark extends BaseCrtBenchmark { @Override protected URI getEndpointOverride(MockServer mock) { return mock.getHttpUri(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(AwsCrtClientNonTlsBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,764
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/async/AwsCrtClientBenchmark.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.benchmark.apicall.httpclient.async; import java.net.URI; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockServer; /** * Using aws-crt-client to test against local mock https server. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class AwsCrtClientBenchmark extends BaseCrtBenchmark { @Override protected URI getEndpointOverride(MockServer mock) { return mock.getHttpsUri(); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(AwsCrtClientBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,765
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/sync/ApacheHttpClientBenchmark.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.benchmark.apicall.httpclient.sync; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.CONCURRENT_CALLS; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.awaitCountdownLatchUninterruptibly; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.countDownUponCompletion; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.trustAllTlsAttributeMapBuilder; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.apicall.httpclient.SdkHttpClientBenchmark; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; /** * Benchmarking for running with different http clients. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class ApacheHttpClientBenchmark implements SdkHttpClientBenchmark { private MockServer mockServer; private SdkHttpClient sdkHttpClient; private ProtocolRestJsonClient client; private ExecutorService executorService; @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); sdkHttpClient = ApacheHttpClient.builder() .buildWithDefaults(trustAllTlsAttributeMapBuilder().build()); client = ProtocolRestJsonClient.builder() .endpointOverride(mockServer.getHttpsUri()) .httpClient(sdkHttpClient) .build(); executorService = Executors.newFixedThreadPool(CONCURRENT_CALLS); client.allTypes(); } @TearDown(Level.Trial) public void tearDown() throws Exception { executorService.shutdown(); mockServer.stop(); sdkHttpClient.close(); client.close(); } @Benchmark @Override public void sequentialApiCall(Blackhole blackhole) { blackhole.consume(client.allTypes()); } @Benchmark @Override @OperationsPerInvocation(CONCURRENT_CALLS) public void concurrentApiCall(Blackhole blackhole) { CountDownLatch countDownLatch = new CountDownLatch(CONCURRENT_CALLS); for (int i = 0; i < CONCURRENT_CALLS; i++) { countDownUponCompletion(blackhole, CompletableFuture.runAsync(() -> client.allTypes(), executorService), countDownLatch); } awaitCountdownLatchUninterruptibly(countDownLatch, 10, TimeUnit.SECONDS); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(ApacheHttpClientBenchmark.class.getSimpleName() + ".concurrentApiCall") .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,766
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/httpclient/sync/UrlConnectionHttpClientBenchmark.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.benchmark.apicall.httpclient.sync; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.CONCURRENT_CALLS; import static software.amazon.awssdk.benchmark.utils.BenchmarkUtils.trustAllTlsAttributeMapBuilder; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.apicall.httpclient.SdkHttpClientBenchmark; import software.amazon.awssdk.benchmark.utils.MockServer; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; /** * Benchmarking for running with different http clients. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class UrlConnectionHttpClientBenchmark implements SdkHttpClientBenchmark { private MockServer mockServer; private SdkHttpClient sdkHttpClient; private ProtocolRestJsonClient client; private ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_CALLS); @Setup(Level.Trial) public void setup() throws Exception { mockServer = new MockServer(); mockServer.start(); sdkHttpClient = UrlConnectionHttpClient.builder() .buildWithDefaults(trustAllTlsAttributeMapBuilder().build()); client = ProtocolRestJsonClient.builder() .endpointOverride(mockServer.getHttpsUri()) .httpClient(sdkHttpClient) .build(); client.allTypes(); } @TearDown(Level.Trial) public void tearDown() throws Exception { executorService.shutdown(); mockServer.stop(); sdkHttpClient.close(); client.close(); } @Benchmark @Override public void sequentialApiCall(Blackhole blackhole) { blackhole.consume(client.allTypes()); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(UrlConnectionHttpClientBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,767
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/protocol/SdkProtocolBenchmark.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.benchmark.apicall.protocol; import org.openjdk.jmh.infra.Blackhole; public interface SdkProtocolBenchmark { void successfulResponse(Blackhole blackhole); //TODO, implement it and remove default default void failedRepsonse(Blackhole blackhole) { } }
2,768
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/protocol/QueryProtocolBenchmark.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.benchmark.apicall.protocol; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.ERROR_XML_BODY; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.QUERY_ALL_TYPES_REQUEST; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.XML_BODY; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockHttpClient; import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient; /** * Benchmarking for running with different protocols. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class QueryProtocolBenchmark implements SdkProtocolBenchmark { private ProtocolQueryClient client; @Setup(Level.Trial) public void setup() { client = ProtocolQueryClient.builder() .httpClient(new MockHttpClient(XML_BODY, ERROR_XML_BODY)) .build(); } @Override @Benchmark public void successfulResponse(Blackhole blackhole) { blackhole.consume(client.allTypes(QUERY_ALL_TYPES_REQUEST)); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(QueryProtocolBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,769
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/protocol/Ec2ProtocolBenchmark.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.benchmark.apicall.protocol; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.EC2_ALL_TYPES_REQUEST; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.ERROR_XML_BODY; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.XML_BODY; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockHttpClient; import software.amazon.awssdk.services.protocolec2.ProtocolEc2Client; /** * Benchmarking for running with different protocols. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class Ec2ProtocolBenchmark implements SdkProtocolBenchmark { private ProtocolEc2Client client; @Setup(Level.Trial) public void setup() { client = ProtocolEc2Client.builder() .httpClient(new MockHttpClient(XML_BODY, ERROR_XML_BODY)) .build(); } @Override @Benchmark public void successfulResponse(Blackhole blackhole) { blackhole.consume(client.allTypes(EC2_ALL_TYPES_REQUEST)); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(Ec2ProtocolBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,770
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/protocol/XmlProtocolBenchmark.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.benchmark.apicall.protocol; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.ERROR_XML_BODY; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.XML_ALL_TYPES_REQUEST; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.XML_BODY; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockHttpClient; import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient; /** * Benchmarking for running with different protocols. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class XmlProtocolBenchmark implements SdkProtocolBenchmark { private ProtocolRestXmlClient client; @Setup(Level.Trial) public void setup() { client = ProtocolRestXmlClient.builder() .httpClient(new MockHttpClient(XML_BODY, ERROR_XML_BODY)) .build(); } @Override @Benchmark public void successfulResponse(Blackhole blackhole) { blackhole.consume(client.allTypes(XML_ALL_TYPES_REQUEST)); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(XmlProtocolBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,771
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/apicall/protocol/JsonProtocolBenchmark.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.benchmark.apicall.protocol; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.ERROR_JSON_BODY; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.JSON_ALL_TYPES_REQUEST; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.JSON_BODY; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.benchmark.utils.MockHttpClient; import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient; /** * Benchmarking for running with different protocols. */ @State(Scope.Benchmark) @Warmup(iterations = 3, time = 15, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 10, timeUnit = TimeUnit.SECONDS) @Fork(2) // To reduce difference between each run @BenchmarkMode(Mode.Throughput) public class JsonProtocolBenchmark implements SdkProtocolBenchmark { private ProtocolRestJsonClient client; @Setup(Level.Trial) public void setup() { client = ProtocolRestJsonClient.builder() .httpClient(new MockHttpClient(JSON_BODY, ERROR_JSON_BODY)) .build(); } @Override @Benchmark public void successfulResponse(Blackhole blackhole) { blackhole.consume(client.allTypes(JSON_ALL_TYPES_REQUEST)); } public static void main(String... args) throws Exception { Options opt = new OptionsBuilder() .include(JsonProtocolBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); new Runner(opt).run(); } }
2,772
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V2DefaultClientCreationBenchmark.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.benchmark.coldstart; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.CommandLineOptionException; import org.openjdk.jmh.runner.options.CommandLineOptions; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * Benchmark for creating the clients */ @State(Scope.Benchmark) @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 3) @Measurement(iterations = 5) @Fork(3) public class V2DefaultClientCreationBenchmark implements SdkClientCreationBenchmark { private DynamoDbClient client; @Override @Benchmark public void createClient(Blackhole blackhole) throws Exception { client = DynamoDbClient.builder() .endpointDiscoveryEnabled(false) .httpClient(ApacheHttpClient.builder().build()).build(); blackhole.consume(client); } @TearDown(Level.Trial) public void tearDown() throws Exception { if (client != null) { client.close(); } } public static void main(String... args) throws RunnerException, CommandLineOptionException { Options opt = new OptionsBuilder() .parent(new CommandLineOptions()) .include(V2DefaultClientCreationBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,773
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V1ClientCreationBenchmark.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.benchmark.coldstart; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.CommandLineOptionException; import org.openjdk.jmh.runner.options.CommandLineOptions; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; /** * Benchmark for creating the clients */ @State(Scope.Benchmark) @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 3) @Measurement(iterations = 5) @Fork(3) public class V1ClientCreationBenchmark implements SdkClientCreationBenchmark { private AmazonDynamoDB client; @Override @Benchmark public void createClient(Blackhole blackhole) throws Exception { client = AmazonDynamoDBClient.builder().build(); blackhole.consume(client); } @TearDown(Level.Trial) public void tearDown() throws Exception { if (client != null) { client.shutdown(); } } public static void main(String... args) throws RunnerException, CommandLineOptionException { Options opt = new OptionsBuilder() .parent(new CommandLineOptions()) .include(V1ClientCreationBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,774
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/SdkClientCreationBenchmark.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.benchmark.coldstart; import org.openjdk.jmh.infra.Blackhole; public interface SdkClientCreationBenchmark { void createClient(Blackhole blackhole) throws Exception; }
2,775
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/coldstart/V2OptimizedClientCreationBenchmark.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.benchmark.coldstart; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.CommandLineOptionException; import org.openjdk.jmh.runner.options.CommandLineOptions; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * Benchmark for creating the clients */ @State(Scope.Benchmark) @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 3) @Measurement(iterations = 5) @Fork(3) public class V2OptimizedClientCreationBenchmark implements SdkClientCreationBenchmark { private DynamoDbClient client; @Override @Benchmark public void createClient(Blackhole blackhole) throws Exception { client = DynamoDbClient.builder() .region(Region.US_WEST_2) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("test", "test"))) .httpClient(ApacheHttpClient.builder().build()) .overrideConfiguration(ClientOverrideConfiguration.builder().build()) .endpointDiscoveryEnabled(false) .build(); blackhole.consume(client); } @TearDown(Level.Trial) public void tearDown() throws Exception { if (client != null) { client.close(); } } public static void main(String... args) throws RunnerException, CommandLineOptionException { Options opt = new OptionsBuilder() .parent(new CommandLineOptions()) .include(V2OptimizedClientCreationBenchmark.class.getSimpleName()) .addProfiler(StackProfiler.class) .build(); Collection<RunResult> run = new Runner(opt).run(); } }
2,776
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockH2Server.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.benchmark.utils; import java.io.IOException; import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; import org.eclipse.jetty.http2.HTTP2Cipher; import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory; import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; /** * Local h2 server used to stub fixed response. * * See: * https://git.eclipse.org/c/jetty/org.eclipse.jetty.project * .git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/Http2Server.java */ public class MockH2Server extends BaseMockServer { private final Server server; public MockH2Server(boolean usingAlpn) throws IOException { super(); server = new Server(); ServerConnector connector = new ServerConnector(server); connector.setPort(httpPort); // HTTP Configuration HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSecureScheme("https"); httpConfiguration.setSecurePort(httpsPort); httpConfiguration.setSendXPoweredBy(true); httpConfiguration.setSendServerVersion(true); // HTTP Connector ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration), new HTTP2CServerConnectionFactory(httpConfiguration)); http.setPort(httpPort); server.addConnector(http); // HTTPS Configuration HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); // SSL Context Factory for HTTPS and HTTP/2 SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setTrustAll(true); sslContextFactory.setValidateCerts(false); sslContextFactory.setNeedClientAuth(false); sslContextFactory.setWantClientAuth(false); sslContextFactory.setValidatePeerCerts(false); sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR); sslContextFactory.setKeyStorePassword("password"); sslContextFactory.setKeyStorePath(MockServer.class.getResource("mock-keystore.jks").toExternalForm()); // HTTP/2 Connection Factory HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(https); // SSL Connection Factory SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "h2"); ServerConnector http2Connector; if (usingAlpn) { ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); alpn.setDefaultProtocol("h2"); // HTTP/2 Connector http2Connector = new ServerConnector(server, ssl, alpn, h2, new HttpConnectionFactory(https)); } else { http2Connector = new ServerConnector(server, ssl, h2, new HttpConnectionFactory(https)); } http2Connector.setPort(httpsPort); server.addConnector(http2Connector); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new AlwaysSuccessServlet()), "/*"); server.setHandler(context); } public void start() throws Exception { server.start(); } public void stop() throws Exception { server.stop(); } }
2,777
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkProcessorOutput.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.benchmark.utils; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.List; import java.util.Map; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkResult; /** * The output object of the benchmark processor. This contains the results of the all the benchmarks that were run, and the * list of benchmarks that failed. */ public final class BenchmarkProcessorOutput { private final Map<String, SdkBenchmarkResult> benchmarkResults; private final List<String> failedBenchmarks; @JsonCreator public BenchmarkProcessorOutput(Map<String, SdkBenchmarkResult> benchmarkResults, List<String> failedBenchmarks) { this.benchmarkResults = benchmarkResults; this.failedBenchmarks = failedBenchmarks; } public Map<String, SdkBenchmarkResult> getBenchmarkResults() { return benchmarkResults; } public List<String> getFailedBenchmarks() { return failedBenchmarks; } }
2,778
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkUtils.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.benchmark.utils; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.DEFAULT_JDK_SSL_PROVIDER; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.OPEN_SSL_PROVIDER; import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslProvider; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.math3.stat.inference.TestUtils; import org.openjdk.jmh.infra.Blackhole; import org.openjdk.jmh.util.Statistics; import software.amazon.awssdk.benchmark.stats.SdkBenchmarkStatistics; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.Logger; /** * Contains utilities methods used by the benchmarks */ public final class BenchmarkUtils { private static final Logger logger = Logger.loggerFor(BenchmarkConstant.class); private BenchmarkUtils() { } public static void countDownUponCompletion(Blackhole blackhole, CompletableFuture<?> completableFuture, CountDownLatch countDownLatch) { completableFuture.whenComplete((r, t) -> { if (t != null) { logger.error(() -> "Exception returned from the response ", t); blackhole.consume(t); } else { blackhole.consume(r); } countDownLatch.countDown(); }); } public static SslProvider getSslProvider(String sslProviderValue) { switch (sslProviderValue) { case DEFAULT_JDK_SSL_PROVIDER: return SslProvider.JDK; case OPEN_SSL_PROVIDER: return SslProvider.OPENSSL; default: return SslContext.defaultClientProvider(); } } public static void awaitCountdownLatchUninterruptibly(CountDownLatch countDownLatch, int timeout, TimeUnit unit) { try { if (!countDownLatch.await(timeout, unit)) { throw new RuntimeException("Countdown latch did not successfully return within " + timeout + " " + unit); } } catch (InterruptedException e) { // No need to re-interrupt. logger.error(() -> "InterruptedException thrown ", e); } } public static AttributeMap.Builder trustAllTlsAttributeMapBuilder() { return AttributeMap.builder().put(TRUST_ALL_CERTIFICATES, true); } /** * Returns an unused port in the localhost. */ public static int getUnusedPort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); return socket.getLocalPort(); } } /** * Compare the results statistically. * * See {@link Statistics#compareTo(Statistics, double)} * * @param current the current result * @param other the other result to compare with * @param confidence the confidence level * @return a negative integer, zero, or a positive integer as this statistics * is less than, equal to, or greater than the specified statistics. */ public static int compare(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other, double confidence) { if (isDifferent(current, other, confidence)) { logger.info(() -> "isDifferent ? " + true); double t = current.getMean(); double o = other.getMean(); return (t > o) ? -1 : 1; } return 0; } /** * See {@link Statistics#compareTo(Statistics)} */ public static int compare(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other) { return compare(current, other, 0.99); } private static boolean isDifferent(SdkBenchmarkStatistics current, SdkBenchmarkStatistics other, double confidence) { return TestUtils.tTest(current, other, 1 - confidence); } }
2,779
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockHttpClient.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.benchmark.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpResponse; /** * Mock implementation of {@link SdkHttpClient} to return mock response. */ public final class MockHttpClient implements SdkHttpClient { private String successResponseContent; private String errorResponseContent; public MockHttpClient(String successResponseContent, String errorResponseContent) { this.successResponseContent = successResponseContent; this.errorResponseContent = errorResponseContent; } @Override public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) { if (request.httpRequest().firstMatchingHeader("stub-error").isPresent()) { return new MockHttpRequest(errorResponse()); } return new MockHttpRequest(successResponse()); } @Override public void close() { } private class MockHttpRequest implements ExecutableHttpRequest { private final HttpExecuteResponse response; private MockHttpRequest(HttpExecuteResponse response) { this.response = response; } @Override public HttpExecuteResponse call() throws IOException { return response; } @Override public void abort() { } } private HttpExecuteResponse successResponse() { AbortableInputStream inputStream = AbortableInputStream.create(new ByteArrayInputStream(successResponseContent.getBytes())); return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .responseBody(inputStream) .build(); } private HttpExecuteResponse errorResponse() { AbortableInputStream inputStream = AbortableInputStream.create(new ByteArrayInputStream(errorResponseContent.getBytes())); return HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(500) .build()) .responseBody(inputStream) .build(); } }
2,780
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/AlwaysSuccessServlet.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.benchmark.utils; import static software.amazon.awssdk.benchmark.utils.BenchmarkConstant.JSON_BODY; import java.io.IOException; import java.nio.charset.StandardCharsets; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; /** * Always succeeds with with a 200 response. */ public class AlwaysSuccessServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpStatus.OK_200); response.setContentType("application/json"); response.setContentLength(JSON_BODY.getBytes(StandardCharsets.UTF_8).length); response.getOutputStream().print(JSON_BODY); } }
2,781
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BenchmarkConstant.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.benchmark.utils; import com.fasterxml.jackson.databind.ObjectMapper; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.protocolec2.model.AllTypesRequest; /** * Contains constants used by the benchmarks */ @SuppressWarnings("unchecked") public final class BenchmarkConstant { public static final String DEFAULT_JDK_SSL_PROVIDER = "jdk"; public static final String OPEN_SSL_PROVIDER = "openssl"; public static final int CONCURRENT_CALLS = 50; public static final Instant TIMESTAMP_MEMBER = LocalDateTime.now().toInstant(ZoneOffset.UTC); public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public static final String ERROR_JSON_BODY = "{}"; public static final String JSON_BODY = "{\"StringMember\":\"foo\",\"IntegerMember\":123,\"BooleanMember\":true," + "\"FloatMember\":123.0,\"DoubleMember\":123.9,\"LongMember\":123," + "\"SimpleList\":[\"so simple\"]," + "\"ListOfStructs\":[{\"StringMember\":\"listOfStructs1\"}]," + "\"TimestampMember\":1540982918.887," + "\"StructWithNestedTimestampMember\":{\"NestedTimestamp\":1540982918.908}," + "\"BlobArg\":\"aGVsbG8gd29ybGQ=\"}"; public static final String XML_BODY = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><AllTypesResponse " + "xmlns=\"https://restxml/\"><stringMember>foo</stringMember><integerMember>123" + "</integerMember><booleanMember>true</booleanMember><floatMember>123" + ".0</floatMember><doubleMember>123" + ".9</doubleMember><longMember>123</longMember><simpleList><member>so " + "simple</member></simpleList><listOfStructs><member><StringMember>listOfStructs1" + "</StringMember></member></listOfStructs><timestampMember>2018-10-31T10:51:12" + ".302183Z</timestampMember><structWithNestedTimestampMember><NestedTimestamp>2018" + "-10-31T10:51:12.311305Z</NestedTimestamp></structWithNestedTimestampMember" + "><blobArg>aGVsbG8gd29ybGQ=</blobArg></AllTypesResponse>"; public static final String ERROR_XML_BODY = "<ErrorResponse>" + " <Error>" + " <Code>ImplicitPayloadException</Code>" + " <Message>this is the service message</Message>" + " <StringMember>foo</StringMember>" + " <IntegerMember>42</IntegerMember>" + " <LongMember>9001</LongMember>" + " <DoubleMember>1234.56</DoubleMember>" + " <FloatMember>789.10</FloatMember>" + " <TimestampMember>2015-01-25T08:00:12Z</TimestampMember>" + " <BooleanMember>true</BooleanMember>" + " <BlobMember>dGhlcmUh</BlobMember>" + " <ListMember>" + " <member>valOne</member>" + " <member>valTwo</member>" + " </ListMember>" + " <MapMember>" + " <entry>" + " <key>keyOne</key>" + " <value>valOne</value>" + " </entry>" + " <entry>" + " <key>keyTwo</key>" + " <value>valTwo</value>" + " </entry>" + " </MapMember>" + " <SimpleStructMember>" + " <StringMember>foobar</StringMember>" + " </SimpleStructMember>" + " </Error>" + "</ErrorResponse>"; public static final software.amazon.awssdk.services.protocolrestxml.model.AllTypesRequest XML_ALL_TYPES_REQUEST = software.amazon.awssdk.services.protocolrestxml.model.AllTypesRequest.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleStructMember(b -> b.stringMember( "bar")) .simpleList("so simple") .listOfStructs(b -> b.stringMember( "listOfStructs1").stringMember( "listOfStructs1")) .timestampMember( TIMESTAMP_MEMBER) .structWithNestedTimestampMember( b -> b.nestedTimestamp(TIMESTAMP_MEMBER)) .blobArg(SdkBytes.fromUtf8String("hello " + "world")) .build(); public static final software.amazon.awssdk.services.protocolquery.model.AllTypesRequest QUERY_ALL_TYPES_REQUEST = software.amazon.awssdk.services.protocolquery.model.AllTypesRequest.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleStructMember(b -> b.stringMember( "bar")) .simpleList("so simple") .listOfStructs(b -> b.stringMember( "listOfStructs1").stringMember( "listOfStructs1")) .timestampMember( TIMESTAMP_MEMBER) .structWithNestedTimestampMember( b -> b.nestedTimestamp( TIMESTAMP_MEMBER)) .blobArg(SdkBytes.fromUtf8String("hello " + "world")) .build(); public static final software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest JSON_ALL_TYPES_REQUEST = software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleList("so simple") .listOfStructs(b -> b.stringMember( "listOfStructs1").stringMember( "listOfStructs1")) .timestampMember( TIMESTAMP_MEMBER) .structWithNestedTimestampMember( b -> b.nestedTimestamp( TIMESTAMP_MEMBER)) .blobArg(SdkBytes.fromUtf8String("hello " + "world")) .build(); public static final AllTypesRequest EC2_ALL_TYPES_REQUEST = AllTypesRequest.builder() .stringMember("foo") .integerMember(123) .booleanMember(true) .floatMember(123.0f) .doubleMember(123.9) .longMember(123L) .simpleStructMember(b -> b.stringMember( "bar")) .simpleList("so simple") .listOfStructs(b -> b.stringMember( "listOfStructs1").stringMember( "listOfStructs1")) .timestampMember(TIMESTAMP_MEMBER) .structWithNestedTimestampMember(b -> b.nestedTimestamp( TIMESTAMP_MEMBER)) .blobArg(SdkBytes.fromUtf8String("hello " + "world")) .build(); private BenchmarkConstant() { } }
2,782
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/MockServer.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.benchmark.utils; import java.io.IOException; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.ssl.SslContextFactory; public class MockServer extends BaseMockServer { private Server server; private ServerConnector connector; private ServerConnector sslConnector; public MockServer() throws IOException { server = new Server(); connector = new ServerConnector(server); connector.setPort(httpPort); HttpConfiguration https = new HttpConfiguration(); https.addCustomizer(new SecureRequestCustomizer()); SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setTrustAll(true); sslContextFactory.setValidateCerts(false); sslContextFactory.setNeedClientAuth(false); sslContextFactory.setWantClientAuth(false); sslContextFactory.setValidatePeerCerts(false); sslContextFactory.setKeyStorePassword("password"); sslContextFactory.setKeyStorePath(MockServer.class.getResource("mock-keystore.jks").toExternalForm()); sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https)); sslConnector.setPort(httpsPort); server.setConnectors(new Connector[] {connector, sslConnector}); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); context.addServlet(new ServletHolder(new AlwaysSuccessServlet()), "/*"); server.setHandler(context); } public void start() throws Exception { server.start(); } public void stop() throws Exception { server.stop(); sslConnector.stop(); connector.stop(); } }
2,783
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/utils/BaseMockServer.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.benchmark.utils; import java.io.IOException; import java.net.URI; public abstract class BaseMockServer { protected int httpPort; protected int httpsPort; public BaseMockServer() throws IOException { httpPort = BenchmarkUtils.getUnusedPort(); httpsPort = BenchmarkUtils.getUnusedPort(); } public URI getHttpUri() { return URI.create(String.format("http://localhost:%s", httpPort)); } public URI getHttpsUri() { return URI.create(String.format("https://localhost:%s", httpsPort)); } }
2,784
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientUpdateV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.model.UpdateItemResult; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientUpdateV1MapperComparisonBenchmark { private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory(); private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory(); private static final DynamoDBMapperConfig MAPPER_CONFIG = DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.UPDATE) .build(); @Benchmark public void v2Update(TestState s) { s.v2Table.updateItem(s.testItem.v2Bean); } @Benchmark public void v1Update(TestState s) { s.v1DdbMapper.save(s.testItem.v1Bean); } private static DynamoDbClient getV2Client(Blackhole bh, UpdateItemResponse updateItemResponse) { return new V2TestDynamoDbUpdateItemClient(bh, updateItemResponse); } private static AmazonDynamoDB getV1Client(Blackhole bh, UpdateItemResult updateItemResult) { return new V1TestDynamoDbUpdateItemClient(bh, updateItemResult); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private DynamoDbTable v2Table; private DynamoDBMapper v1DdbMapper; @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh, testItem.v2UpdateItemResponse)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh, testItem.v1UpdateItemResult), MAPPER_CONFIG); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.tinyBean(), UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.tiny()).build(), V1_ITEM_FACTORY.v1TinyBean(), new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.tiny()) ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.smallBean(), UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.small()).build(), V1_ITEM_FACTORY.v1SmallBean(), new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.small()) ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.hugeBean(), UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.huge()).build(), V1_ITEM_FACTORY.v1hugeBean(), new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.huge()) ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, V2_ITEM_FACTORY.hugeBeanFlat(), UpdateItemResponse.builder().attributes(V2_ITEM_FACTORY.hugeFlat()).build(), V1_ITEM_FACTORY.v1HugeBeanFlat(), new UpdateItemResult().withAttributes(V1_ITEM_FACTORY.hugeFlat()) ), ; // V2 private TableSchema schema; private Object v2Bean; private UpdateItemResponse v2UpdateItemResponse; // V1 private Object v1Bean; private UpdateItemResult v1UpdateItemResult; TestItem(TableSchema<?> schema, Object v2Bean, UpdateItemResponse v2UpdateItemResponse, Object v1Bean, UpdateItemResult v1UpdateItemResult) { this.schema = schema; this.v2Bean = v2Bean; this.v2UpdateItemResponse = v2UpdateItemResponse; this.v1Bean = v1Bean; this.v1UpdateItemResult = v1UpdateItemResult; } } } }
2,785
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbUpdateItemClient.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest; import com.amazonaws.services.dynamodbv2.model.UpdateItemResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbUpdateItemClient extends V1TestDynamoDbBaseClient { private final UpdateItemResult updateItemResult; public V1TestDynamoDbUpdateItemClient(Blackhole bh, UpdateItemResult updateItemResult) { super(bh); this.updateItemResult = updateItemResult; } @Override public UpdateItemResult updateItem(UpdateItemRequest request) { bh.consume(request); return updateItemResult; } }
2,786
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/ItemFactory.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.benchmark.enhanced.dynamodb; import com.amazonaws.util.ImmutableMapParameter; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import software.amazon.awssdk.core.SdkBytes; abstract class ItemFactory<T> { private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private static final Random RNG = new Random(); public final Map<String, T> tiny() { return asItem(tinyBean()); } public final Map<String, T> small() { return asItem(smallBean()); } public final Map<String, T> huge() { return asItem(hugeBean()); } public final Map<String, T> hugeFlat() { return asItem(hugeBeanFlat()); } public final TinyBean tinyBean() { TinyBean b = new TinyBean(); b.setStringAttr(randomS()); return b; } public final SmallBean smallBean() { SmallBean b = new SmallBean(); b.setStringAttr(randomS()); b.setBinaryAttr(randomBytes()); b.setListAttr(Arrays.asList(randomS(), randomS(), randomS())); return b; } public final HugeBean hugeBean() { HugeBean b = new HugeBean(); b.setHashKey(randomS()); b.setStringAttr(randomS()); b.setBinaryAttr(randomBytes()); b.setListAttr(IntStream.range(0, 32).mapToObj(i -> randomS()).collect(Collectors.toList())); Map<String, SdkBytes> mapAttr1 = new HashMap<>(); mapAttr1.put("key1", randomBytes()); mapAttr1.put("key2", randomBytes()); mapAttr1.put("key3", randomBytes()); b.setMapAttr1(mapAttr1); Map<String, List<SdkBytes>> mapAttr2 = new HashMap<>(); mapAttr2.put("key1", Arrays.asList(randomBytes())); mapAttr2.put("key2", IntStream.range(0, 2).mapToObj(i -> randomBytes()).collect(Collectors.toList())); mapAttr2.put("key3", IntStream.range(0, 4).mapToObj(i -> randomBytes()).collect(Collectors.toList())); mapAttr2.put("key4", IntStream.range(0, 8).mapToObj(i -> randomBytes()).collect(Collectors.toList())); mapAttr2.put("key5", IntStream.range(0, 16).mapToObj(i -> randomBytes()).collect(Collectors.toList())); b.setMapAttr2(mapAttr2); ImmutableMapParameter.Builder<String, List<Map<String, List<SdkBytes>>>> mapAttr3Builder = ImmutableMapParameter.builder(); List<Map<String, List<SdkBytes>>> value = Arrays.asList( ImmutableMapParameter.<String, List<SdkBytes>>builder() .put("key1", IntStream.range(0, 2).mapToObj(i -> randomBytes()).collect(Collectors.toList())) .build(), ImmutableMapParameter.<String, List<SdkBytes>>builder() .put("key2", IntStream.range(0, 4).mapToObj(i -> randomBytes()).collect(Collectors.toList())) .build(), ImmutableMapParameter.<String, List<SdkBytes>>builder() .put("key3", IntStream.range(0, 8).mapToObj(i -> randomBytes()).collect(Collectors.toList())) .build() ); mapAttr3Builder.put("key1", value) .put("key2", value) .build(); b.setMapAttr3(mapAttr3Builder.build()); return b; } public HugeBeanFlat hugeBeanFlat() { HugeBeanFlat b = new HugeBeanFlat(); Class<HugeBeanFlat> clazz = HugeBeanFlat.class; for (int i = 1; i <= 63; ++i) { try { Method setter = clazz.getMethod("setStringAttr" + i, String.class); setter.setAccessible(true); setter.invoke(b, randomS()); } catch (Throwable t) { throw new RuntimeException(t); } } return b; } protected abstract Map<String, T> asItem(TinyBean b); protected abstract Map<String, T> asItem(SmallBean b); protected abstract Map<String, T> asItem(HugeBean b); protected final Map<String, T> asItem(HugeBeanFlat b) { Map<String, T> item = new HashMap<>(); Class<HugeBeanFlat> clazz = HugeBeanFlat.class; for (int i = 1; i <= 63; ++i) { try { Method getter = clazz.getMethod("getStringAttr" + i); getter.setAccessible(true); item.put("stringAttr" + i, av((String) getter.invoke(b))); } catch (Throwable t) { throw new RuntimeException(t); } } return item; } protected abstract T av(String val); protected abstract T av(List<T> val); protected abstract T av(Map<String, T> val); protected abstract T av(SdkBytes val); private static String randomS(int len) { StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; ++i) { sb.append(ALPHA.charAt(RNG.nextInt(ALPHA.length()))); } return sb.toString(); } private static String randomS() { return randomS(16); } private static ByteBuffer randomB(int len) { byte[] b = new byte[len]; RNG.nextBytes(b); return ByteBuffer.wrap(b); } private static ByteBuffer randomB() { return randomB(16); } private static SdkBytes randomBytes() { return SdkBytes.fromByteBuffer(randomB()); } public static class TinyBean { private String stringAttr; public String getStringAttr() { return stringAttr; } public void setStringAttr(String stringAttr) { this.stringAttr = stringAttr; } } public static class SmallBean { private String stringAttr; private SdkBytes binaryAttr; private List<String> listAttr; public String getStringAttr() { return stringAttr; } public void setStringAttr(String stringAttr) { this.stringAttr = stringAttr; } public SdkBytes getBinaryAttr() { return binaryAttr; } public void setBinaryAttr(SdkBytes binaryAttr) { this.binaryAttr = binaryAttr; } public List<String> getListAttr() { return listAttr; } public void setListAttr(List<String> listAttr) { this.listAttr = listAttr; } } public static class HugeBean { private String hashKey; private String stringAttr; private SdkBytes binaryAttr; private List<String> listAttr; private Map<String, SdkBytes> mapAttr1; private Map<String, List<SdkBytes>> mapAttr2; private Map<String, List<Map<String, List<SdkBytes>>>> mapAttr3; public String getHashKey() { return hashKey; } public void setHashKey(String hashKey) { this.hashKey = hashKey; } public String getStringAttr() { return stringAttr; } public void setStringAttr(String stringAttr) { this.stringAttr = stringAttr; } public SdkBytes getBinaryAttr() { return binaryAttr; } public void setBinaryAttr(SdkBytes binaryAttr) { this.binaryAttr = binaryAttr; } public List<String> getListAttr() { return listAttr; } public void setListAttr(List<String> listAttr) { this.listAttr = listAttr; } public Map<String, SdkBytes> getMapAttr1() { return mapAttr1; } public void setMapAttr1(Map<String, SdkBytes> mapAttr1) { this.mapAttr1 = mapAttr1; } public Map<String, List<SdkBytes>> getMapAttr2() { return mapAttr2; } public void setMapAttr2(Map<String, List<SdkBytes>> mapAttr2) { this.mapAttr2 = mapAttr2; } public Map<String, List<Map<String, List<SdkBytes>>>> getMapAttr3() { return mapAttr3; } public void setMapAttr3(Map<String, List<Map<String, List<SdkBytes>>>> mapAttr3) { this.mapAttr3 = mapAttr3; } } public static class HugeBeanFlat { private String stringAttr1; private String stringAttr2; private String stringAttr3; private String stringAttr4; private String stringAttr5; private String stringAttr6; private String stringAttr7; private String stringAttr8; private String stringAttr9; private String stringAttr10; private String stringAttr11; private String stringAttr12; private String stringAttr13; private String stringAttr14; private String stringAttr15; private String stringAttr16; private String stringAttr17; private String stringAttr18; private String stringAttr19; private String stringAttr20; private String stringAttr21; private String stringAttr22; private String stringAttr23; private String stringAttr24; private String stringAttr25; private String stringAttr26; private String stringAttr27; private String stringAttr28; private String stringAttr29; private String stringAttr30; private String stringAttr31; private String stringAttr32; private String stringAttr33; private String stringAttr34; private String stringAttr35; private String stringAttr36; private String stringAttr37; private String stringAttr38; private String stringAttr39; private String stringAttr40; private String stringAttr41; private String stringAttr42; private String stringAttr43; private String stringAttr44; private String stringAttr45; private String stringAttr46; private String stringAttr47; private String stringAttr48; private String stringAttr49; private String stringAttr50; private String stringAttr51; private String stringAttr52; private String stringAttr53; private String stringAttr54; private String stringAttr55; private String stringAttr56; private String stringAttr57; private String stringAttr58; private String stringAttr59; private String stringAttr60; private String stringAttr61; private String stringAttr62; private String stringAttr63; public String getStringAttr1() { return stringAttr1; } public void setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; } public String getStringAttr2() { return stringAttr2; } public void setStringAttr2(String stringAttr2) { this.stringAttr2 = stringAttr2; } public String getStringAttr3() { return stringAttr3; } public void setStringAttr3(String stringAttr3) { this.stringAttr3 = stringAttr3; } public String getStringAttr4() { return stringAttr4; } public void setStringAttr4(String stringAttr4) { this.stringAttr4 = stringAttr4; } public String getStringAttr5() { return stringAttr5; } public void setStringAttr5(String stringAttr5) { this.stringAttr5 = stringAttr5; } public String getStringAttr6() { return stringAttr6; } public void setStringAttr6(String stringAttr6) { this.stringAttr6 = stringAttr6; } public String getStringAttr7() { return stringAttr7; } public void setStringAttr7(String stringAttr7) { this.stringAttr7 = stringAttr7; } public String getStringAttr8() { return stringAttr8; } public void setStringAttr8(String stringAttr8) { this.stringAttr8 = stringAttr8; } public String getStringAttr9() { return stringAttr9; } public void setStringAttr9(String stringAttr9) { this.stringAttr9 = stringAttr9; } public String getStringAttr10() { return stringAttr10; } public void setStringAttr10(String stringAttr10) { this.stringAttr10 = stringAttr10; } public String getStringAttr11() { return stringAttr11; } public void setStringAttr11(String stringAttr11) { this.stringAttr11 = stringAttr11; } public String getStringAttr12() { return stringAttr12; } public void setStringAttr12(String stringAttr12) { this.stringAttr12 = stringAttr12; } public String getStringAttr13() { return stringAttr13; } public void setStringAttr13(String stringAttr13) { this.stringAttr13 = stringAttr13; } public String getStringAttr14() { return stringAttr14; } public void setStringAttr14(String stringAttr14) { this.stringAttr14 = stringAttr14; } public String getStringAttr15() { return stringAttr15; } public void setStringAttr15(String stringAttr15) { this.stringAttr15 = stringAttr15; } public String getStringAttr16() { return stringAttr16; } public void setStringAttr16(String stringAttr16) { this.stringAttr16 = stringAttr16; } public String getStringAttr17() { return stringAttr17; } public void setStringAttr17(String stringAttr17) { this.stringAttr17 = stringAttr17; } public String getStringAttr18() { return stringAttr18; } public void setStringAttr18(String stringAttr18) { this.stringAttr18 = stringAttr18; } public String getStringAttr19() { return stringAttr19; } public void setStringAttr19(String stringAttr19) { this.stringAttr19 = stringAttr19; } public String getStringAttr20() { return stringAttr20; } public void setStringAttr20(String stringAttr20) { this.stringAttr20 = stringAttr20; } public String getStringAttr21() { return stringAttr21; } public void setStringAttr21(String stringAttr21) { this.stringAttr21 = stringAttr21; } public String getStringAttr22() { return stringAttr22; } public void setStringAttr22(String stringAttr22) { this.stringAttr22 = stringAttr22; } public String getStringAttr23() { return stringAttr23; } public void setStringAttr23(String stringAttr23) { this.stringAttr23 = stringAttr23; } public String getStringAttr24() { return stringAttr24; } public void setStringAttr24(String stringAttr24) { this.stringAttr24 = stringAttr24; } public String getStringAttr25() { return stringAttr25; } public void setStringAttr25(String stringAttr25) { this.stringAttr25 = stringAttr25; } public String getStringAttr26() { return stringAttr26; } public void setStringAttr26(String stringAttr26) { this.stringAttr26 = stringAttr26; } public String getStringAttr27() { return stringAttr27; } public void setStringAttr27(String stringAttr27) { this.stringAttr27 = stringAttr27; } public String getStringAttr28() { return stringAttr28; } public void setStringAttr28(String stringAttr28) { this.stringAttr28 = stringAttr28; } public String getStringAttr29() { return stringAttr29; } public void setStringAttr29(String stringAttr29) { this.stringAttr29 = stringAttr29; } public String getStringAttr30() { return stringAttr30; } public void setStringAttr30(String stringAttr30) { this.stringAttr30 = stringAttr30; } public String getStringAttr31() { return stringAttr31; } public void setStringAttr31(String stringAttr31) { this.stringAttr31 = stringAttr31; } public String getStringAttr32() { return stringAttr32; } public void setStringAttr32(String stringAttr32) { this.stringAttr32 = stringAttr32; } public String getStringAttr33() { return stringAttr33; } public void setStringAttr33(String stringAttr33) { this.stringAttr33 = stringAttr33; } public String getStringAttr34() { return stringAttr34; } public void setStringAttr34(String stringAttr34) { this.stringAttr34 = stringAttr34; } public String getStringAttr35() { return stringAttr35; } public void setStringAttr35(String stringAttr35) { this.stringAttr35 = stringAttr35; } public String getStringAttr36() { return stringAttr36; } public void setStringAttr36(String stringAttr36) { this.stringAttr36 = stringAttr36; } public String getStringAttr37() { return stringAttr37; } public void setStringAttr37(String stringAttr37) { this.stringAttr37 = stringAttr37; } public String getStringAttr38() { return stringAttr38; } public void setStringAttr38(String stringAttr38) { this.stringAttr38 = stringAttr38; } public String getStringAttr39() { return stringAttr39; } public void setStringAttr39(String stringAttr39) { this.stringAttr39 = stringAttr39; } public String getStringAttr40() { return stringAttr40; } public void setStringAttr40(String stringAttr40) { this.stringAttr40 = stringAttr40; } public String getStringAttr41() { return stringAttr41; } public void setStringAttr41(String stringAttr41) { this.stringAttr41 = stringAttr41; } public String getStringAttr42() { return stringAttr42; } public void setStringAttr42(String stringAttr42) { this.stringAttr42 = stringAttr42; } public String getStringAttr43() { return stringAttr43; } public void setStringAttr43(String stringAttr43) { this.stringAttr43 = stringAttr43; } public String getStringAttr44() { return stringAttr44; } public void setStringAttr44(String stringAttr44) { this.stringAttr44 = stringAttr44; } public String getStringAttr45() { return stringAttr45; } public void setStringAttr45(String stringAttr45) { this.stringAttr45 = stringAttr45; } public String getStringAttr46() { return stringAttr46; } public void setStringAttr46(String stringAttr46) { this.stringAttr46 = stringAttr46; } public String getStringAttr47() { return stringAttr47; } public void setStringAttr47(String stringAttr47) { this.stringAttr47 = stringAttr47; } public String getStringAttr48() { return stringAttr48; } public void setStringAttr48(String stringAttr48) { this.stringAttr48 = stringAttr48; } public String getStringAttr49() { return stringAttr49; } public void setStringAttr49(String stringAttr49) { this.stringAttr49 = stringAttr49; } public String getStringAttr50() { return stringAttr50; } public void setStringAttr50(String stringAttr50) { this.stringAttr50 = stringAttr50; } public String getStringAttr51() { return stringAttr51; } public void setStringAttr51(String stringAttr51) { this.stringAttr51 = stringAttr51; } public String getStringAttr52() { return stringAttr52; } public void setStringAttr52(String stringAttr52) { this.stringAttr52 = stringAttr52; } public String getStringAttr53() { return stringAttr53; } public void setStringAttr53(String stringAttr53) { this.stringAttr53 = stringAttr53; } public String getStringAttr54() { return stringAttr54; } public void setStringAttr54(String stringAttr54) { this.stringAttr54 = stringAttr54; } public String getStringAttr55() { return stringAttr55; } public void setStringAttr55(String stringAttr55) { this.stringAttr55 = stringAttr55; } public String getStringAttr56() { return stringAttr56; } public void setStringAttr56(String stringAttr56) { this.stringAttr56 = stringAttr56; } public String getStringAttr57() { return stringAttr57; } public void setStringAttr57(String stringAttr57) { this.stringAttr57 = stringAttr57; } public String getStringAttr58() { return stringAttr58; } public void setStringAttr58(String stringAttr58) { this.stringAttr58 = stringAttr58; } public String getStringAttr59() { return stringAttr59; } public void setStringAttr59(String stringAttr59) { this.stringAttr59 = stringAttr59; } public String getStringAttr60() { return stringAttr60; } public void setStringAttr60(String stringAttr60) { this.stringAttr60 = stringAttr60; } public String getStringAttr61() { return stringAttr61; } public void setStringAttr61(String stringAttr61) { this.stringAttr61 = stringAttr61; } public String getStringAttr62() { return stringAttr62; } public void setStringAttr62(String stringAttr62) { this.stringAttr62 = stringAttr62; } public String getStringAttr63() { return stringAttr63; } public void setStringAttr63(String stringAttr63) { this.stringAttr63 = stringAttr63; } } }
2,787
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbQueryClient.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.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.paginators.QueryIterable; public final class V2TestDynamoDbQueryClient extends V2TestDynamoDbBaseClient { private final QueryResponse queryResponse; public V2TestDynamoDbQueryClient(Blackhole bh, QueryResponse queryResponse) { super(bh); this.queryResponse = queryResponse; } @Override public QueryResponse query(QueryRequest queryRequest) { bh.consume(queryRequest); return this.queryResponse; } @Override public QueryIterable queryPaginator(QueryRequest queryRequest) { return new QueryIterable(this, queryRequest); } }
2,788
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbDeleteItemClient.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.DeleteItemRequest; import com.amazonaws.services.dynamodbv2.model.DeleteItemResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbDeleteItemClient extends V1TestDynamoDbBaseClient { private static final DeleteItemResult DELETE_ITEM_RESULT = new DeleteItemResult(); public V1TestDynamoDbDeleteItemClient(Blackhole bh) { super(bh); } @Override public DeleteItemResult deleteItem(DeleteItemRequest request) { bh.consume(request); return DELETE_ITEM_RESULT; } }
2,789
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2ItemFactory.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.benchmark.enhanced.dynamodb; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import com.amazonaws.util.ImmutableMapParameter; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public final class V2ItemFactory extends ItemFactory<AttributeValue> { public static final TableSchema<ItemFactory.TinyBean> TINY_BEAN_TABLE_SCHEMA = TableSchema.builder(ItemFactory.TinyBean.class) .newItemSupplier(ItemFactory.TinyBean::new) .addAttribute(String.class, a -> a.name("stringAttr") .getter(ItemFactory.TinyBean::getStringAttr) .setter(ItemFactory.TinyBean::setStringAttr) .tags(primaryPartitionKey())) .build(); public static final TableSchema<ItemFactory.SmallBean> SMALL_BEAN_TABLE_SCHEMA = TableSchema.builder(ItemFactory.SmallBean.class) .newItemSupplier(ItemFactory.SmallBean::new) .addAttribute(String.class, a -> a.name("stringAttr") .getter(ItemFactory.SmallBean::getStringAttr) .setter(ItemFactory.SmallBean::setStringAttr) .tags(primaryPartitionKey())) .addAttribute(SdkBytes.class, a -> a.name("binaryAttr") .getter(ItemFactory.SmallBean::getBinaryAttr) .setter(ItemFactory.SmallBean::setBinaryAttr)) .addAttribute(EnhancedType.listOf(String.class), a -> a.name("listAttr") .getter(ItemFactory.SmallBean::getListAttr) .setter(ItemFactory.SmallBean::setListAttr)) .build(); public static final TableSchema<ItemFactory.HugeBean> HUGE_BEAN_TABLE_SCHEMA = TableSchema.builder(ItemFactory.HugeBean.class) .newItemSupplier(ItemFactory.HugeBean::new) .addAttribute(String.class, a -> a.name("stringAttr") .getter(ItemFactory.HugeBean::getStringAttr) .setter(ItemFactory.HugeBean::setStringAttr) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("hashKey") .getter(ItemFactory.HugeBean::getHashKey) .setter(ItemFactory.HugeBean::setHashKey)) .addAttribute(SdkBytes.class, a -> a.name("binaryAttr") .getter(ItemFactory.HugeBean::getBinaryAttr) .setter(ItemFactory.HugeBean::setBinaryAttr)) .addAttribute(EnhancedType.listOf(String.class), a -> a.name("listAttr") .getter(ItemFactory.HugeBean::getListAttr) .setter(ItemFactory.HugeBean::setListAttr)) .addAttribute(new EnhancedType<Map<String, SdkBytes>>() { }, a -> a.name("mapAttr1") .getter(ItemFactory.HugeBean::getMapAttr1) .setter(ItemFactory.HugeBean::setMapAttr1)) .addAttribute(new EnhancedType<Map<String, List<SdkBytes>>>() { }, a -> a.name("mapAttr2") .getter(ItemFactory.HugeBean::getMapAttr2) .setter(ItemFactory.HugeBean::setMapAttr2)) .addAttribute(new EnhancedType<Map<String, List<Map<String, List<SdkBytes>>>>>() { }, a -> a.name("mapAttr3") .getter(ItemFactory.HugeBean::getMapAttr3) .setter(ItemFactory.HugeBean::setMapAttr3)) .build(); public static final TableSchema<ItemFactory.HugeBeanFlat> HUGE_BEAN_FLAT_TABLE_SCHEMA = TableSchema.builder(ItemFactory.HugeBeanFlat.class) .newItemSupplier(ItemFactory.HugeBeanFlat::new) .addAttribute(String.class, a -> a.name("stringAttr") .getter(ItemFactory.HugeBeanFlat::getStringAttr1) .setter(ItemFactory.HugeBeanFlat::setStringAttr1) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr2") .getter(ItemFactory.HugeBeanFlat::getStringAttr2) .setter(ItemFactory.HugeBeanFlat::setStringAttr2)) .addAttribute(String.class, a -> a.name("stringAttr3") .getter(ItemFactory.HugeBeanFlat::getStringAttr3) .setter(ItemFactory.HugeBeanFlat::setStringAttr3)) .addAttribute(String.class, a -> a.name("stringAttr4") .getter(ItemFactory.HugeBeanFlat::getStringAttr4) .setter(ItemFactory.HugeBeanFlat::setStringAttr4)) .addAttribute(String.class, a -> a.name("stringAttr5") .getter(ItemFactory.HugeBeanFlat::getStringAttr5) .setter(ItemFactory.HugeBeanFlat::setStringAttr5)) .addAttribute(String.class, a -> a.name("stringAttr6") .getter(ItemFactory.HugeBeanFlat::getStringAttr6) .setter(ItemFactory.HugeBeanFlat::setStringAttr6)) .addAttribute(String.class, a -> a.name("stringAttr7") .getter(ItemFactory.HugeBeanFlat::getStringAttr7) .setter(ItemFactory.HugeBeanFlat::setStringAttr7)) .addAttribute(String.class, a -> a.name("stringAttr8") .getter(ItemFactory.HugeBeanFlat::getStringAttr8) .setter(ItemFactory.HugeBeanFlat::setStringAttr8)) .addAttribute(String.class, a -> a.name("stringAttr9") .getter(ItemFactory.HugeBeanFlat::getStringAttr9) .setter(ItemFactory.HugeBeanFlat::setStringAttr9)) .addAttribute(String.class, a -> a.name("stringAttr10") .getter(ItemFactory.HugeBeanFlat::getStringAttr10) .setter(ItemFactory.HugeBeanFlat::setStringAttr10)) .addAttribute(String.class, a -> a.name("stringAttr11") .getter(ItemFactory.HugeBeanFlat::getStringAttr11) .setter(ItemFactory.HugeBeanFlat::setStringAttr11)) .addAttribute(String.class, a -> a.name("stringAttr12") .getter(ItemFactory.HugeBeanFlat::getStringAttr12) .setter(ItemFactory.HugeBeanFlat::setStringAttr12)) .addAttribute(String.class, a -> a.name("stringAttr13") .getter(ItemFactory.HugeBeanFlat::getStringAttr13) .setter(ItemFactory.HugeBeanFlat::setStringAttr13)) .addAttribute(String.class, a -> a.name("stringAttr14") .getter(ItemFactory.HugeBeanFlat::getStringAttr14) .setter(ItemFactory.HugeBeanFlat::setStringAttr14)) .addAttribute(String.class, a -> a.name("stringAttr15") .getter(ItemFactory.HugeBeanFlat::getStringAttr15) .setter(ItemFactory.HugeBeanFlat::setStringAttr15)) .addAttribute(String.class, a -> a.name("stringAttr16") .getter(ItemFactory.HugeBeanFlat::getStringAttr16) .setter(ItemFactory.HugeBeanFlat::setStringAttr16)) .addAttribute(String.class, a -> a.name("stringAttr17") .getter(ItemFactory.HugeBeanFlat::getStringAttr17) .setter(ItemFactory.HugeBeanFlat::setStringAttr17)) .addAttribute(String.class, a -> a.name("stringAttr18") .getter(ItemFactory.HugeBeanFlat::getStringAttr18) .setter(ItemFactory.HugeBeanFlat::setStringAttr18)) .addAttribute(String.class, a -> a.name("stringAttr19") .getter(ItemFactory.HugeBeanFlat::getStringAttr19) .setter(ItemFactory.HugeBeanFlat::setStringAttr19)) .addAttribute(String.class, a -> a.name("stringAttr20") .getter(ItemFactory.HugeBeanFlat::getStringAttr20) .setter(ItemFactory.HugeBeanFlat::setStringAttr20)) .addAttribute(String.class, a -> a.name("stringAttr21") .getter(ItemFactory.HugeBeanFlat::getStringAttr21) .setter(ItemFactory.HugeBeanFlat::setStringAttr21)) .addAttribute(String.class, a -> a.name("stringAttr22") .getter(ItemFactory.HugeBeanFlat::getStringAttr22) .setter(ItemFactory.HugeBeanFlat::setStringAttr22)) .addAttribute(String.class, a -> a.name("stringAttr23") .getter(ItemFactory.HugeBeanFlat::getStringAttr23) .setter(ItemFactory.HugeBeanFlat::setStringAttr23)) .addAttribute(String.class, a -> a.name("stringAttr24") .getter(ItemFactory.HugeBeanFlat::getStringAttr24) .setter(ItemFactory.HugeBeanFlat::setStringAttr24)) .addAttribute(String.class, a -> a.name("stringAttr25") .getter(ItemFactory.HugeBeanFlat::getStringAttr25) .setter(ItemFactory.HugeBeanFlat::setStringAttr25)) .addAttribute(String.class, a -> a.name("stringAttr26") .getter(ItemFactory.HugeBeanFlat::getStringAttr26) .setter(ItemFactory.HugeBeanFlat::setStringAttr26)) .addAttribute(String.class, a -> a.name("stringAttr27") .getter(ItemFactory.HugeBeanFlat::getStringAttr27) .setter(ItemFactory.HugeBeanFlat::setStringAttr27)) .addAttribute(String.class, a -> a.name("stringAttr28") .getter(ItemFactory.HugeBeanFlat::getStringAttr28) .setter(ItemFactory.HugeBeanFlat::setStringAttr28)) .addAttribute(String.class, a -> a.name("stringAttr29") .getter(ItemFactory.HugeBeanFlat::getStringAttr29) .setter(ItemFactory.HugeBeanFlat::setStringAttr29)) .addAttribute(String.class, a -> a.name("stringAttr30") .getter(ItemFactory.HugeBeanFlat::getStringAttr30) .setter(ItemFactory.HugeBeanFlat::setStringAttr30)) .addAttribute(String.class, a -> a.name("stringAttr31") .getter(ItemFactory.HugeBeanFlat::getStringAttr31) .setter(ItemFactory.HugeBeanFlat::setStringAttr31)) .addAttribute(String.class, a -> a.name("stringAttr32") .getter(ItemFactory.HugeBeanFlat::getStringAttr32) .setter(ItemFactory.HugeBeanFlat::setStringAttr32)) .addAttribute(String.class, a -> a.name("stringAttr33") .getter(ItemFactory.HugeBeanFlat::getStringAttr33) .setter(ItemFactory.HugeBeanFlat::setStringAttr33)) .addAttribute(String.class, a -> a.name("stringAttr34") .getter(ItemFactory.HugeBeanFlat::getStringAttr34) .setter(ItemFactory.HugeBeanFlat::setStringAttr34)) .addAttribute(String.class, a -> a.name("stringAttr35") .getter(ItemFactory.HugeBeanFlat::getStringAttr35) .setter(ItemFactory.HugeBeanFlat::setStringAttr35)) .addAttribute(String.class, a -> a.name("stringAttr36") .getter(ItemFactory.HugeBeanFlat::getStringAttr36) .setter(ItemFactory.HugeBeanFlat::setStringAttr36)) .addAttribute(String.class, a -> a.name("stringAttr37") .getter(ItemFactory.HugeBeanFlat::getStringAttr37) .setter(ItemFactory.HugeBeanFlat::setStringAttr37)) .addAttribute(String.class, a -> a.name("stringAttr38") .getter(ItemFactory.HugeBeanFlat::getStringAttr38) .setter(ItemFactory.HugeBeanFlat::setStringAttr38)) .addAttribute(String.class, a -> a.name("stringAttr39") .getter(ItemFactory.HugeBeanFlat::getStringAttr39) .setter(ItemFactory.HugeBeanFlat::setStringAttr39)) .addAttribute(String.class, a -> a.name("stringAttr40") .getter(ItemFactory.HugeBeanFlat::getStringAttr40) .setter(ItemFactory.HugeBeanFlat::setStringAttr40)) .addAttribute(String.class, a -> a.name("stringAttr41") .getter(ItemFactory.HugeBeanFlat::getStringAttr41) .setter(ItemFactory.HugeBeanFlat::setStringAttr41)) .addAttribute(String.class, a -> a.name("stringAttr42") .getter(ItemFactory.HugeBeanFlat::getStringAttr42) .setter(ItemFactory.HugeBeanFlat::setStringAttr42)) .addAttribute(String.class, a -> a.name("stringAttr43") .getter(ItemFactory.HugeBeanFlat::getStringAttr43) .setter(ItemFactory.HugeBeanFlat::setStringAttr43)) .addAttribute(String.class, a -> a.name("stringAttr44") .getter(ItemFactory.HugeBeanFlat::getStringAttr44) .setter(ItemFactory.HugeBeanFlat::setStringAttr44)) .addAttribute(String.class, a -> a.name("stringAttr45") .getter(ItemFactory.HugeBeanFlat::getStringAttr45) .setter(ItemFactory.HugeBeanFlat::setStringAttr45)) .addAttribute(String.class, a -> a.name("stringAttr46") .getter(ItemFactory.HugeBeanFlat::getStringAttr46) .setter(ItemFactory.HugeBeanFlat::setStringAttr46)) .addAttribute(String.class, a -> a.name("stringAttr47") .getter(ItemFactory.HugeBeanFlat::getStringAttr47) .setter(ItemFactory.HugeBeanFlat::setStringAttr47)) .addAttribute(String.class, a -> a.name("stringAttr48") .getter(ItemFactory.HugeBeanFlat::getStringAttr48) .setter(ItemFactory.HugeBeanFlat::setStringAttr48)) .addAttribute(String.class, a -> a.name("stringAttr49") .getter(ItemFactory.HugeBeanFlat::getStringAttr49) .setter(ItemFactory.HugeBeanFlat::setStringAttr49)) .addAttribute(String.class, a -> a.name("stringAttr50") .getter(ItemFactory.HugeBeanFlat::getStringAttr50) .setter(ItemFactory.HugeBeanFlat::setStringAttr50)) .addAttribute(String.class, a -> a.name("stringAttr51") .getter(ItemFactory.HugeBeanFlat::getStringAttr51) .setter(ItemFactory.HugeBeanFlat::setStringAttr51)) .addAttribute(String.class, a -> a.name("stringAttr52") .getter(ItemFactory.HugeBeanFlat::getStringAttr52) .setter(ItemFactory.HugeBeanFlat::setStringAttr52)) .addAttribute(String.class, a -> a.name("stringAttr53") .getter(ItemFactory.HugeBeanFlat::getStringAttr53) .setter(ItemFactory.HugeBeanFlat::setStringAttr53)) .addAttribute(String.class, a -> a.name("stringAttr54") .getter(ItemFactory.HugeBeanFlat::getStringAttr54) .setter(ItemFactory.HugeBeanFlat::setStringAttr54)) .addAttribute(String.class, a -> a.name("stringAttr55") .getter(ItemFactory.HugeBeanFlat::getStringAttr55) .setter(ItemFactory.HugeBeanFlat::setStringAttr55)) .addAttribute(String.class, a -> a.name("stringAttr56") .getter(ItemFactory.HugeBeanFlat::getStringAttr56) .setter(ItemFactory.HugeBeanFlat::setStringAttr56)) .addAttribute(String.class, a -> a.name("stringAttr57") .getter(ItemFactory.HugeBeanFlat::getStringAttr57) .setter(ItemFactory.HugeBeanFlat::setStringAttr57)) .addAttribute(String.class, a -> a.name("stringAttr58") .getter(ItemFactory.HugeBeanFlat::getStringAttr58) .setter(ItemFactory.HugeBeanFlat::setStringAttr58)) .addAttribute(String.class, a -> a.name("stringAttr59") .getter(ItemFactory.HugeBeanFlat::getStringAttr59) .setter(ItemFactory.HugeBeanFlat::setStringAttr59)) .addAttribute(String.class, a -> a.name("stringAttr60") .getter(ItemFactory.HugeBeanFlat::getStringAttr60) .setter(ItemFactory.HugeBeanFlat::setStringAttr60)) .addAttribute(String.class, a -> a.name("stringAttr61") .getter(ItemFactory.HugeBeanFlat::getStringAttr61) .setter(ItemFactory.HugeBeanFlat::setStringAttr61)) .addAttribute(String.class, a -> a.name("stringAttr62") .getter(ItemFactory.HugeBeanFlat::getStringAttr62) .setter(ItemFactory.HugeBeanFlat::setStringAttr62)) .addAttribute(String.class, a -> a.name("stringAttr63") .getter(ItemFactory.HugeBeanFlat::getStringAttr63) .setter(ItemFactory.HugeBeanFlat::setStringAttr63)) .build(); @Override protected Map<String, AttributeValue> asItem(TinyBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("stringAttr", av(b.getStringAttr())); return builder.build(); } @Override protected Map<String, AttributeValue> asItem(SmallBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("stringAttr", av(b.getStringAttr())); builder.put("binaryAttr", av(b.getBinaryAttr())); List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList()); builder.put("listAttr", av(listAttr)); return builder.build(); } @Override protected Map<String, AttributeValue> asItem(HugeBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("hashKey", av(b.getHashKey())); builder.put("stringAttr", av(b.getStringAttr())); builder.put("binaryAttr", av(b.getBinaryAttr())); List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList()); builder.put("listAttr", av(listAttr)); Map<String, AttributeValue> mapAttr1 = b.getMapAttr1().entrySet().stream().collect( Collectors.toMap(Map.Entry::getKey, e -> av(e.getValue()))); builder.put("mapAttr1", av(mapAttr1)); Map<String, AttributeValue> mapAttr2 = b.getMapAttr2().entrySet().stream().collect( Collectors.toMap(Map.Entry::getKey, e -> av(e.getValue().stream().map(this::av).collect(Collectors.toList())))); builder.put("mapAttr2", av(mapAttr2)); Map<String, AttributeValue> mapAttr3 = b.getMapAttr3().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> { List<Map<String, List<SdkBytes>>> value = e.getValue(); AttributeValue valueAv = av(value.stream().map(m -> av(m.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, ee -> av(ee.getValue().stream().map(this::av).collect(Collectors.toList())))))) .collect(Collectors.toList())); return valueAv; })); builder.put("mapAttr3", av(mapAttr3)); return builder.build(); } @Override protected AttributeValue av(String val) { return AttributeValue.builder().s(val).build(); } @Override protected AttributeValue av(List<AttributeValue> val) { return AttributeValue.builder().l(val).build(); } @Override protected AttributeValue av(Map<String, AttributeValue> val) { return AttributeValue.builder().m(val).build(); } @Override protected AttributeValue av(SdkBytes val) { return AttributeValue.builder().b(val).build(); } }
2,790
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbDeleteItemClient.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.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; public final class V2TestDynamoDbDeleteItemClient extends V2TestDynamoDbBaseClient { private static final DeleteItemResponse DELETE_ITEM_RESPONSE = DeleteItemResponse.builder().build(); public V2TestDynamoDbDeleteItemClient(Blackhole bh) { super(bh); } @Override public DeleteItemResponse deleteItem(DeleteItemRequest deleteItemRequest) { bh.consume(deleteItemRequest); return DELETE_ITEM_RESPONSE; } }
2,791
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/EnhancedClientPutV1MapperComparisonBenchmark.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @BenchmarkMode(Mode.Throughput) @Warmup(iterations = 5) @Measurement(iterations = 5) @Fork(2) @State(Scope.Benchmark) public class EnhancedClientPutV1MapperComparisonBenchmark { private static final V2ItemFactory V2_ITEM_FACTORY = new V2ItemFactory(); private static final V1ItemFactory V1_ITEM_FACTORY = new V1ItemFactory(); private static final DynamoDBMapperConfig MAPPER_CONFIG = DynamoDBMapperConfig.builder() .withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.PUT) .build(); @Benchmark public void v2Put(TestState s) { s.v2Table.putItem(s.testItem.v2Bean); } @Benchmark public void v1Put(TestState s) { s.v1DdbMapper.save(s.testItem.v1Bean); } private static DynamoDbClient getV2Client(Blackhole bh) { return new V2TestDynamoDbPutItemClient(bh); } private static AmazonDynamoDB getV1Client(Blackhole bh) { return new V1TestDynamoDbPutItemClient(bh); } @State(Scope.Benchmark) public static class TestState { @Param({"TINY", "SMALL", "HUGE", "HUGE_FLAT"}) public TestItem testItem; private DynamoDbTable v2Table; private DynamoDBMapper v1DdbMapper; @Setup public void setup(Blackhole bh) { DynamoDbEnhancedClient v2DdbEnh = DynamoDbEnhancedClient.builder() .dynamoDbClient(getV2Client(bh)) .build(); v2Table = v2DdbEnh.table(testItem.name(), testItem.schema); v1DdbMapper = new DynamoDBMapper(getV1Client(bh), MAPPER_CONFIG); } public enum TestItem { TINY( V2ItemFactory.TINY_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.tinyBean(), V1_ITEM_FACTORY.v1TinyBean() ), SMALL( V2ItemFactory.SMALL_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.smallBean(), V1_ITEM_FACTORY.v1SmallBean() ), HUGE( V2ItemFactory.HUGE_BEAN_TABLE_SCHEMA, V2_ITEM_FACTORY.hugeBean(), V1_ITEM_FACTORY.v1hugeBean() ), HUGE_FLAT( V2ItemFactory.HUGE_BEAN_FLAT_TABLE_SCHEMA, V2_ITEM_FACTORY.hugeBeanFlat(), V1_ITEM_FACTORY.v1HugeBeanFlat() ), ; // V2 private TableSchema<?> schema; private Object v2Bean; // V1 private Object v1Bean; TestItem(TableSchema<?> schema, Object v2Bean, Object v1Bean) { this.schema = schema; this.v2Bean = v2Bean; this.v1Bean = v1Bean; } } } }
2,792
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbPutItemClient.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.PutItemResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbPutItemClient extends V1TestDynamoDbBaseClient { private static final PutItemResult PUT_ITEM_RESULT = new PutItemResult(); public V1TestDynamoDbPutItemClient(Blackhole bh) { super(bh); } @Override public PutItemResult putItem(PutItemRequest request) { bh.consume(request); return PUT_ITEM_RESULT; } }
2,793
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbGetItemClient.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import com.amazonaws.services.dynamodbv2.model.GetItemResult; import org.openjdk.jmh.infra.Blackhole; public class V1TestDynamoDbGetItemClient extends V1TestDynamoDbBaseClient { private final GetItemResult getItemResult; public V1TestDynamoDbGetItemClient(Blackhole bh, GetItemResult getItemResult) { super(bh); this.getItemResult = getItemResult; } @Override public GetItemResult getItem(GetItemRequest request) { bh.consume(request); return getItemResult; } }
2,794
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1TestDynamoDbBaseClient.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.AbstractAmazonDynamoDB; import org.openjdk.jmh.infra.Blackhole; abstract class V1TestDynamoDbBaseClient extends AbstractAmazonDynamoDB { protected final Blackhole bh; protected V1TestDynamoDbBaseClient(Blackhole bh) { this.bh = bh; } }
2,795
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbScanClient.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.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable; public final class V2TestDynamoDbScanClient extends V2TestDynamoDbBaseClient { private final ScanResponse scanResponse; public V2TestDynamoDbScanClient(Blackhole bh, ScanResponse scanResponse) { super(bh); this.scanResponse = scanResponse; } @Override public ScanResponse scan(ScanRequest scanRequest) { bh.consume(scanRequest); return this.scanResponse; } @Override public ScanIterable scanPaginator(ScanRequest scanRequest) { return new ScanIterable(this, scanRequest); } }
2,796
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbUpdateItemClient.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.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; public final class V2TestDynamoDbUpdateItemClient extends V2TestDynamoDbBaseClient { private final UpdateItemResponse updateItemResponse; public V2TestDynamoDbUpdateItemClient(Blackhole bh, UpdateItemResponse updateItemResponse) { super(bh); this.updateItemResponse = updateItemResponse; } @Override public UpdateItemResponse updateItem(UpdateItemRequest updateItemRequest) { bh.consume(updateItemRequest); return this.updateItemResponse; } }
2,797
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V2TestDynamoDbGetItemClient.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.benchmark.enhanced.dynamodb; import org.openjdk.jmh.infra.Blackhole; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; public final class V2TestDynamoDbGetItemClient extends V2TestDynamoDbBaseClient { private final GetItemResponse getItemResponse; public V2TestDynamoDbGetItemClient(Blackhole bh, GetItemResponse getItemResponse) { super(bh); this.getItemResponse = getItemResponse; } @Override public GetItemResponse getItem(GetItemRequest getItemRequest) { bh.consume(getItemRequest); return getItemResponse; } }
2,798
0
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced
Create_ds/aws-sdk-java-v2/test/sdk-benchmarks/src/main/java/software/amazon/awssdk/benchmark/enhanced/dynamodb/V1ItemFactory.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.benchmark.enhanced.dynamodb; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.util.ImmutableMapParameter; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.core.SdkBytes; public final class V1ItemFactory extends ItemFactory<AttributeValue> { public V1HugeBean v1hugeBean() { return V1HugeBean.fromHugeBean(super.hugeBean()); } public V1TinyBean v1TinyBean() { return V1TinyBean.fromTinyBean(super.tinyBean()); } public V1SmallBean v1SmallBean() { return V1SmallBean.fromSmallBean(super.smallBean()); } public V1HugeBeanFlat v1HugeBeanFlat() { return V1HugeBeanFlat.fromHugeBeanFlat(super.hugeBeanFlat()); } @Override protected Map<String, AttributeValue> asItem(TinyBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("stringAttr", av(b.getStringAttr())); return builder.build(); } @Override protected Map<String, AttributeValue> asItem(SmallBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("stringAttr", av(b.getStringAttr())); builder.put("binaryAttr", av(b.getBinaryAttr())); List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList()); builder.put("listAttr", av(listAttr)); return builder.build(); } @Override protected Map<String, AttributeValue> asItem(HugeBean b) { ImmutableMapParameter.Builder<String, AttributeValue> builder = ImmutableMapParameter.builder(); builder.put("hashKey", av(b.getHashKey())); builder.put("stringAttr", av(b.getStringAttr())); builder.put("binaryAttr", av(b.getBinaryAttr())); List<AttributeValue> listAttr = b.getListAttr().stream().map(this::av).collect(Collectors.toList()); builder.put("listAttr", av(listAttr)); Map<String, AttributeValue> mapAttr1 = b.getMapAttr1().entrySet().stream().collect( Collectors.toMap(Map.Entry::getKey, e -> av(e.getValue()))); builder.put("mapAttr1", av(mapAttr1)); Map<String, AttributeValue> mapAttr2 = b.getMapAttr2().entrySet().stream().collect( Collectors.toMap(Map.Entry::getKey, e -> av(e.getValue().stream().map(this::av).collect(Collectors.toList())))); builder.put("mapAttr2", av(mapAttr2)); Map<String, AttributeValue> mapAttr3 = b.getMapAttr3().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> { List<Map<String, List<SdkBytes>>> value = e.getValue(); AttributeValue valueAv = av(value.stream().map(m -> av(m.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, ee -> av(ee.getValue().stream().map(this::av).collect(Collectors.toList())))))) .collect(Collectors.toList())); return valueAv; })); builder.put("mapAttr3", av(mapAttr3)); return builder.build(); } @Override protected AttributeValue av(String val) { return new AttributeValue() .withS(val); } @Override protected AttributeValue av(List<AttributeValue> val) { return new AttributeValue() .withL(val); } @Override protected AttributeValue av(Map<String, AttributeValue> val) { return new AttributeValue() .withM(val); } @Override protected AttributeValue av(SdkBytes val) { return new AttributeValue() .withB(val.asByteBuffer()); } @DynamoDBTable(tableName = "V1TinyBean") public static class V1TinyBean extends ItemFactory.TinyBean { public V1TinyBean() { } public V1TinyBean(String stringAttr) { super.setStringAttr(stringAttr); } @DynamoDBHashKey @Override public String getStringAttr() { return super.getStringAttr(); } private static V1TinyBean fromTinyBean(TinyBean tb) { V1TinyBean b = new V1TinyBean(); b.setStringAttr(tb.getStringAttr()); return b; } } @DynamoDBTable(tableName = "V1SmallBean") public static class V1SmallBean extends ItemFactory.SmallBean { private ByteBuffer binaryAttr; public V1SmallBean() { } public V1SmallBean(String stringAttr) { super.setStringAttr(stringAttr); } @DynamoDBHashKey @Override public String getStringAttr() { return super.getStringAttr(); } @DynamoDBAttribute(attributeName = "binaryAttr") public ByteBuffer getBinaryAttrV1() { return binaryAttr; } @DynamoDBAttribute(attributeName = "binaryAttr") public void setBinaryAttrV1(ByteBuffer binaryAttr) { this.binaryAttr = binaryAttr; } @DynamoDBAttribute @Override public List<String> getListAttr() { return super.getListAttr(); } private static V1SmallBean fromSmallBean(SmallBean sb) { V1SmallBean b = new V1SmallBean(); b.setStringAttr(sb.getStringAttr()); b.setBinaryAttrV1(sb.getBinaryAttr().asByteBuffer()); b.setListAttr(sb.getListAttr()); return b; } } @DynamoDBTable(tableName = "V1HugeBean") public static class V1HugeBean extends ItemFactory.HugeBean { private ByteBuffer binaryAttr; private Map<String, ByteBuffer> mapAttr1; private Map<String, List<ByteBuffer>> mapAttr2; private Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3; public V1HugeBean() { } public V1HugeBean(String stringAttr) { super.setStringAttr(stringAttr); } @DynamoDBHashKey @Override public String getStringAttr() { return super.getStringAttr(); } @DynamoDBAttribute @Override public String getHashKey() { return super.getHashKey(); } @DynamoDBAttribute(attributeName = "binaryAttr") public ByteBuffer getBinaryAttrV1() { return binaryAttr; } @DynamoDBAttribute(attributeName = "binaryAttr") public void setBinaryAttrV1(ByteBuffer binaryAttr) { this.binaryAttr = binaryAttr; } @DynamoDBAttribute @Override public List<String> getListAttr() { return super.getListAttr(); } @DynamoDBAttribute(attributeName = "mapAttr1") public Map<String, ByteBuffer> getMapAttr1V1() { return mapAttr1; } @DynamoDBAttribute(attributeName = "mapAttr1") public void setMapAttr1V1(Map<String, ByteBuffer> mapAttr1) { this.mapAttr1 = mapAttr1; } @DynamoDBAttribute(attributeName = "mapAttr2") public Map<String, List<ByteBuffer>> getMapAttr2V1() { return mapAttr2; } @DynamoDBAttribute(attributeName = "mapAttr2") public void setMapAttr2V1(Map<String, List<ByteBuffer>> mapAttr2) { this.mapAttr2 = mapAttr2; } @DynamoDBAttribute(attributeName = "mapAttr3") public Map<String, List<Map<String, List<ByteBuffer>>>> getMapAttr3V1() { return mapAttr3; } @DynamoDBAttribute(attributeName = "mapAttr3") public void setMapAttr3V1(Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3) { this.mapAttr3 = mapAttr3; } private static V1HugeBean fromHugeBean(HugeBean hb) { V1HugeBean b = new V1HugeBean(); b.setHashKey(hb.getHashKey()); b.setStringAttr(hb.getStringAttr()); b.setBinaryAttrV1(hb.getBinaryAttr().asByteBuffer()); b.setListAttr(hb.getListAttr()); b.setMapAttr1V1(hb.getMapAttr1() .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().asByteBuffer()))); b.setMapAttr2V1(hb.getMapAttr2() .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(SdkBytes::asByteBuffer).collect(Collectors.toList())))); Map<String, List<Map<String, List<ByteBuffer>>>> mapAttr3V1 = hb.getMapAttr3() .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream() .map(m -> m.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, ee -> ee.getValue().stream().map(SdkBytes::asByteBuffer).collect(Collectors.toList()) ))) .collect(Collectors.toList()))); b.setMapAttr3V1(mapAttr3V1); return b; } } @DynamoDBTable(tableName = "V1HugeBeanFlat") public static class V1HugeBeanFlat extends HugeBeanFlat { public V1HugeBeanFlat() { } public V1HugeBeanFlat(String stringAttr) { this.setStringAttr1(stringAttr); } @DynamoDBAttribute(attributeName = "stringAttr1") @DynamoDBHashKey @Override public String getStringAttr1() { return super.getStringAttr1(); } @DynamoDBAttribute(attributeName = "stringAttr2") @Override public String getStringAttr2() { return super.getStringAttr2(); } @DynamoDBAttribute(attributeName = "stringAttr3") @Override public String getStringAttr3() { return super.getStringAttr3(); } @DynamoDBAttribute(attributeName = "stringAttr4") @Override public String getStringAttr4() { return super.getStringAttr4(); } @DynamoDBAttribute(attributeName = "stringAttr5") @Override public String getStringAttr5() { return super.getStringAttr5(); } @DynamoDBAttribute(attributeName = "stringAttr6") @Override public String getStringAttr6() { return super.getStringAttr6(); } @DynamoDBAttribute(attributeName = "stringAttr7") @Override public String getStringAttr7() { return super.getStringAttr7(); } @DynamoDBAttribute(attributeName = "stringAttr8") @Override public String getStringAttr8() { return super.getStringAttr8(); } @DynamoDBAttribute(attributeName = "stringAttr9") @Override public String getStringAttr9() { return super.getStringAttr9(); } @DynamoDBAttribute(attributeName = "stringAttr10") @Override public String getStringAttr10() { return super.getStringAttr10(); } @DynamoDBAttribute(attributeName = "stringAttr11") @Override public String getStringAttr11() { return super.getStringAttr11(); } @DynamoDBAttribute(attributeName = "stringAttr12") @Override public String getStringAttr12() { return super.getStringAttr12(); } @DynamoDBAttribute(attributeName = "stringAttr13") @Override public String getStringAttr13() { return super.getStringAttr13(); } @DynamoDBAttribute(attributeName = "stringAttr14") @Override public String getStringAttr14() { return super.getStringAttr14(); } @DynamoDBAttribute(attributeName = "stringAttr15") @Override public String getStringAttr15() { return super.getStringAttr15(); } @DynamoDBAttribute(attributeName = "stringAttr16") @Override public String getStringAttr16() { return super.getStringAttr16(); } @DynamoDBAttribute(attributeName = "stringAttr17") @Override public String getStringAttr17() { return super.getStringAttr17(); } @DynamoDBAttribute(attributeName = "stringAttr18") @Override public String getStringAttr18() { return super.getStringAttr18(); } @DynamoDBAttribute(attributeName = "stringAttr19") @Override public String getStringAttr19() { return super.getStringAttr19(); } @DynamoDBAttribute(attributeName = "stringAttr20") @Override public String getStringAttr20() { return super.getStringAttr20(); } @DynamoDBAttribute(attributeName = "stringAttr21") @Override public String getStringAttr21() { return super.getStringAttr21(); } @DynamoDBAttribute(attributeName = "stringAttr22") @Override public String getStringAttr22() { return super.getStringAttr22(); } @DynamoDBAttribute(attributeName = "stringAttr23") @Override public String getStringAttr23() { return super.getStringAttr23(); } @DynamoDBAttribute(attributeName = "stringAttr24") @Override public String getStringAttr24() { return super.getStringAttr24(); } @DynamoDBAttribute(attributeName = "stringAttr25") @Override public String getStringAttr25() { return super.getStringAttr25(); } @DynamoDBAttribute(attributeName = "stringAttr26") @Override public String getStringAttr26() { return super.getStringAttr26(); } @DynamoDBAttribute(attributeName = "stringAttr27") @Override public String getStringAttr27() { return super.getStringAttr27(); } @DynamoDBAttribute(attributeName = "stringAttr28") @Override public String getStringAttr28() { return super.getStringAttr28(); } @DynamoDBAttribute(attributeName = "stringAttr29") @Override public String getStringAttr29() { return super.getStringAttr29(); } @DynamoDBAttribute(attributeName = "stringAttr30") @Override public String getStringAttr30() { return super.getStringAttr30(); } @DynamoDBAttribute(attributeName = "stringAttr31") @Override public String getStringAttr31() { return super.getStringAttr31(); } @DynamoDBAttribute(attributeName = "stringAttr32") @Override public String getStringAttr32() { return super.getStringAttr32(); } @DynamoDBAttribute(attributeName = "stringAttr33") @Override public String getStringAttr33() { return super.getStringAttr33(); } @DynamoDBAttribute(attributeName = "stringAttr34") @Override public String getStringAttr34() { return super.getStringAttr34(); } @DynamoDBAttribute(attributeName = "stringAttr35") @Override public String getStringAttr35() { return super.getStringAttr35(); } @DynamoDBAttribute(attributeName = "stringAttr36") @Override public String getStringAttr36() { return super.getStringAttr36(); } @DynamoDBAttribute(attributeName = "stringAttr37") @Override public String getStringAttr37() { return super.getStringAttr37(); } @DynamoDBAttribute(attributeName = "stringAttr38") @Override public String getStringAttr38() { return super.getStringAttr38(); } @DynamoDBAttribute(attributeName = "stringAttr39") @Override public String getStringAttr39() { return super.getStringAttr39(); } @DynamoDBAttribute(attributeName = "stringAttr40") @Override public String getStringAttr40() { return super.getStringAttr40(); } @DynamoDBAttribute(attributeName = "stringAttr41") @Override public String getStringAttr41() { return super.getStringAttr41(); } @DynamoDBAttribute(attributeName = "stringAttr42") @Override public String getStringAttr42() { return super.getStringAttr42(); } @DynamoDBAttribute(attributeName = "stringAttr43") @Override public String getStringAttr43() { return super.getStringAttr43(); } @DynamoDBAttribute(attributeName = "stringAttr44") @Override public String getStringAttr44() { return super.getStringAttr44(); } @DynamoDBAttribute(attributeName = "stringAttr45") @Override public String getStringAttr45() { return super.getStringAttr45(); } @DynamoDBAttribute(attributeName = "stringAttr46") @Override public String getStringAttr46() { return super.getStringAttr46(); } @DynamoDBAttribute(attributeName = "stringAttr47") @Override public String getStringAttr47() { return super.getStringAttr47(); } @DynamoDBAttribute(attributeName = "stringAttr48") @Override public String getStringAttr48() { return super.getStringAttr48(); } @DynamoDBAttribute(attributeName = "stringAttr49") @Override public String getStringAttr49() { return super.getStringAttr49(); } @DynamoDBAttribute(attributeName = "stringAttr50") @Override public String getStringAttr50() { return super.getStringAttr50(); } @DynamoDBAttribute(attributeName = "stringAttr51") @Override public String getStringAttr51() { return super.getStringAttr51(); } @DynamoDBAttribute(attributeName = "stringAttr52") @Override public String getStringAttr52() { return super.getStringAttr52(); } @DynamoDBAttribute(attributeName = "stringAttr53") @Override public String getStringAttr53() { return super.getStringAttr53(); } @Override @DynamoDBAttribute(attributeName = "stringAttr54") public String getStringAttr54() { return super.getStringAttr54(); } @DynamoDBAttribute(attributeName = "stringAttr55") @Override public String getStringAttr55() { return super.getStringAttr55(); } @DynamoDBAttribute(attributeName = "stringAttr56") @Override public String getStringAttr56() { return super.getStringAttr56(); } @DynamoDBAttribute(attributeName = "stringAttr57") @Override public String getStringAttr57() { return super.getStringAttr57(); } @DynamoDBAttribute(attributeName = "stringAttr58") @Override public String getStringAttr58() { return super.getStringAttr58(); } @DynamoDBAttribute(attributeName = "stringAttr59") @Override public String getStringAttr59() { return super.getStringAttr59(); } @DynamoDBAttribute(attributeName = "stringAttr60") @Override public String getStringAttr60() { return super.getStringAttr60(); } @DynamoDBAttribute(attributeName = "stringAttr61") @Override public String getStringAttr61() { return super.getStringAttr61(); } @DynamoDBAttribute(attributeName = "stringAttr62") @Override public String getStringAttr62() { return super.getStringAttr62(); } @DynamoDBAttribute(attributeName = "stringAttr63") @Override public String getStringAttr63() { return super.getStringAttr63(); } public static V1HugeBeanFlat fromHugeBeanFlat(HugeBeanFlat b) { V1HugeBeanFlat bean = new V1HugeBeanFlat(); for (int i = 1; i <= 63; ++i) { try { Method setter = V1HugeBeanFlat.class.getMethod("setStringAttr" + i, String.class); Method getter = HugeBeanFlat.class.getMethod("getStringAttr" + i); setter.setAccessible(true); setter.invoke(bean, getter.invoke(b)); } catch (Throwable t) { throw new RuntimeException(t); } } return bean; } } }
2,799