index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/BaseApiCallAttemptTimeoutTest.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.protocol.tests.timeout;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.Pair;
public abstract class BaseApiCallAttemptTimeoutTest extends BaseTimeoutTest {
protected static final Duration API_CALL_ATTEMPT_TIMEOUT = Duration.ofMillis(100);
protected static final Duration DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT = Duration.ofMillis(50);
protected static final Duration DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT = Duration.ofMillis(150);
@Test
public void nonstreamingOperation200_finishedWithinTime_shouldSucceed() throws Exception {
stubSuccessResponse(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT);
verifySuccessResponseNotTimedOut();
}
@Test
public void nonstreamingOperation200_notFinishedWithinTime_shouldTimeout() {
stubSuccessResponse(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT);
verifyTimedOut();
}
@Test
public void nonstreamingOperation500_finishedWithinTime_shouldNotTimeout() throws Exception {
stubErrorResponse(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT);
verifyFailedResponseNotTimedOut();
}
@Test
public void nonstreamingOperation500_notFinishedWithinTime_shouldTimeout() {
stubErrorResponse(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT);
verifyTimedOut();
}
@Test
public void streamingOperation_finishedWithinTime_shouldSucceed() throws Exception {
stubSuccessResponse(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT);
verifySuccessResponseNotTimedOut();
}
@Test
public void streamingOperation_notFinishedWithinTime_shouldTimeout() {
stubSuccessResponse(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT);
verifyTimedOut();
}
@Test
public void firstAttemptTimeout_retryFinishWithInTime_shouldNotTimeout() throws Exception {
mockHttpClient().stubResponses(Pair.of(mockResponse(200), DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT),
Pair.of(mockResponse(200), DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT));
assertThat(retryableCallable().call()).isNotNull();
verifyRequestCount(2);
}
@Test
public void firstAttemptTimeout_retryFinishWithInTime500_shouldNotTimeout() {
mockHttpClient().stubResponses(Pair.of(mockResponse(200), DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT),
Pair.of(mockResponse(500), DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT));
verifyRetraybleFailedResponseNotTimedOut();
verifyRequestCount(2);
}
@Test
public void allAttemptsNotFinishedWithinTime_shouldTimeout() {
stubSuccessResponse(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT);
verifyRetryableTimeout();
}
}
| 2,400 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/BaseTimeoutTest.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.protocol.tests.timeout;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import org.assertj.core.api.ThrowableAssert;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
public abstract class BaseTimeoutTest {
/**
* @return the exception to assert
*/
protected abstract Consumer<ThrowableAssert.ThrowingCallable> timeoutExceptionAssertion();
protected abstract Consumer<ThrowableAssert.ThrowingCallable> serviceExceptionAssertion();
protected abstract Callable callable();
protected abstract Callable retryableCallable();
protected abstract Callable streamingCallable();
protected abstract void stubSuccessResponse(Duration delayAfterTimeout);
protected abstract void stubErrorResponse(Duration delayAfterTimeout);
protected void verifySuccessResponseNotTimedOut() throws Exception {
assertThat(callable().call()).isNotNull();
}
protected void verifyFailedResponseNotTimedOut() throws Exception {
serviceExceptionAssertion().accept(() -> callable().call());
}
protected void verifyRetraybleFailedResponseNotTimedOut() {
serviceExceptionAssertion().accept(() -> retryableCallable().call());
}
protected void verifyTimedOut() {
timeoutExceptionAssertion().accept(() -> callable().call());
assertThat(Thread.currentThread().isInterrupted()).isFalse();
}
protected void verifyRetryableTimeout() {
timeoutExceptionAssertion().accept(() -> retryableCallable().call());
}
public static class SlowBytesResponseTransformer<ResponseT> implements ResponseTransformer<ResponseT, ResponseBytes<ResponseT>> {
private ResponseTransformer<ResponseT, ResponseBytes<ResponseT>> delegate;
public SlowBytesResponseTransformer() {
this.delegate = ResponseTransformer.toBytes();
}
@Override
public ResponseBytes<ResponseT> transform(ResponseT response, AbortableInputStream inputStream) throws Exception {
wastingTimeInterruptibly();
return delegate.transform(response, inputStream);
}
}
public static class SlowInputStreamResponseTransformer<ResponseT> implements ResponseTransformer<ResponseT, ResponseInputStream<ResponseT>> {
private ResponseTransformer<ResponseT, ResponseInputStream<ResponseT>> delegate;
public SlowInputStreamResponseTransformer() {
this.delegate = ResponseTransformer.toInputStream();
}
@Override
public ResponseInputStream<ResponseT> transform(ResponseT response, AbortableInputStream inputStream) throws Exception {
wastingTimeInterruptibly();
return delegate.transform(response, inputStream);
}
}
public static class SlowFileResponseTransformer<ResponseT> implements ResponseTransformer<ResponseT, ResponseT> {
private ResponseTransformer<ResponseT, ResponseT> delegate;
public SlowFileResponseTransformer() {
try {
this.delegate = ResponseTransformer.toFile(File.createTempFile("ApiCallTiemoutTest", ".txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public ResponseT transform(ResponseT response, AbortableInputStream inputStream) throws Exception {
wastingTimeInterruptibly();
return delegate.transform(response, inputStream);
}
}
public static class SlowCustomResponseTransformer implements ResponseTransformer {
@Override
public Object transform(Object response, AbortableInputStream inputStream) throws Exception {
wastingTimeInterruptibly();
return null;
}
}
public static void wastingTimeInterruptibly() throws InterruptedException {
Thread.sleep(1200);
}
public abstract MockHttpClient mockHttpClient();
public static HttpExecuteResponse mockResponse(int statusCode) {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(statusCode)
.build())
.build();
}
public void verifyRequestCount(int requestCount) {
assertThat(mockHttpClient().getRequests().size()).isEqualTo(requestCount);
}
}
| 2,401 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/async/AsyncApiCallTimeoutTest.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.protocol.tests.timeout.async;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.retry.backoff.BackoffStrategy;
import software.amazon.awssdk.protocol.tests.timeout.BaseApiCallTimeoutTest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Test apiCallTimeout feature for asynchronous operations.
*/
public class AsyncApiCallTimeoutTest extends BaseApiCallTimeoutTest {
private ProtocolRestJsonAsyncClient client;
private ProtocolRestJsonAsyncClient clientWithRetry;
private MockAsyncHttpClient mockClient;
@BeforeEach
public void setup() {
mockClient = new MockAsyncHttpClient();
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallTimeout(TIMEOUT)
.retryPolicy(RetryPolicy.none()))
.build();
clientWithRetry = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_1)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallTimeout(TIMEOUT)
.retryPolicy(RetryPolicy.builder()
.backoffStrategy(BackoffStrategy.none())
.numRetries(1)
.build()))
.httpClient(mockClient)
.build();
}
@AfterEach
public void cleanUp() {
mockClient.reset();
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> timeoutExceptionAssertion() {
return c -> assertThatThrownBy(c).hasCauseInstanceOf(ApiCallTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> serviceExceptionAssertion() {
return c -> assertThatThrownBy(c).hasCauseInstanceOf(ProtocolRestJsonException.class);
}
@Override
protected Callable callable() {
return () -> client.allTypes().join();
}
@Override
protected Callable retryableCallable() {
return () -> clientWithRetry.allTypes().join();
}
@Override
protected Callable streamingCallable() {
return () -> client.streamingOutputOperation(SdkBuilder::build, AsyncResponseTransformer.toBytes()).join();
}
@Override
protected void stubSuccessResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(200), delay);
}
@Override
protected void stubErrorResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(500), delay);
}
@Override
public MockHttpClient mockHttpClient() {
return mockClient;
}
@Test
public void increaseTimeoutInRequestOverrideConfig_shouldTakePrecedence() {
ProtocolRestJsonAsyncClient asyncClient = createClientWithMockClient(mockClient);
mockClient.stubNextResponse(mockResponse(200), DELAY_AFTER_TIMEOUT);
CompletableFuture<AllTypesResponse> allTypesResponseCompletableFuture =
asyncClient.allTypes(b -> b.overrideConfiguration(c -> c.apiCallTimeout(DELAY_AFTER_TIMEOUT.plus(Duration.ofSeconds(1)))));
AllTypesResponse response = allTypesResponseCompletableFuture.join();
assertThat(response).isNotNull();
}
public ProtocolRestJsonAsyncClient createClientWithMockClient(MockAsyncHttpClient mockClient) {
return ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallTimeout(TIMEOUT)
.retryPolicy(RetryPolicy.none()))
.build();
}
}
| 2,402 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/async/AsyncApiCallAttemptsTimeoutTest.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.protocol.tests.timeout.async;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.protocol.tests.timeout.BaseApiCallAttemptTimeoutTest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationResponse;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
/**
* Test apiCallAttemptTimeout feature for asynchronous operations.
*/
public class AsyncApiCallAttemptsTimeoutTest extends BaseApiCallAttemptTimeoutTest {
private ProtocolRestJsonAsyncClient client;
private ProtocolRestJsonAsyncClient clientWithRetry;
private MockAsyncHttpClient mockClient;
@BeforeEach
public void setup() {
mockClient = new MockAsyncHttpClient();
client = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallAttemptTimeout(API_CALL_ATTEMPT_TIMEOUT)
.retryPolicy(RetryPolicy.none()))
.build();
clientWithRetry = ProtocolRestJsonAsyncClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallAttemptTimeout(API_CALL_ATTEMPT_TIMEOUT)
.retryPolicy(RetryPolicy.builder()
.numRetries(1)
.build()))
.build();
}
@Override
public MockHttpClient mockHttpClient() {
return mockClient;
}
@AfterEach
public void cleanUp() {
mockClient.reset();
}
@Test
public void streamingOperation_slowTransformer_shouldThrowApiCallAttemptTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT);
CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> future = client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new SlowResponseTransformer<>());
assertThatThrownBy(future::join)
.hasCauseInstanceOf(ApiCallAttemptTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> timeoutExceptionAssertion() {
return c -> assertThatThrownBy(c).hasCauseInstanceOf(ApiCallAttemptTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> serviceExceptionAssertion() {
return c -> assertThatThrownBy(c).hasCauseInstanceOf(ProtocolRestJsonException.class);
}
@Override
protected Callable callable() {
return () -> client.allTypes().join();
}
@Override
protected Callable retryableCallable() {
return () -> clientWithRetry.allTypes().join();
}
@Override
protected Callable streamingCallable() {
return () -> client.streamingOutputOperation(StreamingOutputOperationRequest.builder().build(),
AsyncResponseTransformer.toBytes()).join();
}
@Override
protected void stubSuccessResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(200), delay);
}
@Override
protected void stubErrorResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(500), delay);
}
private static final class SlowResponseTransformer<ResponseT>
implements AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> {
private final AtomicInteger callCount = new AtomicInteger(0);
private final AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> delegate;
private SlowResponseTransformer() {
this.delegate = AsyncResponseTransformer.toBytes();
}
@Override
public CompletableFuture<ResponseBytes<ResponseT>> prepare() {
return delegate.prepare()
.thenApply(r -> {
try {
Thread.sleep(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT.toMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
return r;
});
}
public int currentCallCount() {
return callCount.get();
}
@Override
public void onResponse(ResponseT response) {
callCount.incrementAndGet();
delegate.onResponse(response);
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
delegate.onStream(publisher);
}
@Override
public void exceptionOccurred(Throwable throwable) {
delegate.exceptionOccurred(throwable);
}
}
}
| 2,403 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/sync/SyncApiCallTimeoutTest.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.protocol.tests.timeout.sync;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.retry.backoff.BackoffStrategy;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.protocol.tests.timeout.BaseApiCallTimeoutTest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Test apiCallTimeout feature for synchronous operations.
*/
public class SyncApiCallTimeoutTest extends BaseApiCallTimeoutTest {
private ProtocolRestJsonClient client;
private ProtocolRestJsonClient clientWithRetry;
private MockSyncHttpClient mockClient;
@BeforeEach
public void setup() {
mockClient = new MockSyncHttpClient();
client = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallTimeout(TIMEOUT)
.retryPolicy(RetryPolicy.none()))
.build();
clientWithRetry = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(b -> b.apiCallTimeout(TIMEOUT)
.retryPolicy(RetryPolicy.builder()
.backoffStrategy(BackoffStrategy.none())
.numRetries(1)
.build()))
.build();
}
@AfterEach
public void cleanUp() {
mockClient.reset();
}
@Test
public void increaseTimeoutInRequestOverrideConfig_shouldTakePrecedence() {
stubSuccessResponse(DELAY_AFTER_TIMEOUT);
AllTypesResponse response =
client.allTypes(b -> b.overrideConfiguration(c -> c.apiCallTimeout(DELAY_AFTER_TIMEOUT.plusMillis(1000))));
assertThat(response).isNotNull();
}
@Test
public void streamingOperation_slowFileTransformer_shouldThrowApiCallAttemptTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_TIMEOUT);
assertThatThrownBy(() -> client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new SlowFileResponseTransformer<>()))
.isInstanceOf(ApiCallTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> timeoutExceptionAssertion() {
return c -> assertThatThrownBy(c).isInstanceOf(ApiCallTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> serviceExceptionAssertion() {
return c -> assertThatThrownBy(c).isInstanceOf(ProtocolRestJsonException.class);
}
@Override
protected Callable callable() {
return () -> client.allTypes();
}
@Override
protected Callable retryableCallable() {
return () -> clientWithRetry.allTypes();
}
@Override
protected Callable streamingCallable() {
return () -> client.streamingOutputOperation(SdkBuilder::build, ResponseTransformer.toBytes());
}
@Override
protected void stubSuccessResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(200), delay);
}
@Override
protected void stubErrorResponse(Duration delay) {
mockClient.stubNextResponse(mockResponse(500), delay);
}
@Override
public MockHttpClient mockHttpClient() {
return mockClient;
}
}
| 2,404 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/sync/SyncStreamingOperationApiCallAttemptTimeoutTest.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.protocol.tests.timeout.sync;
import java.time.Duration;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
/**
* A set of tests to test ApiCallTimeout for synchronous streaming operations because they are tricky.
*/
public class SyncStreamingOperationApiCallAttemptTimeoutTest extends BaseSyncStreamingTimeoutTest {
@Override
Class<? extends Exception> expectedException() {
return ApiCallAttemptTimeoutException.class;
}
@Override
ClientOverrideConfiguration clientOverrideConfiguration() {
return ClientOverrideConfiguration.builder().apiCallAttemptTimeout(Duration.ofMillis(TIMEOUT)).retryPolicy(RetryPolicy.none()).build();
}
}
| 2,405 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/sync/SyncStreamingOperationApiCallTimeoutTest.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.protocol.tests.timeout.sync;
import java.time.Duration;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
/**
* A set of tests to test ApiCallTimeout for synchronous streaming operations because they are tricky.
*/
public class SyncStreamingOperationApiCallTimeoutTest extends BaseSyncStreamingTimeoutTest {
@Override
Class<? extends Exception> expectedException() {
return ApiCallTimeoutException.class;
}
@Override
ClientOverrideConfiguration clientOverrideConfiguration() {
return ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofMillis(TIMEOUT))
.retryPolicy(RetryPolicy.none())
.build();
}
}
| 2,406 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/sync/SyncApiCallAttemptTimeoutTest.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.protocol.tests.timeout.sync;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.protocol.tests.timeout.BaseApiCallAttemptTimeoutTest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Test apiCallAttemptTimeout feature for synchronous calls.
*/
public class SyncApiCallAttemptTimeoutTest extends BaseApiCallAttemptTimeoutTest {
private ProtocolRestJsonClient client;
private ProtocolRestJsonClient clientWithRetry;
private MockSyncHttpClient mockSyncHttpClient;
@BeforeEach
public void setup() {
mockSyncHttpClient = new MockSyncHttpClient();
client = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockSyncHttpClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(
b -> b.apiCallAttemptTimeout(API_CALL_ATTEMPT_TIMEOUT)
.retryPolicy(RetryPolicy.none()))
.build();
clientWithRetry = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockSyncHttpClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(
b -> b.apiCallAttemptTimeout(API_CALL_ATTEMPT_TIMEOUT)
.retryPolicy(RetryPolicy.builder()
.numRetries(1)
.build()))
.build();
}
@AfterEach
public void cleanUp() {
mockSyncHttpClient.reset();
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> timeoutExceptionAssertion() {
return c -> assertThatThrownBy(c).isInstanceOf(ApiCallAttemptTimeoutException.class);
}
@Override
protected Consumer<ThrowableAssert.ThrowingCallable> serviceExceptionAssertion() {
return c -> assertThatThrownBy(c).isInstanceOf(ProtocolRestJsonException.class);
}
@Override
protected Callable callable() {
return () -> client.allTypes();
}
@Override
protected Callable retryableCallable() {
return () -> clientWithRetry.allTypes();
}
@Override
protected Callable streamingCallable() {
return () -> client.streamingOutputOperation(SdkBuilder::build, ResponseTransformer.toBytes());
}
@Override
protected void stubSuccessResponse(Duration delay) {
mockSyncHttpClient.stubNextResponse(mockResponse(200), delay);
}
@Override
protected void stubErrorResponse(Duration delay) {
mockSyncHttpClient.stubNextResponse(mockResponse(500), delay);
}
@Override
public MockHttpClient mockHttpClient() {
return mockSyncHttpClient;
}
}
| 2,407 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/timeout/sync/BaseSyncStreamingTimeoutTest.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.protocol.tests.timeout.sync;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static software.amazon.awssdk.protocol.tests.timeout.BaseTimeoutTest.mockResponse;
import java.time.Duration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.protocol.tests.timeout.BaseTimeoutTest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingOutputOperationRequest;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public abstract class BaseSyncStreamingTimeoutTest {
private ProtocolRestJsonClient client;
protected static final int TIMEOUT = 1000;
protected static final Duration DELAY_BEFORE_TIMEOUT = Duration.ofMillis(100);
private MockSyncHttpClient mockSyncHttpClient;
@BeforeEach
public void setup() {
mockSyncHttpClient = new MockSyncHttpClient();
client = ProtocolRestJsonClient.builder()
.region(Region.US_WEST_1)
.httpClient(mockSyncHttpClient)
.credentialsProvider(() -> AwsBasicCredentials.create("akid", "skid"))
.overrideConfiguration(clientOverrideConfiguration())
.build();
}
@Test
public void slowFileTransformer_shouldThrowTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_TIMEOUT);
assertThatThrownBy(() -> client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new BaseTimeoutTest.SlowFileResponseTransformer<>()))
.isInstanceOf(expectedException());
verifyInterruptStatusClear();
}
@Test
public void slowBytesTransformer_shouldThrowTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_TIMEOUT);
assertThatThrownBy(() -> client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new BaseTimeoutTest.SlowBytesResponseTransformer<>()))
.isInstanceOf(expectedException());
verifyInterruptStatusClear();
}
@Test
public void slowInputTransformer_shouldThrowTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_TIMEOUT);
assertThatThrownBy(() -> client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new BaseTimeoutTest.SlowInputStreamResponseTransformer<>()))
.isInstanceOf(expectedException());
verifyInterruptStatusClear();
}
@Test
public void slowCustomResponseTransformer_shouldThrowTimeoutException() {
stubSuccessResponse(DELAY_BEFORE_TIMEOUT);
assertThatThrownBy(() -> client
.streamingOutputOperation(
StreamingOutputOperationRequest.builder().build(), new BaseTimeoutTest.SlowCustomResponseTransformer()))
.isInstanceOf(expectedException());
verifyInterruptStatusClear();
}
abstract Class<? extends Exception> expectedException();
abstract ClientOverrideConfiguration clientOverrideConfiguration();
private void verifyInterruptStatusClear() {
assertThat(Thread.currentThread().isInterrupted()).isFalse();
}
private void stubSuccessResponse(Duration delay) {
mockSyncHttpClient.stubNextResponse(mockResponse(200), delay);
}
}
| 2,408 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/crc32/AwsJsonAsyncCrc32ChecksumTests.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.protocol.tests.crc32;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import com.github.tomakehurst.wiremock.common.SingleRootFileSource;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.Crc32MismatchException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocoljsonrpc.ProtocolJsonRpcAsyncClient;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesRequest;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesResponse;
import software.amazon.awssdk.services.protocoljsonrpccustomized.ProtocolJsonRpcCustomizedAsyncClient;
import software.amazon.awssdk.services.protocoljsonrpccustomized.model.SimpleRequest;
import software.amazon.awssdk.services.protocoljsonrpccustomized.model.SimpleResponse;
import software.amazon.awssdk.utils.builder.SdkBuilder;
public class AwsJsonAsyncCrc32ChecksumTests {
@Rule
public WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig()
.port(0)
.fileSource(new SingleRootFileSource
("src/test/resources")));
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
private static final String JSON_BODY_GZIP = "compressed_json_body.gz";
private static final String JSON_BODY_Crc32_CHECKSUM = "3049587505";
private static final String JSON_BODY_GZIP_Crc32_CHECKSUM = "3023995622";
private static final String JSON_BODY_EXTRA_DATA_GZIP = "compressed_json_body_with_extra_data.gz";
private static final String JSON_BODY_EXTRA_DATA_GZIP_Crc32_CHECKSUM = "1561543715";
private static final StaticCredentialsProvider FAKE_CREDENTIALS_PROVIDER =
StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"));
private ProtocolJsonRpcCustomizedAsyncClient customizedJsonRpcAsync;
private ProtocolJsonRpcAsyncClient jsonRpcAsync;
@Before
public void setup() {
jsonRpcAsync = ProtocolJsonRpcAsyncClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
customizedJsonRpcAsync = ProtocolJsonRpcCustomizedAsyncClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" +
mockServer.port()))
.build();
}
@Test
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsValid() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
SimpleResponse result = customizedJsonRpcAsync.simple(SimpleRequest.builder().build()).get();
assertEquals("foo", result.stringMember());
}
/**
* See https://github.com/aws/aws-sdk-java/issues/1018. With GZIP there is apparently a chance there can be some extra
* stuff/padding beyond the JSON document. Jackson's JsonParser won't necessarily read this if it's able to close the JSON
* object. After unmarshalling the response, the SDK should consume all the remaining bytes from the stream to ensure the
* Crc32 calculated is accurate.
*/
@Test
public void clientCalculatesCrc32FromCompressedData_ExtraData_WhenCrc32IsValid() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_EXTRA_DATA_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_EXTRA_DATA_GZIP)));
SimpleResponse result = customizedJsonRpcAsync.simple(SimpleRequest.builder().build()).get();
assertEquals("foo", result.stringMember());
}
@Test
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsInvalid_ThrowsException() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
assertThatThrownBy(() -> customizedJsonRpcAsync.simple(SdkBuilder::build).get())
.hasRootCauseInstanceOf(Crc32MismatchException.class);
}
@Test
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsValid() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
AllTypesResponse result =
jsonRpcAsync.allTypes(AllTypesRequest.builder().build()).get();
assertEquals("foo", result.stringMember());
}
@Test
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsInvalid_ThrowsException() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
assertThatThrownBy(() -> jsonRpcAsync.allTypes(AllTypesRequest.builder().build()).get())
.hasRootCauseInstanceOf(Crc32MismatchException.class);
}
@Test
public void useGzipFalse_WhenCrc32IsValid() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
AllTypesResponse result =
jsonRpcAsync.allTypes(AllTypesRequest.builder().build()).get();
assertEquals("foo", result.stringMember());
}
@Test
public void useGzipFalse_WhenCrc32IsInvalid_ThrowException() throws Exception {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
assertThatThrownBy(() -> jsonRpcAsync.allTypes(AllTypesRequest.builder().build()).get())
.hasRootCauseInstanceOf(Crc32MismatchException.class);
}
}
| 2,409 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/crc32/AwsJsonCrc32ChecksumTests.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.protocol.tests.crc32;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import com.github.tomakehurst.wiremock.common.SingleRootFileSource;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocoljsonrpc.ProtocolJsonRpcClient;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesRequest;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesResponse;
import software.amazon.awssdk.services.protocoljsonrpccustomized.ProtocolJsonRpcCustomizedClient;
import software.amazon.awssdk.services.protocoljsonrpccustomized.model.SimpleRequest;
import software.amazon.awssdk.services.protocoljsonrpccustomized.model.SimpleResponse;
public class AwsJsonCrc32ChecksumTests {
@Rule
public WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig()
.port(0)
.fileSource(new SingleRootFileSource("src/test/resources")));
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
private static final String JSON_BODY_GZIP = "compressed_json_body.gz";
private static final String JSON_BODY_Crc32_CHECKSUM = "3049587505";
private static final String JSON_BODY_GZIP_Crc32_CHECKSUM = "3023995622";
private static final String JSON_BODY_EXTRA_DATA_GZIP = "compressed_json_body_with_extra_data.gz";
private static final String JSON_BODY_EXTRA_DATA_GZIP_Crc32_CHECKSUM = "1561543715";
private static final StaticCredentialsProvider FAKE_CREDENTIALS_PROVIDER =
StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar"));
@Test
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsValid() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolJsonRpcCustomizedClient jsonRpc = ProtocolJsonRpcCustomizedClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
SimpleResponse result = jsonRpc.simple(SimpleRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
/**
* See https://github.com/aws/aws-sdk-java/issues/1018. With GZIP there is apparently a chance there can be some extra
* stuff/padding beyond the JSON document. Jackson's JsonParser won't necessarily read this if it's able to close the JSON
* object. After unmarshalling the response, the SDK should consume all the remaining bytes from the stream to ensure the
* Crc32 calculated is accurate.
*/
@Test
public void clientCalculatesCrc32FromCompressedData_ExtraData_WhenCrc32IsValid() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_EXTRA_DATA_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_EXTRA_DATA_GZIP)));
ProtocolJsonRpcCustomizedClient jsonRpc = ProtocolJsonRpcCustomizedClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
SimpleResponse result = jsonRpc.simple(SimpleRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsInvalid_ThrowsException() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolJsonRpcCustomizedClient jsonRpc = ProtocolJsonRpcCustomizedClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
jsonRpc.simple(SimpleRequest.builder().build());
}
@Test
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsValid() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolJsonRpcClient jsonRpc = ProtocolJsonRpcClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
AllTypesResponse result =
jsonRpc.allTypes(AllTypesRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsInvalid_ThrowsException() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolJsonRpcClient jsonRpc = ProtocolJsonRpcClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
jsonRpc.allTypes(AllTypesRequest.builder().build());
}
@Test
public void useGzipFalse_WhenCrc32IsValid() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
ProtocolJsonRpcClient jsonRpc = ProtocolJsonRpcClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
AllTypesResponse result =
jsonRpc.allTypes(AllTypesRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void useGzipFalse_WhenCrc32IsInvalid_ThrowException() {
stubFor(post(urlEqualTo("/")).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
ProtocolJsonRpcClient jsonRpc = ProtocolJsonRpcClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
jsonRpc.allTypes(AllTypesRequest.builder().build());
}
}
| 2,410 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/crc32/RestJsonCrc32ChecksumTests.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.protocol.tests.crc32;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import com.github.tomakehurst.wiremock.common.SingleRootFileSource;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesResponse;
import software.amazon.awssdk.services.protocolrestjsoncustomized.ProtocolRestJsonCustomizedClient;
import software.amazon.awssdk.services.protocolrestjsoncustomized.model.SimpleRequest;
import software.amazon.awssdk.services.protocolrestjsoncustomized.model.SimpleResponse;
public class RestJsonCrc32ChecksumTests {
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
private static final String JSON_BODY_GZIP = "compressed_json_body.gz";
private static final String JSON_BODY_Crc32_CHECKSUM = "3049587505";
private static final String JSON_BODY_GZIP_Crc32_CHECKSUM = "3023995622";
private static final String RESOURCE_PATH = "/2016-03-11/allTypes";
private static final AwsCredentialsProvider FAKE_CREDENTIALS_PROVIDER = StaticCredentialsProvider.create(
AwsBasicCredentials.create("foo", "bar"));
@Rule
public WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig()
.port(0)
.fileSource(
new SingleRootFileSource("src/test/resources")));
@Test
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsValid() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolRestJsonCustomizedClient client = ProtocolRestJsonCustomizedClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
SimpleResponse result = client.simple(SimpleRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void clientCalculatesCrc32FromCompressedData_WhenCrc32IsInvalid_ThrowsException() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolRestJsonCustomizedClient client = ProtocolRestJsonCustomizedClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
client.simple(SimpleRequest.builder().build());
}
@Test
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsValid() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
AllTypesResponse result =
client.allTypes(AllTypesRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void clientCalculatesCrc32FromDecompressedData_WhenCrc32IsInvalid_ThrowsException() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Encoding", "gzip")
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBodyFile(JSON_BODY_GZIP)));
ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
client.allTypes(AllTypesRequest.builder().build());
}
@Test
public void useGzipFalse_WhenCrc32IsValid() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
AllTypesResponse result =
client.allTypes(AllTypesRequest.builder().build());
Assert.assertEquals("foo", result.stringMember());
}
@Test(expected = SdkClientException.class)
public void useGzipFalse_WhenCrc32IsInvalid_ThrowException() {
stubFor(post(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse()
.withStatus(200)
.withHeader("x-amz-crc32", JSON_BODY_GZIP_Crc32_CHECKSUM)
.withBody(JSON_BODY)));
ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.credentialsProvider(FAKE_CREDENTIALS_PROVIDER)
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.build();
client.allTypes(AllTypesRequest.builder().build());
}
}
| 2,411 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/endpoint/EndpointTraitTest.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.protocol.tests.endpoint;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.ExecutableHttpRequest;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocoljsonendpointtrait.ProtocolJsonEndpointTraitClient;
import software.amazon.awssdk.services.protocoljsonendpointtrait.ProtocolJsonEndpointTraitClientBuilder;
import software.amazon.awssdk.services.protocoljsonendpointtrait.model.EndpointTraitOneRequest;
import software.amazon.awssdk.services.protocoljsonendpointtrait.model.EndpointTraitTwoRequest;
@RunWith(MockitoJUnitRunner.class)
public class EndpointTraitTest {
@Mock
private SdkHttpClient mockHttpClient;
@Mock
private ExecutableHttpRequest abortableCallable;
private ProtocolJsonEndpointTraitClient client;
private ProtocolJsonEndpointTraitClient clientWithDisabledHostPrefix;
@Before
public void setup() throws Exception {
client = clientBuilder().build();
clientWithDisabledHostPrefix = clientBuilder().overrideConfiguration(
ClientOverrideConfiguration.builder()
.putAdvancedOption(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, true)
.build()).build();
when(mockHttpClient.prepareRequest(any())).thenReturn(abortableCallable);
when(abortableCallable.call()).thenThrow(SdkClientException.create("Dummy exception"));
}
@Test
public void hostExpression_withoutInputMemberLabel() throws URISyntaxException {
try {
client.endpointTraitOne(EndpointTraitOneRequest.builder().build());
Assert.fail("Expected an exception");
} catch (SdkClientException exception) {
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture());
SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest();
assertThat(request.host()).isEqualTo("data.localhost.com");
assertThat(request.port()).isEqualTo(443);
assertThat(request.encodedPath()).isEqualTo("/");
assertThat(request.getUri()).isEqualTo(new URI("http://data.localhost.com:443/"));
}
}
@Test
public void hostExpression_withInputMemberLabel() throws URISyntaxException {
try {
client.endpointTraitTwo(EndpointTraitTwoRequest.builder()
.stringMember("123456")
.pathIdempotentToken("dummypath")
.build());
Assert.fail("Expected an exception");
} catch (SdkClientException exception) {
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture());
SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest();
assertThat(request.host()).isEqualTo("123456-localhost.com");
assertThat(request.port()).isEqualTo(443);
assertThat(request.encodedPath()).isEqualTo("/dummypath");
assertThat(request.getUri()).isEqualTo(new URI("http://123456-localhost.com:443/dummypath"));
}
}
@Test (expected = IllegalArgumentException.class)
public void validationException_whenInputMember_inHostPrefix_isNull() {
client.endpointTraitTwo(EndpointTraitTwoRequest.builder().build());
}
@Test (expected = IllegalArgumentException.class)
public void validationException_whenInputMember_inHostPrefix_isEmpty() {
client.endpointTraitTwo(EndpointTraitTwoRequest.builder().stringMember("").build());
}
@Test
public void clientWithDisabledHostPrefix_withoutInputMemberLabel_usesOriginalUri() {
try {
clientWithDisabledHostPrefix.endpointTraitOne(EndpointTraitOneRequest.builder().build());
Assert.fail("Expected an exception");
} catch (SdkClientException exception) {
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture());
SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest();
assertThat(request.host()).isEqualTo("localhost.com");
}
}
@Test
public void clientWithDisabledHostPrefix_withInputMemberLabel_usesOriginalUri() {
try {
clientWithDisabledHostPrefix.endpointTraitTwo(EndpointTraitTwoRequest.builder()
.stringMember("123456")
.build());
Assert.fail("Expected an exception");
} catch (SdkClientException exception) {
ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class);
verify(mockHttpClient).prepareRequest(httpRequestCaptor.capture());
SdkHttpRequest request = httpRequestCaptor.getAllValues().get(0).httpRequest();
assertThat(request.host()).isEqualTo("localhost.com");
}
}
private StaticCredentialsProvider mockCredentials() {
return StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
}
private String getEndpoint() {
return "http://localhost.com:443";
}
private ProtocolJsonEndpointTraitClientBuilder clientBuilder() {
return ProtocolJsonEndpointTraitClient.builder()
.httpClient(mockHttpClient)
.credentialsProvider(mockCredentials())
.region(Region.US_EAST_1)
.endpointOverride(URI.create(getEndpoint()));
}
}
| 2,412 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/exception/RestJsonExceptionTests.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.protocol.tests.exception;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.head;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static software.amazon.awssdk.protocol.tests.util.exception.ExceptionTestUtils.stub404Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.time.Instant;
import java.util.AbstractMap.SimpleEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolrestjson.model.EmptyModeledException;
import software.amazon.awssdk.services.protocolrestjson.model.ExplicitPayloadAndHeadersException;
import software.amazon.awssdk.services.protocolrestjson.model.HeadOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.ImplicitPayloadException;
import software.amazon.awssdk.services.protocolrestjson.model.MultiLocationOperationRequest;
import software.amazon.awssdk.services.protocolrestjson.model.ProtocolRestJsonException;
/**
* Exception related tests for AWS REST JSON.
*/
public class RestJsonExceptionTests {
private static final String ALL_TYPES_PATH = "/2016-03-11/allTypes";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestJsonClient client;
@Before
public void setupClient() {
client = ProtocolRestJsonClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void unmodeledException_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH, "{\"__type\": \"SomeUnknownType\"}");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void modeledException_UnmarshalledIntoModeledException() {
stub404Response(ALL_TYPES_PATH, "{\"__type\": \"EmptyModeledException\"}");
assertThrowsException(this::callAllTypes, EmptyModeledException.class);
}
@Test
public void modeledExceptionWithMembers_UnmarshalledIntoModeledException() {
stub404Response(ALL_TYPES_PATH, "");
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse().withStatus(404)
.withHeader("x-amz-string", "foo")
.withHeader("x-amz-integer", "42")
.withHeader("x-amz-long", "9001")
.withHeader("x-amz-double", "1234.56")
.withHeader("x-amz-float", "789.10")
.withHeader("x-amz-timestamp", "Sun, 25 Jan 2015 08:00:00 GMT")
.withHeader("x-amz-boolean", "true")
.withBody("{\"__type\": \"ExplicitPayloadAndHeadersException\", \"StringMember\": \"foobar\"}")));
try {
callAllTypes();
} catch (ExplicitPayloadAndHeadersException e) {
assertEquals("foo", e.stringHeader());
assertEquals(42, (int) e.integerHeader());
assertEquals(9001, (long) e.longHeader());
assertEquals(1234.56, e.doubleHeader(), 0.1);
assertEquals(789.10, e.floatHeader(), 0.1);
assertEquals(Instant.ofEpochMilli(1422172800000L), e.timestampHeader());
assertEquals(true, e.booleanHeader());
assertEquals("foobar", e.payloadMember().stringMember());
}
}
@Test
public void modeledExceptionWithImplicitPayloadMembers_UnmarshalledIntoModeledException() {
stub404Response(ALL_TYPES_PATH, "");
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse().withStatus(404)
.withBody("{\"__type\": \"ImplicitPayloadException\", "
+ "\"StringMember\": \"foo\","
+ "\"IntegerMember\": 42,"
+ "\"LongMember\": 9001,"
+ "\"DoubleMember\": 1234.56,"
+ "\"FloatMember\": 789.10,"
+ "\"TimestampMember\": 1398796238.123,"
+ "\"BooleanMember\": true,"
+ "\"BlobMember\": \"dGhlcmUh\","
+ "\"ListMember\": [\"valOne\", \"valTwo\"],"
+ "\"MapMember\": {\"keyOne\": \"valOne\", \"keyTwo\": \"valTwo\"},"
+ "\"SimpleStructMember\": {\"StringMember\": \"foobar\"}"
+ "}")));
try {
callAllTypes();
} catch (ImplicitPayloadException e) {
assertThat(e.stringMember()).isEqualTo("foo");
assertThat(e.integerMember()).isEqualTo(42);
assertThat(e.longMember()).isEqualTo(9001);
assertThat(e.doubleMember()).isEqualTo(1234.56);
assertThat(e.floatMember()).isEqualTo(789.10f);
assertThat(e.timestampMember()).isEqualTo(Instant.ofEpochMilli(1398796238123L));
assertThat(e.booleanMember()).isEqualTo(true);
assertThat(e.blobMember().asUtf8String()).isEqualTo("there!");
assertThat(e.listMember()).contains("valOne", "valTwo");
assertThat(e.mapMember())
.containsOnly(new SimpleEntry<>("keyOne", "valOne"),
new SimpleEntry<>("keyTwo", "valTwo"));
assertThat(e.simpleStructMember().stringMember()).isEqualTo("foobar");
}
}
@Test
public void modeledException_HasExceptionMetadataSet() {
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")
.withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestJson");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")
.withHeader("x-amz-id-2", "5678")
.withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestJson");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isEqualTo("5678");
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void emptyErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH, "");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void malformedErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH, "THIS ISN'T JSON");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void modeledExceptionInHeadRequest_UnmarshalledIntoModeledException() {
stubFor(head(urlEqualTo("/2016-03-11/headOperation"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("x-amzn-ErrorType", "EmptyModeledException")));
assertThrowsException(() -> client.headOperation(HeadOperationRequest.builder().build()), EmptyModeledException.class);
}
@Test
public void unmodeledExceptionInHeadRequest_UnmarshalledIntoModeledException() {
stubFor(head(urlEqualTo("/2016-03-11/headOperation"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("x-amzn-ErrorType", "SomeUnknownType")));
assertThrowsServiceBaseException(() -> client.headOperation(HeadOperationRequest.builder().build()));
}
@Test
public void nullPathParam_ThrowsSdkClientException() {
assertThrowsSdkClientException(() -> client.multiLocationOperation(MultiLocationOperationRequest.builder().build()));
}
@Test
public void emptyPathParam_ThrowsSdkClientException() {
assertThrowsSdkClientException(() -> client.multiLocationOperation(MultiLocationOperationRequest.builder().pathParam("").build()));
}
private void callAllTypes() {
client.allTypes(AllTypesRequest.builder().build());
}
private void assertThrowsServiceBaseException(Runnable runnable) {
assertThrowsException(runnable, ProtocolRestJsonException.class);
}
private void assertThrowsSdkClientException(Runnable runnable) {
assertThrowsException(runnable, SdkClientException.class);
}
private void assertThrowsException(Runnable runnable, Class<? extends Exception> expectedException) {
try {
runnable.run();
} catch (Exception e) {
assertEquals(expectedException, e.getClass());
}
}
}
| 2,413 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/exception/AwsJsonExceptionTest.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.protocol.tests.exception;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.protocol.tests.util.exception.ExceptionTestUtils.stub404Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.time.Instant;
import java.util.AbstractMap.SimpleEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocoljsonrpc.ProtocolJsonRpcClient;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesRequest;
import software.amazon.awssdk.services.protocoljsonrpc.model.EmptyModeledException;
import software.amazon.awssdk.services.protocoljsonrpc.model.ImplicitPayloadException;
import software.amazon.awssdk.services.protocoljsonrpc.model.ProtocolJsonRpcException;
/**
* Exception related tests for AWS/JSON RPC.
*/
public class AwsJsonExceptionTest {
private static final String PATH = "/";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolJsonRpcClient client;
@Before
public void setupClient() {
client = ProtocolJsonRpcClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void unmodeledException_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "{\"__type\": \"SomeUnknownType\"}");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolJsonRpcException.class);
}
@Test
public void modeledExceptionWithImplicitPayloadMembers_UnmarshalledIntoModeledException() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse().withStatus(404)
.withBody("{\"__type\": \"ImplicitPayloadException\", "
+ "\"StringMember\": \"foo\","
+ "\"IntegerMember\": 42,"
+ "\"LongMember\": 9001,"
+ "\"DoubleMember\": 1234.56,"
+ "\"FloatMember\": 789.10,"
+ "\"TimestampMember\": 1398796238.123,"
+ "\"BooleanMember\": true,"
+ "\"BlobMember\": \"dGhlcmUh\","
+ "\"ListMember\": [\"valOne\", \"valTwo\"],"
+ "\"MapMember\": {\"keyOne\": \"valOne\", \"keyTwo\": \"valTwo\"},"
+ "\"SimpleStructMember\": {\"StringMember\": \"foobar\"}"
+ "}")));
try {
client.allTypes();
} catch (ImplicitPayloadException e) {
assertThat(e.stringMember()).isEqualTo("foo");
assertThat(e.integerMember()).isEqualTo(42);
assertThat(e.longMember()).isEqualTo(9001);
assertThat(e.doubleMember()).isEqualTo(1234.56);
assertThat(e.floatMember()).isEqualTo(789.10f);
assertThat(e.timestampMember()).isEqualTo(Instant.ofEpochMilli(1398796238123L));
assertThat(e.booleanMember()).isEqualTo(true);
assertThat(e.blobMember().asUtf8String()).isEqualTo("there!");
assertThat(e.listMember()).contains("valOne", "valTwo");
assertThat(e.mapMember())
.containsOnly(new SimpleEntry<>("keyOne", "valOne"),
new SimpleEntry<>("keyTwo", "valTwo"));
assertThat(e.simpleStructMember().stringMember()).isEqualTo("foobar");
}
}
@Test
public void modeledException_UnmarshalledIntoModeledException() {
stub404Response(PATH, "{\"__type\": \"EmptyModeledException\"}");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(EmptyModeledException.class);
}
@Test
public void modeledException_HasExceptionMetadataSet() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")
.withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolJsonRpc");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")
.withHeader("x-amz-id-2", "5678")
.withBody("{\"__type\": \"EmptyModeledException\", \"Message\": \"This is the service message\"}")));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolJsonRpc");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isEqualTo("5678");
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void emptyErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolJsonRpcException.class);
}
@Test
public void malformedErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "THIS ISN'T JSON");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolJsonRpcException.class);
}
}
| 2,414 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/exception/Ec2ExceptionTests.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.protocol.tests.exception;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.protocol.tests.util.exception.ExceptionTestUtils.stub404Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolec2.ProtocolEc2Client;
import software.amazon.awssdk.services.protocolec2.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolec2.model.ProtocolEc2Exception;
public class Ec2ExceptionTests {
private static final String PATH = "/";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolEc2Client client;
@Before
public void setupClient() {
client = ProtocolEc2Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void unmodeledException_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH,
"<Response><Errors><Error><Code>UnmodeledException</Code></Error></Errors></Response>");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolEc2Exception.class);
}
@Test
public void emptyErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolEc2Exception.class);
}
@Test
public void malformedErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "THIS ISN'T XML");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolEc2Exception.class);
}
}
| 2,415 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/exception/QueryExceptionTests.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.protocol.tests.exception;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.protocol.tests.util.exception.ExceptionTestUtils.stub404Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.time.Instant;
import java.util.AbstractMap.SimpleEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolquery.ProtocolQueryClient;
import software.amazon.awssdk.services.protocolquery.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolquery.model.EmptyModeledException;
import software.amazon.awssdk.services.protocolquery.model.ImplicitPayloadException;
import software.amazon.awssdk.services.protocolquery.model.ProtocolQueryException;
public class QueryExceptionTests {
private static final String PATH = "/";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolQueryClient client;
@Before
public void setupClient() {
client = ProtocolQueryClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void unmodeledException_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>UnmodeledException</Code></Error></ErrorResponse>");
assertThatThrownBy(() -> client.allTypes(AllTypesRequest.builder().build()))
.isExactlyInstanceOf(ProtocolQueryException.class);
}
@Test
public void unmodeledException_ErrorCodeSetOnServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>UnmodeledException</Code></Error></ErrorResponse>");
AwsServiceException exception = captureServiceException(this::callAllTypes);
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("UnmodeledException");
}
@Test
public void unmodeledExceptionWithMessage_MessageSetOnServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>UnmodeledException</Code><Message>Something happened</Message></Error></ErrorResponse>");
AwsServiceException exception = captureServiceException(this::callAllTypes);
assertThat(exception.awsErrorDetails().errorMessage()).isEqualTo("Something happened");
}
@Test
public void unmodeledException_StatusCodeSetOnServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>UnmodeledException</Code></Error></ErrorResponse>");
SdkServiceException exception = captureServiceException(this::callAllTypes);
assertThat(exception.statusCode()).isEqualTo(404);
}
@Test
public void modeledException_UnmarshalledIntoModeledException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>EmptyModeledException</Code></Error></ErrorResponse>");
try {
callAllTypes();
} catch (EmptyModeledException e) {
assertThat(e).isInstanceOf(ProtocolQueryException.class);
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("EmptyModeledException");
}
}
@Test
public void modeledExceptionWithMessage_MessageSetOnServiceExeption() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>EmptyModeledException</Code><Message>Something happened</Message></Error></ErrorResponse>");
EmptyModeledException exception = captureModeledException(this::callAllTypes);
assertThat(exception.awsErrorDetails().errorMessage()).isEqualTo("Something happened");
}
@Test
public void modeledException_ErrorCodeSetOnServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>EmptyModeledException</Code></Error></ErrorResponse>");
final EmptyModeledException exception = captureModeledException(this::callAllTypes);
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("EmptyModeledException");
}
@Test
public void modeledException_StatusCodeSetOnServiceException() {
stub404Response(PATH,
"<ErrorResponse><Error><Code>EmptyModeledException</Code></Error></ErrorResponse>");
final EmptyModeledException exception = captureModeledException(this::callAllTypes);
assertThat(exception.statusCode()).isEqualTo(404);
}
@Test
public void emptyErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void malformedErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(PATH, "THIS ISN'T XML");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void emptyErrorResponse_UnmarshallsIntoUnknownErrorType() {
stub404Response(PATH, "");
AwsServiceException exception = captureServiceException(this::callAllTypes);
assertThat(exception.statusCode()).isEqualTo(404);
}
@Test
public void malformedErrorResponse_UnmarshallsIntoUnknownErrorType() {
stub404Response(PATH, "THIS ISN'T XML");
AwsServiceException exception = captureServiceException(this::callAllTypes);
assertThat(exception.statusCode()).isEqualTo(404);
}
@Test
public void modeledExceptionWithImplicitPayloadMembers_UnmarshalledIntoModeledException() {
String xml = "<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>";
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse().withStatus(404)
.withBody(xml)));
try {
client.allTypes();
} catch (ImplicitPayloadException e) {
assertThat(e.stringMember()).isEqualTo("foo");
assertThat(e.integerMember()).isEqualTo(42);
assertThat(e.longMember()).isEqualTo(9001);
assertThat(e.doubleMember()).isEqualTo(1234.56);
assertThat(e.floatMember()).isEqualTo(789.10f);
assertThat(e.timestampMember()).isEqualTo(Instant.ofEpochMilli(1422172812000L));
assertThat(e.booleanMember()).isEqualTo(true);
assertThat(e.blobMember().asUtf8String()).isEqualTo("there!");
assertThat(e.listMember()).contains("valOne", "valTwo");
assertThat(e.mapMember())
.containsOnly(new SimpleEntry<>("keyOne", "valOne"),
new SimpleEntry<>("keyTwo", "valTwo"));
assertThat(e.simpleStructMember().stringMember()).isEqualTo("foobar");
}
}
@Test
public void modeledException_HasExceptionMetadataSet() {
String xml = "<ErrorResponse>"
+ " <Error>"
+ " <Code>EmptyModeledException</Code>"
+ " <Message>This is the service message</Message>"
+ " </Error>"
+ " <RequestId>1234</RequestId>"
+ "</ErrorResponse>";
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withBody(xml)));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolQuery");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void modeledException_RequestIDInXml_SetCorrectly() {
String xml = "<ErrorResponse>"
+ " <Error>"
+ " <Code>EmptyModeledException</Code>"
+ " <Message>This is the service message</Message>"
+ " </Error>"
+ " <RequestID>1234</RequestID>"
+ "</ErrorResponse>";
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withBody(xml)));
try {
client.allTypes();
} catch (EmptyModeledException e) {
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
}
}
@Test
public void requestIdInHeader_IsSetOnException() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")));
try {
client.allTypes();
} catch (ProtocolQueryException e) {
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
}
}
@Test
public void requestIdAndExtendedRequestIdInHeader_IsSetOnException() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amzn-RequestId", "1234")
.withHeader("x-amz-id-2", "5678")));
try {
client.allTypes();
} catch (ProtocolQueryException e) {
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isEqualTo("5678");
}
}
@Test
public void alternateRequestIdInHeader_IsSetOnException() {
stubFor(post(urlEqualTo(PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amz-request-id", "1234")));
try {
client.allTypes();
} catch (ProtocolQueryException e) {
assertThat(e.requestId()).isEqualTo("1234");
}
}
private void callAllTypes() {
client.allTypes(AllTypesRequest.builder().build());
}
private void assertThrowsServiceBaseException(Runnable runnable) {
assertThatThrownBy(runnable::run)
.isExactlyInstanceOf(ProtocolQueryException.class);
}
private AwsServiceException captureServiceException(Runnable runnable) {
try {
runnable.run();
return null;
} catch (AwsServiceException exception) {
return exception;
}
}
private EmptyModeledException captureModeledException(Runnable runnable) {
try {
runnable.run();
return null;
} catch (EmptyModeledException exception) {
return exception;
}
}
}
| 2,416 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/exception/RestXmlExceptionTests.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.protocol.tests.exception;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static software.amazon.awssdk.protocol.tests.util.exception.ExceptionTestUtils.stub404Response;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.net.URI;
import java.time.Instant;
import java.util.AbstractMap.SimpleEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocolrestxml.ProtocolRestXmlClient;
import software.amazon.awssdk.services.protocolrestxml.model.AllTypesRequest;
import software.amazon.awssdk.services.protocolrestxml.model.EmptyModeledException;
import software.amazon.awssdk.services.protocolrestxml.model.ImplicitPayloadException;
import software.amazon.awssdk.services.protocolrestxml.model.MultiLocationOperationRequest;
import software.amazon.awssdk.services.protocolrestxml.model.ProtocolRestXmlException;
public class RestXmlExceptionTests {
private static final String ALL_TYPES_PATH = "/2016-03-11/allTypes";
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private ProtocolRestXmlClient client;
@Before
public void setupClient() {
client = ProtocolRestXmlClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build();
}
@Test
public void unmodeledException_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH,
"<ErrorResponse><Error><Code>UnmodeledException</Code></Error></ErrorResponse>");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void modeledException_UnmarshalledIntoModeledException() {
stub404Response(ALL_TYPES_PATH,
"<ErrorResponse><Error><Code>EmptyModeledException</Code></Error></ErrorResponse>");
try {
callAllTypes();
} catch (EmptyModeledException e) {
assertThat(e).isInstanceOf(ProtocolRestXmlException.class);
}
}
@Test
public void modeledExceptionWithImplicitPayloadMembers_UnmarshalledIntoModeledException() {
String xml = "<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>";
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse().withStatus(404)
.withBody(xml)));
try {
client.allTypes();
} catch (ImplicitPayloadException e) {
assertThat(e.stringMember()).isEqualTo("foo");
assertThat(e.integerMember()).isEqualTo(42);
assertThat(e.longMember()).isEqualTo(9001);
assertThat(e.doubleMember()).isEqualTo(1234.56);
assertThat(e.floatMember()).isEqualTo(789.10f);
assertThat(e.timestampMember()).isEqualTo(Instant.ofEpochMilli(1422172812000L));
assertThat(e.booleanMember()).isEqualTo(true);
assertThat(e.blobMember().asUtf8String()).isEqualTo("there!");
assertThat(e.listMember()).contains("valOne", "valTwo");
assertThat(e.mapMember())
.containsOnly(new SimpleEntry<>("keyOne", "valOne"),
new SimpleEntry<>("keyTwo", "valTwo"));
assertThat(e.simpleStructMember().stringMember()).isEqualTo("foobar");
}
}
@Test
public void modeledException_HasExceptionMetadataSet() {
String xml = "<ErrorResponse>"
+ " <Error>"
+ " <Code>EmptyModeledException</Code>"
+ " <Message>This is the service message</Message>"
+ " </Error>"
+ " <RequestId>1234</RequestId>"
+ "</ErrorResponse>";
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse()
.withStatus(404)
.withBody(xml)));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestXml");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isNull();
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void modeledException_HasExceptionMetadataIncludingExtendedRequestIdSet() {
String xml = "<ErrorResponse>"
+ " <Error>"
+ " <Code>EmptyModeledException</Code>"
+ " <Message>This is the service message</Message>"
+ " </Error>"
+ " <RequestId>1234</RequestId>"
+ "</ErrorResponse>";
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amz-id-2", "5678")
.withBody(xml)));
try {
client.allTypes();
} catch (EmptyModeledException e) {
AwsErrorDetails awsErrorDetails = e.awsErrorDetails();
assertThat(awsErrorDetails.errorCode()).isEqualTo("EmptyModeledException");
assertThat(awsErrorDetails.errorMessage()).isEqualTo("This is the service message");
assertThat(awsErrorDetails.serviceName()).isEqualTo("ProtocolRestXml");
assertThat(awsErrorDetails.sdkHttpResponse()).isNotNull();
assertThat(e.requestId()).isEqualTo("1234");
assertThat(e.extendedRequestId()).isEqualTo("5678");
assertThat(e.statusCode()).isEqualTo(404);
}
}
@Test
public void emptyErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH, "");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void malformedErrorResponse_UnmarshalledIntoBaseServiceException() {
stub404Response(ALL_TYPES_PATH, "THIS ISN'T XML");
assertThrowsServiceBaseException(this::callAllTypes);
}
@Test
public void illegalArgumentException_nullPathParam() {
assertThrowsNestedExceptions(() -> client.multiLocationOperation(MultiLocationOperationRequest.builder().build()),
SdkClientException.class,
IllegalArgumentException.class);
}
@Test
public void illegalArgumentException_emptyPathParam() {
assertThrowsNestedExceptions(() -> client.multiLocationOperation(MultiLocationOperationRequest.builder()
.pathParam("")
.build()),
SdkClientException.class,
IllegalArgumentException.class);
}
@Test
public void alternateRequestIdInHeader_IsSetOnException() {
stubFor(post(urlEqualTo(ALL_TYPES_PATH)).willReturn(
aResponse()
.withStatus(404)
.withHeader("x-amz-request-id", "1234")));
try {
client.allTypes();
} catch (ProtocolRestXmlException e) {
assertThat(e.requestId()).isEqualTo("1234");
}
}
private void callAllTypes() {
client.allTypes(AllTypesRequest.builder().build());
}
private void assertThrowsServiceBaseException(Runnable runnable) {
assertThrowsException(runnable, ProtocolRestXmlException.class);
}
private void assertThrowsIllegalArgumentException(Runnable runnable) {
assertThrowsException(runnable, IllegalArgumentException.class);
}
private void assertThrowsNullPointerException(Runnable runnable) {
assertThrowsException(runnable, NullPointerException.class);
}
private void assertThrowsException(Runnable runnable, Class<? extends Exception> expectedException) {
try {
runnable.run();
} catch (Exception e) {
assertEquals(expectedException, e.getClass());
}
}
private void assertThrowsNestedExceptions(Runnable runnable, Class<? extends Exception> parentException,
Class<? extends Exception> nestedException) {
try {
runnable.run();
} catch (Exception e) {
assertEquals(parentException, e.getClass());
assertEquals(nestedException, e.getCause().getClass());
}
}
}
| 2,417 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/chunkedencoding/TransferEncodingChunkedFunctionalTests.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.protocol.tests.chunkedencoding;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.TRANSFER_ENCODING;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.reactivex.Flowable;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonAsyncClient;
import software.amazon.awssdk.services.protocolrestjson.ProtocolRestJsonClient;
import software.amazon.awssdk.services.protocolrestjson.model.StreamingInputOperationChunkedEncodingRequest;
public final class TransferEncodingChunkedFunctionalTests {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
@Test
public void apacheClientStreamingOperation_withoutContentLength_addsTransferEncodingDoesNotAddContentLength() {
stubSuccessfulResponse();
try (ProtocolRestJsonClient client = ProtocolRestJsonClient.builder()
.httpClient(ApacheHttpClient.builder().build())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build()) {
TestContentProvider provider = new TestContentProvider(RandomStringUtils.random(1000).getBytes(StandardCharsets.UTF_8));
RequestBody requestBody = RequestBody.fromContentProvider(provider, "binary/octet-stream");
client.streamingInputOperationChunkedEncoding(StreamingInputOperationChunkedEncodingRequest.builder().build(), requestBody);
verify(postRequestedFor(anyUrl()).withHeader(TRANSFER_ENCODING, equalTo("chunked")));
verify(postRequestedFor(anyUrl()).withoutHeader(CONTENT_LENGTH));
}
}
@Test
public void nettyClientStreamingOperation_withoutContentLength_addsTransferEncodingDoesNotAddContentLength() {
stubSuccessfulResponse();
try (ProtocolRestJsonAsyncClient client = ProtocolRestJsonAsyncClient.builder()
.httpClient(NettyNioAsyncHttpClient.create())
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.build()) {
client.streamingInputOperationChunkedEncoding(StreamingInputOperationChunkedEncodingRequest.builder().build(),
customAsyncRequestBodyWithoutContentLength()).join();
verify(postRequestedFor(anyUrl()).withHeader(TRANSFER_ENCODING, equalTo("chunked")));
}
}
private void stubSuccessfulResponse() {
stubFor(post(anyUrl()).willReturn(aResponse().withStatus(200)));
}
private AsyncRequestBody customAsyncRequestBodyWithoutContentLength() {
return new AsyncRequestBody() {
@Override
public Optional<Long> contentLength() {
return Optional.empty();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
Flowable.fromPublisher(AsyncRequestBody.fromBytes("Random text".getBytes()))
.subscribe(s);
}
};
}
private static final class TestContentProvider implements ContentStreamProvider {
private final byte[] content;
private final List<CloseTrackingInputStream> createdStreams = new ArrayList<>();
private CloseTrackingInputStream currentStream;
private TestContentProvider(byte[] content) {
this.content = content;
}
@Override
public InputStream newStream() {
if (currentStream != null) {
invokeSafely(currentStream::close);
}
currentStream = new CloseTrackingInputStream(new ByteArrayInputStream(content));
createdStreams.add(currentStream);
return currentStream;
}
List<CloseTrackingInputStream> getCreatedStreams() {
return Collections.unmodifiableList(createdStreams);
}
}
private static class CloseTrackingInputStream extends FilterInputStream {
private boolean isClosed = false;
CloseTrackingInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
super.close();
isClosed = true;
}
boolean isClosed() {
return isClosed;
}
}
}
| 2,418 |
0 | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests | Create_ds/aws-sdk-java-v2/test/protocol-tests/src/test/java/software/amazon/awssdk/protocol/tests/clockskew/ClockSkewAdjustmentTest.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.protocol.tests.clockskew;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.net.URI;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkGlobalTime;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.protocoljsonrpc.ProtocolJsonRpcAsyncClient;
import software.amazon.awssdk.services.protocoljsonrpc.ProtocolJsonRpcClient;
import software.amazon.awssdk.services.protocoljsonrpc.model.AllTypesResponse;
import software.amazon.awssdk.utils.DateUtils;
public class ClockSkewAdjustmentTest {
@Rule
public WireMockRule wireMock = new WireMockRule(0);
private static final String SCENARIO = "scenario";
private static final String PATH = "/";
private static final String JSON_BODY = "{\"StringMember\":\"foo\"}";
private ProtocolJsonRpcClient client;
private ProtocolJsonRpcAsyncClient asyncClient;
@Before
public void setupClient() {
SdkGlobalTime.setGlobalTimeOffset(0);
client = createClient(1);
asyncClient = createAsyncClient(1);
}
@Test
public void clockSkewAdjustsOnClockSkewErrors() {
assertAdjusts(Instant.now().plus(5, MINUTES), 400, "RequestTimeTooSkewed");
assertAdjusts(Instant.now().minus(5, MINUTES), 400, "RequestTimeTooSkewed");
assertAdjusts(Instant.now().plus(1, HOURS), 400, "RequestTimeTooSkewed");
assertAdjusts(Instant.now().minus(2, HOURS), 400, "RequestTimeTooSkewed");
assertAdjusts(Instant.now().plus(3, HOURS), 400, "InvalidSignatureException");
assertAdjusts(Instant.now().minus(4, HOURS), 400, "InvalidSignatureException");
assertAdjusts(Instant.now().plus(5, HOURS), 403, "");
assertAdjusts(Instant.now().minus(6, HOURS), 403, "");
}
@Test
public void clockSkewDoesNotAdjustOnNonClockSkewErrors() {
// Force client clock forward 1 hour
Instant clientTime = Instant.now().plus(1, HOURS);
assertAdjusts(clientTime, 400, "RequestTimeTooSkewed");
// Verify scenarios that should not adjust the client time
assertNoAdjust(clientTime, clientTime.plus(1, HOURS), 500, "");
assertNoAdjust(clientTime, clientTime.minus(1, HOURS), 500, "");
assertNoAdjust(clientTime, clientTime.plus(1, HOURS), 404, "");
assertNoAdjust(clientTime, clientTime.minus(1, HOURS), 404, "");
assertNoAdjust(clientTime, clientTime.plus(1, HOURS), 300, "BandwidthLimitExceeded");
assertNoAdjust(clientTime, clientTime.minus(1, HOURS), 300, "BandwidthLimitExceeded");
assertNoAdjust(clientTime, clientTime.plus(1, HOURS), 500, "PriorRequestNotComplete");
assertNoAdjust(clientTime, clientTime.minus(1, HOURS), 500, "PriorRequestNotComplete");
}
@Test
public void clientClockSkewAdjustsWithoutRetries() {
try (ProtocolJsonRpcClient client = createClient(0)) {
clientClockSkewAdjustsWithoutRetries(client::allTypes);
}
try (ProtocolJsonRpcAsyncClient client = createAsyncClient(0)) {
clientClockSkewAdjustsWithoutRetries(() -> client.allTypes().join());
}
}
private void clientClockSkewAdjustsWithoutRetries(Runnable call) {
Instant actualTime = Instant.now();
Instant skewedTime = actualTime.plus(7, HOURS);
// Force the client time forward
stubForResponse(skewedTime, 400, "RequestTimeTooSkewed");
assertThatThrownBy(call::run).isInstanceOfAny(SdkException.class, CompletionException.class);
// Verify the next call uses that time
stubForResponse(actualTime, 200, "");
call.run();
assertSigningDateApproximatelyEquals(getRecordedRequests().get(0), skewedTime);
}
private void assertNoAdjust(Instant clientTime, Instant serviceTime, int statusCode, String errorCode) {
assertNoAdjust(clientTime, serviceTime, statusCode, errorCode, () -> client.allTypes());
assertNoAdjust(clientTime, serviceTime, statusCode, errorCode, () -> asyncClient.allTypes().join());
}
private void assertAdjusts(Instant serviceTime, int statusCode, String errorCode) {
assertAdjusts(serviceTime, statusCode, errorCode, () -> client.allTypes());
assertAdjusts(serviceTime, statusCode, errorCode, () -> asyncClient.allTypes().join());
}
private void assertNoAdjust(Instant clientTime, Instant serviceTime, int statusCode, String errorCode, Runnable methodCall) {
stubForResponse(serviceTime, statusCode, errorCode);
assertThatThrownBy(methodCall::run).isInstanceOfAny(SdkException.class, CompletionException.class);
List<LoggedRequest> requests = getRecordedRequests();
assertThat(requests.size()).isGreaterThanOrEqualTo(1);
requests.forEach(r -> assertSigningDateApproximatelyEquals(r, clientTime));
}
private void assertAdjusts(Instant serviceTime, int statusCode, String errorCode, Supplier<AllTypesResponse> methodCall) {
stubForClockSkewFailureThenSuccess(serviceTime, statusCode, errorCode);
assertThat(methodCall.get().stringMember()).isEqualTo("foo");
List<LoggedRequest> requests = getRecordedRequests();
assertThat(requests.size()).isEqualTo(2);
assertSigningDateApproximatelyEquals(requests.get(1), serviceTime);
}
private Instant parseSigningDate(String signatureDate) {
return Instant.from(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")
.withZone(ZoneId.of("UTC"))
.parse(signatureDate));
}
private void stubForResponse(Instant serviceTime, int statusCode, String errorCode) {
WireMock.reset();
stubFor(post(urlEqualTo(PATH))
.willReturn(aResponse()
.withStatus(statusCode)
.withHeader("x-amzn-ErrorType", errorCode)
.withHeader("Date", DateUtils.formatRfc822Date(serviceTime))
.withBody("{}")));
}
private void stubForClockSkewFailureThenSuccess(Instant serviceTime, int statusCode, String errorCode) {
WireMock.reset();
stubFor(post(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("1")
.willReturn(aResponse()
.withStatus(statusCode)
.withHeader("x-amzn-ErrorType", errorCode)
.withHeader("Date", DateUtils.formatRfc822Date(serviceTime))
.withBody("{}")));
stubFor(post(urlEqualTo(PATH))
.inScenario(SCENARIO)
.whenScenarioStateIs("1")
.willSetStateTo("2")
.willReturn(aResponse()
.withStatus(200)
.withBody(JSON_BODY)));
}
private void assertSigningDateApproximatelyEquals(LoggedRequest request, Instant expectedTime) {
assertThat(parseSigningDate(request.getHeader("X-Amz-Date"))).isBetween(expectedTime.minusSeconds(10), expectedTime.plusSeconds(10));
}
private List<LoggedRequest> getRecordedRequests() {
return findAll(postRequestedFor(urlEqualTo(PATH)));
}
private ProtocolJsonRpcClient createClient(int retryCount) {
return ProtocolJsonRpcClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(c -> c.retryPolicy(r -> r.numRetries(retryCount)))
.build();
}
private ProtocolJsonRpcAsyncClient createAsyncClient(int retryCount) {
return ProtocolJsonRpcAsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_EAST_1)
.endpointOverride(URI.create("http://localhost:" + wireMock.port()))
.overrideConfiguration(c -> c.retryPolicy(r -> r.numRetries(retryCount)))
.build();
}
}
| 2,419 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/core/auth | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/core/auth/policy/PolicyReaderTest.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 static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.auth.policy.Principal.Service;
import software.amazon.awssdk.core.auth.policy.Statement.Effect;
import software.amazon.awssdk.core.auth.policy.conditions.ConditionFactory;
import software.amazon.awssdk.core.auth.policy.conditions.IpAddressCondition;
import software.amazon.awssdk.core.auth.policy.conditions.IpAddressCondition.IpAddressComparisonType;
import software.amazon.awssdk.core.auth.policy.conditions.StringCondition;
import software.amazon.awssdk.core.auth.policy.conditions.StringCondition.StringComparisonType;
/**
* Unit tests for generating AWS policy object from JSON string.
*/
public class PolicyReaderTest {
final String POLICY_VERSION = "2012-10-17";
@Test
public void testPrincipals() {
Policy policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal("accountId1"), new Principal("accountId2"))
.withActions(new Action("action")));
policy = Policy.fromJson(policy.toJson());
assertEquals(1, policy.getStatements().size());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("action", statements.get(0).getActions().get(0).getActionName());
assertEquals("resource", statements.get(0).getResources().get(0).getId());
assertEquals(2, statements.get(0).getPrincipals().size());
assertEquals("AWS", statements.get(0).getPrincipals().get(0).getProvider());
assertEquals("accountId1", statements.get(0).getPrincipals().get(0).getId());
assertEquals("AWS", statements.get(0).getPrincipals().get(1).getProvider());
assertEquals("accountId2", statements.get(0).getPrincipals().get(1).getId());
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow).withResources(new Resource("resource")).withPrincipals(new Principal(
Principal.Service.AmazonEC2), new Principal(Service.AmazonElasticTranscoder))
.withActions(new Action("action")));
policy = Policy.fromJson(policy.toJson());
assertEquals(1, policy.getStatements().size());
statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals(1, statements.get(0).getActions().size());
assertEquals("action", statements.get(0).getActions().get(0).getActionName());
assertEquals(2, statements.get(0).getPrincipals().size());
assertEquals("Service", statements.get(0).getPrincipals().get(0).getProvider());
assertEquals(Principal.Service.AmazonEC2.getServiceId(), statements.get(0).getPrincipals().get(0).getId());
assertEquals("Service", statements.get(0).getPrincipals().get(1).getProvider());
assertEquals(Principal.Service.AmazonElasticTranscoder.getServiceId(), statements.get(0).getPrincipals().get(1).getId());
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow).withResources(new Resource("resource")).withPrincipals(Principal.ALL)
.withActions(new Action("action")));
policy = Policy.fromJson(policy.toJson());
assertEquals(1, policy.getStatements().size());
statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals(1, statements.get(0).getActions().size());
assertEquals("action", statements.get(0).getActions().get(0).getActionName());
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals(Principal.ALL, statements.get(0).getPrincipals().get(0));
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow).withResources(new Resource("resource")).withPrincipals(Principal.ALL_USERS, Principal.ALL_SERVICES, Principal.ALL_WEB_PROVIDERS)
.withActions(new Action("action")));
policy = Policy.fromJson(policy.toJson());
assertEquals(1, policy.getStatements().size());
statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals(1, statements.get(0).getActions().size());
assertEquals("action", statements.get(0).getActions().get(0).getActionName());
assertEquals(3, statements.get(0).getPrincipals().size());
assertThat(statements.get(0).getPrincipals(),
contains(Principal.ALL_USERS, Principal.ALL_SERVICES, Principal.ALL_WEB_PROVIDERS));
}
@Test
public void testMultipleConditionKeysForConditionType() throws Exception {
Policy policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("arn:aws:sqs:us-east-1:987654321000:MyQueue"))
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("foo"))
.withConditions(
new StringCondition(StringComparisonType.StringNotLike, "key1", "foo"),
new StringCondition(StringComparisonType.StringNotLike, "key1", "bar")));
policy = Policy.fromJson(policy.toJson());
assertEquals(1, policy.getStatements().size());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals(1, statements.get(0).getActions().size());
assertEquals("foo", statements.get(0).getActions().get(0).getActionName());
assertEquals(1, statements.get(0).getConditions().size());
assertEquals("StringNotLike", statements.get(0).getConditions().get(0).getType());
assertEquals("key1", statements.get(0).getConditions().get(0).getConditionKey());
assertEquals(2, statements.get(0).getConditions().get(0).getValues().size());
assertEquals("foo", statements.get(0).getConditions().get(0).getValues().get(0));
assertEquals("bar", statements.get(0).getConditions().get(0).getValues().get(1));
}
/**
* Test policy parsing when the "Effect" is not mentioned in a Statement.
* The Effect must be default to "Deny" when it is not mentioned.
*/
@Test
public void testPolicyParsingWithNoEffect() {
String jsonString =
"{" +
"\"Statement\": [{" +
"\"Action\": [" +
"\"elasticmapreduce:*\"," +
"\"iam:PassRole\"" +
"]," +
"\"Resource\": [\"*\"]" +
"}]" +
"}";
Policy policy = Policy.fromJson(jsonString);
assertEquals(1, policy.getStatements().size());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Deny, statements.get(0).getEffect());
assertEquals(1, statements.size());
}
@Test
public void testMultipleStatements() throws Exception {
Policy policy = new Policy("S3PolicyId1");
policy.withStatements(
new Statement(Effect.Allow)
.withId("0")
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action1"))
.withResources(new Resource("resource"))
.withConditions(
new IpAddressCondition("192.168.143.0/24"),
new IpAddressCondition(IpAddressComparisonType.NotIpAddress, "192.168.143.188/32")),
new Statement(Effect.Deny)
.withId("1")
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action2"))
.withResources(new Resource("resource"))
.withConditions(new IpAddressCondition("10.1.2.0/24")));
policy = Policy.fromJson(policy.toJson());
assertEquals(2, policy.getStatements().size());
assertEquals("S3PolicyId1", policy.getId());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("0", statements.get(0).getId());
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals("*", statements.get(0).getPrincipals().get(0).getId());
assertEquals("AWS", statements.get(0).getPrincipals().get(0).getProvider());
assertEquals(1, statements.get(0).getResources().size());
assertEquals("resource", statements.get(0).getResources().get(0).getId());
assertEquals(1, statements.get(0).getActions().size());
assertEquals("action1", statements.get(0).getActions().get(0).getActionName());
assertEquals(2, statements.get(0).getConditions().size());
assertEquals("IpAddress", statements.get(0).getConditions().get(0).getType());
assertEquals(ConditionFactory.SOURCE_IP_CONDITION_KEY, statements.get(0).getConditions().get(0).getConditionKey());
assertEquals(1, statements.get(0).getConditions().get(0).getValues().size());
assertEquals("192.168.143.0/24", statements.get(0).getConditions().get(0).getValues().get(0));
assertEquals("NotIpAddress", statements.get(0).getConditions().get(1).getType());
assertEquals(1, statements.get(0).getConditions().get(1).getValues().size());
assertEquals("192.168.143.188/32", statements.get(0).getConditions().get(1).getValues().get(0));
assertEquals(ConditionFactory.SOURCE_IP_CONDITION_KEY, statements.get(1).getConditions().get(0).getConditionKey());
assertEquals(Effect.Deny, statements.get(1).getEffect());
assertEquals("1", statements.get(1).getId());
assertEquals(1, statements.get(1).getPrincipals().size());
assertEquals("*", statements.get(1).getPrincipals().get(0).getId());
assertEquals("AWS", statements.get(1).getPrincipals().get(0).getProvider());
assertEquals(1, statements.get(1).getResources().size());
assertEquals("resource", statements.get(1).getResources().get(0).getId());
assertEquals(1, statements.get(1).getActions().size());
assertEquals("action2", statements.get(1).getActions().get(0).getActionName());
assertEquals(1, statements.get(1).getConditions().size());
assertEquals("IpAddress", statements.get(1).getConditions().get(0).getType());
assertEquals(ConditionFactory.SOURCE_IP_CONDITION_KEY, statements.get(0).getConditions().get(0).getConditionKey());
assertEquals(1, statements.get(0).getConditions().get(0).getValues().size());
assertEquals("10.1.2.0/24", statements.get(1).getConditions().get(0).getValues().get(0));
}
@Test
public void testNoJsonArray() {
String jsonString =
"{" +
"\"Version\": \"2012-10-17\"," +
"\"Statement\": [" +
"{" +
"\"Effect\": \"Allow\"," +
"\"Principal\": {" +
"\"AWS\": \"*\"" +
"}," +
"\"Action\": \"sts:AssumeRole\"," +
"\"Condition\": {" +
"\"IpAddress\": {" +
" \"aws:SourceIp\": \"10.10.10.10/32\"" +
"}" +
"}" +
"}" +
"]" +
"}";
Policy policy = Policy.fromJson(jsonString);
assertEquals(POLICY_VERSION, policy.getVersion());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(1, statements.size());
assertEquals(1, statements.get(0).getActions().size());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("sts:AssumeRole", statements.get(0).getActions().get(0).getActionName());
assertEquals(1, statements.get(0).getConditions().size());
assertEquals("IpAddress", statements.get(0).getConditions().get(0).getType());
assertEquals("aws:SourceIp", statements.get(0).getConditions().get(0).getConditionKey());
assertEquals(1, statements.get(0).getConditions().get(0).getValues().size());
assertEquals("10.10.10.10/32", statements.get(0).getConditions().get(0).getValues().get(0));
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals("*", statements.get(0).getPrincipals().get(0).getId());
assertEquals("AWS", statements.get(0).getPrincipals().get(0).getProvider());
}
/**
* Tests that SAML-based federated user is supported as principal.
*/
@Test
public void testFederatedUserBySAMLProvider() {
String jsonString =
"{" +
"\"Version\":\"2012-10-17\"," +
"\"Statement\":[" +
"{" +
"\"Sid\":\"\"," +
"\"Effect\":\"Allow\"," +
"\"Principal\":{" +
"\"Federated\":\"arn:aws:iam::862954416975:saml-provider/myprovider\"" +
"}," +
"\"Action\":\"sts:AssumeRoleWithSAML\"," +
"\"Condition\":{" +
"\"StringEquals\":{" +
"\"SAML:aud\":\"https://signin.aws.amazon.com/saml\"" +
"}" +
"}" +
"}" +
"]" +
"}";
Policy policy = Policy.fromJson(jsonString);
assertEquals(POLICY_VERSION, policy.getVersion());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(1, statements.size());
assertEquals(1, statements.get(0).getActions().size());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("sts:AssumeRoleWithSAML", statements.get(0).getActions().get(0).getActionName());
assertEquals(1, statements.get(0).getConditions().size());
assertEquals("StringEquals", statements.get(0).getConditions().get(0).getType());
assertEquals("SAML:aud", statements.get(0).getConditions().get(0).getConditionKey());
assertEquals(1, statements.get(0).getConditions().get(0).getValues().size());
assertEquals("https://signin.aws.amazon.com/saml", statements.get(0).getConditions().get(0).getValues().get(0));
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals("arn:aws:iam::862954416975:saml-provider/myprovider", statements.get(0).getPrincipals().get(0).getId());
assertEquals("Federated", statements.get(0).getPrincipals().get(0).getProvider());
}
@Test
public void testCloudHSMServicePrincipal() {
String jsonString =
"{" +
"\"Version\":\"2008-10-17\"," +
"\"Statement\":[" +
"{\"Sid\":\"\"," +
"\"Effect\":\"Allow\"," +
"\"Principal\":{\"Service\":\"cloudhsm.amazonaws.com\"}," +
"\"Action\":\"sts:AssumeRole\"}" +
"]" +
"}";
Policy policy = Policy.fromJson(jsonString);
assertEquals(POLICY_VERSION, policy.getVersion());
List<Statement> statements = new LinkedList<Statement>(policy.getStatements());
assertEquals(1, statements.size());
assertEquals(1, statements.get(0).getActions().size());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("sts:AssumeRole", statements.get(0).getActions().get(0).getActionName());
assertEquals(0, statements.get(0).getConditions().size());
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals(Service.AWSCloudHSM.getServiceId(), statements.get(0).getPrincipals().get(0).getId());
assertEquals("Service", statements.get(0).getPrincipals().get(0).getProvider());
}
/**
* This test case was written as result of the following TT
*
* @see TT:0030871921
*
* When a service is mentioned in the principal, we always try to
* figure out the service from
* <code>software.amazon.awssdk.core.auth.policy.Principal.Services</code> enum. For
* new services introduced, if the enum is not updated, then the parsing
* fails.
*/
@Test
public void testPrincipalWithServiceNotInServicesEnum() {
String jsonString = "{" + "\"Version\":\"2008-10-17\","
+ "\"Statement\":[" + "{" + "\"Sid\":\"\","
+ "\"Effect\":\"Allow\"," + "\"Principal\":{"
+ "\"Service\":\"workspaces.amazonaws.com\" " + "},"
+ "\"Action\":\"sts:AssumeRole\"" + "}" + "]" + "}";
Policy policy = Policy.fromJson(jsonString);
assertEquals(POLICY_VERSION, policy.getVersion());
List<Statement> statements = new LinkedList<Statement>(
policy.getStatements());
assertEquals(1, statements.size());
assertEquals(1, statements.get(0).getActions().size());
assertEquals(Effect.Allow, statements.get(0).getEffect());
assertEquals("sts:AssumeRole", statements.get(0).getActions().get(0)
.getActionName());
assertEquals(0, statements.get(0).getConditions().size());
assertEquals(1, statements.get(0).getPrincipals().size());
assertEquals("workspaces.amazonaws.com", statements.get(0)
.getPrincipals().get(0).getId());
assertEquals("Service", statements.get(0).getPrincipals().get(0)
.getProvider());
}
}
| 2,420 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/core/auth | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/core/auth/policy/PolicyTest.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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.auth.policy.Principal.Service;
import software.amazon.awssdk.core.auth.policy.Principal.WebIdentityProvider;
import software.amazon.awssdk.core.auth.policy.Statement.Effect;
import software.amazon.awssdk.core.auth.policy.conditions.IpAddressCondition;
import software.amazon.awssdk.core.auth.policy.conditions.IpAddressCondition.IpAddressComparisonType;
import software.amazon.awssdk.core.auth.policy.conditions.StringCondition;
import software.amazon.awssdk.core.auth.policy.conditions.StringCondition.StringComparisonType;
import software.amazon.awssdk.core.auth.policy.internal.JacksonUtils;
/**
* Unit tests for constructing policy objects and serializing them to JSON.
*/
public class PolicyTest {
@Test
public void testPrincipals() {
Policy policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal("accountId1"),
new Principal("accountId2"))
.withActions(new Action("action")));
JsonNode jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
JsonNode statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.isArray());
assertTrue(statementArray.size() == 1);
JsonNode statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
JsonNode users = statement.get("Principal").get("AWS");
assertEquals(2, users.size());
assertEquals(users.get(0).asText(), "accountId1");
assertEquals(users.get(1).asText(), "accountId2");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal(Principal.Service.AmazonEC2),
new Principal(Principal.Service.AmazonElasticTranscoder))
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
JsonNode services = statement.get("Principal").get("Service");
assertTrue(services.isArray());
assertTrue(services.size() == 2);
assertEquals(Service.AmazonEC2.getServiceId(), services.get(0)
.asText());
assertEquals(Principal.Service.AmazonElasticTranscoder.getServiceId(), services
.get(1).asText());
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
assertEquals(users.asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(Principal.ALL_SERVICES, Principal.ALL_USERS)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
services = statement.get("Principal").get("Service");
assertEquals(users.asText(), "*");
assertEquals(services.asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(Principal.ALL_SERVICES, Principal.ALL_USERS,
Principal.ALL_WEB_PROVIDERS)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
services = statement.get("Principal").get("Service");
JsonNode webProviders = statement.get("Principal").get("Federated");
assertEquals(users.asText(), "*");
assertEquals(services.asText(), "*");
assertEquals(webProviders.asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(Principal.ALL_SERVICES, Principal.ALL_USERS,
Principal.ALL_WEB_PROVIDERS, Principal.ALL)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
services = statement.get("Principal").get("Service");
webProviders = statement.get("Principal").get("Federated");
JsonNode allUsers = statement.get("Principal").get("*");
assertEquals(users.asText(), "*");
assertEquals(services.asText(), "*");
assertEquals(webProviders.asText(), "*");
assertEquals(allUsers.asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal("accountId1"), Principal.ALL_USERS)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
assertTrue(users.isArray());
assertEquals(users.get(0).asText(), "accountId1");
assertEquals(users.get(1).asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal(Principal.Service.AmazonEC2),
Principal.ALL_SERVICES, new Principal("accountId1"))
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
services = statement.get("Principal").get("Service");
assertEquals(users.asText(), "accountId1");
assertEquals(services.get(0).asText(),
Service.AmazonEC2.getServiceId());
assertEquals(services.get(1).asText(), "*");
policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(new Resource("resource"))
.withPrincipals(new Principal(Service.AmazonEC2),
Principal.ALL_SERVICES, new Principal("accountId1"),
new Principal(WebIdentityProvider.Amazon),
Principal.ALL_WEB_PROVIDERS)
.withActions(new Action("action")));
jsonPolicyNode = JacksonUtils.jsonNodeOf(policy.toJson());
statementArray = jsonPolicyNode.get("Statement");
assertTrue(statementArray.size() == 1);
statement = statementArray.get(0);
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Effect"));
users = statement.get("Principal").get("AWS");
services = statement.get("Principal").get("Service");
webProviders = statement.get("Principal").get("Federated");
assertEquals(services.get(0).asText(),
Service.AmazonEC2.getServiceId());
assertEquals(services.get(1).asText(), "*");
assertEquals(users.asText(), "accountId1");
assertEquals(webProviders.get(0).asText(),
WebIdentityProvider.Amazon.getWebIdentityProvider());
assertEquals(webProviders.get(1).asText(), "*");
}
/**
* Policies with multiple conditions that use the same comparison type must
* be merged together in the JSON format, otherwise there will be two keys
* with the same name and one will override the other.
*/
@Test
public void testMultipleConditionKeysForConditionType() throws Exception {
Policy policy = new Policy();
policy.withStatements(new Statement(Effect.Allow)
.withResources(
new Resource(
"arn:aws:sqs:us-east-1:987654321000:MyQueue"))
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("foo"))
.withConditions(
new StringCondition(StringComparisonType.StringNotLike,
"key1", "foo"),
new StringCondition(StringComparisonType.StringNotLike,
"key1", "bar")));
JsonNode jsonPolicy = JacksonUtils.jsonNodeOf(policy.toJson());
JsonNode statementArray = jsonPolicy.get("Statement");
assertEquals(statementArray.size(), 1);
JsonNode conditions = statementArray.get(0).get("Condition");
assertEquals(conditions.size(), 1);
JsonNode stringLikeCondition = conditions.get(StringComparisonType.StringNotLike.toString());
assertTrue(stringLikeCondition.has("key1"));
assertFalse(stringLikeCondition.has("key2"));
assertValidStatementIds(policy);
}
/**
* Tests serializing a more complex policy object with multiple statements.
*/
@Test
public void testMultipleStatements() throws Exception {
Policy policy = new Policy("S3PolicyId1");
policy.withStatements(
new Statement(Effect.Allow)
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action1"))
.withResources(new Resource("resource"))
.withConditions(
new IpAddressCondition("192.168.143.0/24"),
new IpAddressCondition(IpAddressComparisonType.NotIpAddress, "192.168.143.188/32")),
new Statement(Effect.Deny).withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action2"))
.withResources(new Resource("resource"))
.withConditions(new IpAddressCondition("10.1.2.0/24")));
JsonNode jsonPolicy = JacksonUtils.jsonNodeOf(policy.toJson());
assertTrue(jsonPolicy.has("Id"));
JsonNode statementArray = jsonPolicy.get("Statement");
assertEquals(statementArray.size(), 2);
assertValidStatementIds(policy);
JsonNode statement;
for (int i = 0; i < statementArray.size(); i++) {
statement = statementArray.get(i);
assertTrue(statement.has("Sid"));
assertTrue(statement.has("Effect"));
assertTrue(statement.has("Principal"));
assertTrue(statement.has("Action"));
assertTrue(statement.has("Resource"));
assertTrue(statement.has("Condition"));
}
}
/**
* Tests that a policy correctly assigns unique statement IDs to any added
* statements without IDs yet.
*/
@Test
public void testStatementIdAssignment() throws Exception {
Policy policy = new Policy("S3PolicyId1");
policy.withStatements(
new Statement(Effect.Allow).withId("0")
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action1")),
new Statement(Effect.Allow).withId("1")
.withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action1")), new Statement(
Effect.Deny).withPrincipals(Principal.ALL_USERS)
.withActions(new Action("action2")));
assertValidStatementIds(policy);
}
/**
* Asserts that each statement in the specified policy has a unique ID
* assigned to it.
*/
private void assertValidStatementIds(Policy policy) {
Set<String> statementIds = new HashSet<String>();
for (Statement statement : policy.getStatements()) {
assertNotNull(statement.getId());
assertFalse(statementIds.contains(statement.getId()));
statementIds.add(statement.getId());
}
}
@Test
public void testPrincipalAccountId() {
String ID_WITH_HYPHEN = "a-b-c-d-e-f-g";
String ID_WITHOUT_HYPHEN = "abcdefg";
assertEquals(ID_WITHOUT_HYPHEN,
new Principal(ID_WITH_HYPHEN).getId());
assertEquals(ID_WITHOUT_HYPHEN,
new Principal("AWS", ID_WITH_HYPHEN).getId());
assertEquals(ID_WITH_HYPHEN,
new Principal("Federated", ID_WITH_HYPHEN).getId());
assertEquals(ID_WITH_HYPHEN,
new Principal("AWS", ID_WITH_HYPHEN, false).getId());
}
}
| 2,421 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/LogCaptorTest.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.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.utils.Logger;
class LogCaptorTest {
private static final Logger log = Logger.loggerFor(LogCaptorTest.class);
@Test
@DisplayName("Assert that default level captures all levels")
void test_defaultLevel_capturesAll() {
Level originalRootLevel = getRootLevel();
try (LogCaptor logCaptor = LogCaptor.create()) {
assertThat(getRootLevel()).isEqualTo(Level.ALL);
logAtAllLevels();
allLevels()
.forEach(l -> assertContains(logCaptor.loggedEvents(), event -> event.getLevel().equals(l)));
}
assertThat(getRootLevel()).isEqualTo(originalRootLevel);
}
@ParameterizedTest
@MethodSource("allLevels")
@DisplayName("Assert that explicit level captures same level and higher")
void test_explicitLevel_capturesCorrectLevels(Level level) {
Level originalRootLevel = getRootLevel();
try (LogCaptor logCaptor = LogCaptor.create(level)) {
assertThat(getRootLevel()).isEqualTo(level);
logAtAllLevels();
allLevels()
.filter(l -> l.isMoreSpecificThan(level))
.forEach(l -> assertContains(logCaptor.loggedEvents(), event -> event.getLevel().equals(l)));
}
assertThat(getRootLevel()).isEqualTo(originalRootLevel);
}
@Test
@DisplayName("Assert that appender name uses caller's class name")
void test_getCallerClassName() {
String callerClassName = LogCaptor.DefaultLogCaptor.getCallerClassName();
assertThat(callerClassName).isEqualTo(this.getClass().getName());
}
private static Stream<Level> allLevels() {
return Stream.of(
Level.TRACE,
Level.DEBUG,
Level.INFO,
Level.WARN,
Level.ERROR
);
}
private static void assertContains(List<LogEvent> events, Predicate<LogEvent> predicate) {
for (LogEvent event : events) {
if (predicate.test(event)) {
return;
}
}
throw new AssertionError("Couldn't find a log event matching the given predicate");
}
private static void logAtAllLevels() {
allLevels()
.map(Level::toString)
.map(org.slf4j.event.Level::valueOf)
.forEach(level -> log.log(level, level::toString));
}
private static Level getRootLevel() {
LoggerContext loggerContext = LoggerContext.getContext(false);
LoggerConfig loggerConfig = loggerContext.getConfiguration().getRootLogger();
return loggerConfig.getLevel();
}
} | 2,422 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/DateUtilsTest.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.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class DateUtilsTest {
@Test
public void test() {
assertTrue("yyMMdd-hhmmss".length() == DateUtils.yyMMddhhmmss().length());
}
}
| 2,423 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/MemoryTest.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 org.junit.jupiter.api.Test;
public class MemoryTest {
@Test
public void test() {
System.out.println(Memory.heapSummary());
System.out.println(Memory.poolSummaries());
}
}
| 2,424 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/UnorderedCollectionComparatorTest.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.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.Test;
public class UnorderedCollectionComparatorTest {
/**
* Tests that UnorderedCollectionComparator.equalUnorderedCollections
* correctly compares two unordered collections.
*/
@Test
public void testEqualUnorderedLists() {
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(null, null));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(null, Collections.emptyList()));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(Collections.emptyList(), Collections.emptyList()));
// Lists of Strings
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("a", "b", "c")));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("a", "c", "b")));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("b", "a", "c")));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("b", "c", "a")));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("c", "a", "b")));
assertTrue(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("c", "b", "a")));
assertFalse(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("a")));
assertFalse(UnorderedCollectionComparator.equalUnorderedCollections(
Arrays.asList("a", "b", "c"),
Arrays.asList("a", "b", "d")));
}
}
| 2,425 |
0 | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/test/test-utils/src/test/java/software/amazon/awssdk/testutils/EnvironmentVariableHelperTest.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.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import software.amazon.awssdk.utils.SystemSetting;
public class EnvironmentVariableHelperTest {
@Test
public void testCanUseStaticRun() {
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).isEmpty();
EnvironmentVariableHelper.run(helper -> {
helper.set("hello", "world");
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).hasValue("world");
});
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).isEmpty();
}
@Test
public void testCanManuallyReset() {
EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).isEmpty();
helper.set("hello", "world");
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).hasValue("world");
helper.reset();
assertThat(SystemSetting.getStringValueFromEnvironmentVariable("hello")).isEmpty();
}
}
| 2,426 |
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,427 |
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,428 |
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,429 |
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,430 |
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,431 |
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,432 |
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,433 |
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,434 |
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,435 |
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,436 |
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,437 |
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,438 |
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,439 |
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,440 |
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,441 |
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,442 |
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("MyQueuePolicy");
* policy.withStatements(new Statement("AllowSNSMessages", Effect.Allow)
* .withPrincipals(new Principal("*")).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,443 |
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,444 |
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,445 |
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,446 |
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,447 |
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,448 |
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,449 |
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,450 |
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,451 |
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,452 |
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,453 |
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,454 |
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,455 |
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,456 |
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,457 |
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,458 |
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,459 |
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,460 |
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,461 |
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,462 |
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,463 |
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,464 |
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,465 |
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,466 |
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,467 |
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,468 |
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,469 |
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,470 |
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,471 |
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,472 |
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,473 |
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,474 |
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,475 |
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,476 |
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,477 |
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,478 |
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,479 |
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,480 |
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,481 |
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,482 |
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,483 |
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,484 |
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,485 |
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,486 |
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,487 |
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,488 |
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,489 |
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,490 |
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,491 |
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,492 |
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,493 |
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,494 |
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,495 |
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,496 |
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,497 |
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,498 |
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,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.