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/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/ErrorDuringUnmarshallingResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class ErrorDuringUnmarshallingResponseHandler extends NullResponseHandler { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { throw new RuntimeException("Unable to unmarshall response"); } }
1,700
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/UnresponsiveResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Error Response Handler implementation that hangs forever */ public class UnresponsiveResponseHandler implements HttpResponseHandler<SdkResponse> { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { Thread.sleep(Long.MAX_VALUE); return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,701
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/NullErrorResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class NullErrorResponseHandler implements HttpResponseHandler<SdkServiceException> { @Override public SdkServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return SdkServiceException.builder().build(); } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,702
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/EmptySdkResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.http.SdkHttpFullResponse; public class EmptySdkResponseHandler implements HttpResponseHandler<SdkResponse> { @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return VoidSdkResponse.builder().build(); } @Override public boolean needsConnectionLeftOpen() { return true; } }
1,703
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/UnresponsiveErrorResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Response Handler implementation that hangs forever */ public class UnresponsiveErrorResponseHandler implements HttpResponseHandler<SdkServiceException> { @Override public SdkServiceException handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { Thread.sleep(Long.MAX_VALUE); return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,704
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/response/NullResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.response; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertThat; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullResponse; public class NullResponseHandler implements HttpResponseHandler<SdkResponse> { public static void assertIsUnmarshallingException(SdkClientException e) { assertThat(e.getCause(), instanceOf(RuntimeException.class)); RuntimeException re = (RuntimeException) e.getCause(); assertThat(re.getMessage(), containsString("Unable to unmarshall response")); } @Override public SdkResponse handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return null; } @Override public boolean needsConnectionLeftOpen() { return false; } }
1,705
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/HttpClientApiCallTimeoutTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; 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.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.noOpSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class HttpClientApiCallTimeoutTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonSyncHttpClient httpClient; @Before public void setup() { httpClient = testClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallTimeout(API_CALL_TIMEOUT) .build(); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); assertThatThrownBy(() -> requestBuilder().execute(combinedSyncResponseHandler( superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()), null))) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); assertThatThrownBy(() -> httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedSyncResponseHandler(noOpSyncResponseHandler(), superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())))) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallTimeoutException.class); } private AmazonSyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,706
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/AsyncHttpClientApiCallTimeoutTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; 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.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.combinedAsyncResponseHandler; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.noOpResponseHandler; import static software.amazon.awssdk.core.internal.util.AsyncResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testAsyncClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonAsyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class AsyncHttpClientApiCallTimeoutTests { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonAsyncHttpClient httpClient; @Before public void setup() { httpClient = testAsyncClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallTimeout(API_CALL_TIMEOUT) .build(); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); CompletableFuture future = httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedAsyncResponseHandler(noOpResponseHandler(), superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()))); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void errorResponse_SlowAfterErrorRequestHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain( Collections.singletonList(new SlowExecutionInterceptor().onExecutionFailureWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT))); SdkHttpFullRequest request = generateRequest(); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(request) .build(); ExecutionContext executionContext = ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); CompletableFuture future = httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .request(request) .executionContext(executionContext) .execute(combinedAsyncResponseHandler(noOpResponseHandler(), noOpResponseHandler(SdkServiceException.builder().build()))); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowBeforeRequestRequestHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); CompletableFuture future = requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpResponseHandler()); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); CompletableFuture future = requestBuilder().execute(superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallTimeoutException.class); } @Test public void slowApiAttempt_ThrowsApiCallAttemptTimeoutException() { httpClient = testAsyncClientBuilder() .apiCallTimeout(API_CALL_TIMEOUT) .apiCallAttemptTimeout(Duration.ofMillis(1)) .build(); stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}").withFixedDelay(1_000))); CompletableFuture future = requestBuilder().execute(noOpResponseHandler()); assertThatThrownBy(future::join).hasCauseInstanceOf(ApiCallAttemptTimeoutException.class); } private AmazonAsyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,707
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/HttpClientApiCallAttemptTimeoutTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; 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.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.internal.http.timers.TimeoutTestConstants.SLOW_REQUEST_HANDLER_TIMEOUT; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.noOpSyncResponseHandler; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.superSlowResponseHandler; import static utils.HttpTestUtils.testClientBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayInputStream; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.metrics.MetricCollector; import utils.ValidSdkObjects; public class HttpClientApiCallAttemptTimeoutTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private AmazonSyncHttpClient httpClient; @Before public void setup() { httpClient = testClientBuilder() .retryPolicy(RetryPolicy.none()) .apiCallAttemptTimeout(API_CALL_TIMEOUT) .build(); } @Test public void successfulResponse_SlowResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); assertThatThrownBy(() -> requestBuilder().execute(combinedSyncResponseHandler( superSlowResponseHandler(API_CALL_TIMEOUT.toMillis()), null))) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void errorResponse_SlowErrorResponseHandler_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("{}"))); ExecutionContext executionContext = ClientExecutionAndRequestTimerTestUtils.executionContext(null); assertThatThrownBy(() -> httpClient.requestExecutionBuilder() .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext) .request(generateRequest()) .execute(combinedSyncResponseHandler(null, superSlowResponseHandler(API_CALL_TIMEOUT.toMillis())))) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void successfulResponse_SlowBeforeTransmissionExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().beforeTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallAttemptTimeoutException.class); } @Test public void successfulResponse_SlowAfterResponseExecutionInterceptor_ThrowsApiCallTimeoutException() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200).withBody("{}"))); ExecutionInterceptor interceptor = new SlowExecutionInterceptor().afterTransmissionWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT); assertThatThrownBy(() -> requestBuilder().executionContext(withInterceptors(interceptor)) .execute(noOpSyncResponseHandler())) .isInstanceOf(ApiCallAttemptTimeoutException.class); } private AmazonSyncHttpClient.RequestExecutionBuilder requestBuilder() { return httpClient.requestExecutionBuilder() .request(generateRequest()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)); } private SdkHttpFullRequest generateRequest() { return ValidSdkObjects.sdkHttpFullRequest(wireMock.port()) .host("localhost") .contentStreamProvider(() -> new ByteArrayInputStream("test".getBytes())).build(); } private ExecutionContext withInterceptors(ExecutionInterceptor... requestHandlers) { ExecutionInterceptorChain interceptors = new ExecutionInterceptorChain(Arrays.asList(requestHandlers)); InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(generateRequest()) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(interceptors) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } }
1,708
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/SyncTimeoutTaskTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; public class SyncTimeoutTaskTest { private static final ExecutorService EXEC = Executors.newSingleThreadExecutor(); @AfterAll public static void teardown() { EXEC.shutdown(); } @Test public void taskInProgress_hasExecutedReturnsTrue() throws InterruptedException { Thread mockThread = mock(Thread.class); SyncTimeoutTask task = new SyncTimeoutTask(mockThread); CountDownLatch latch = new CountDownLatch(1); task.abortable(() -> { try { latch.countDown(); Thread.sleep(1000); } catch (InterruptedException e) { } }); EXEC.submit(task); latch.await(); assertThat(task.hasExecuted()).isTrue(); } @Test public void taskInProgress_cancelCalled_abortableIsNotInterrupted() throws InterruptedException { Thread mockThread = mock(Thread.class); SyncTimeoutTask task = new SyncTimeoutTask(mockThread); AtomicBoolean interrupted = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(1); task.abortable(() -> { try { latch.countDown(); Thread.sleep(1000); } catch (InterruptedException e) { interrupted.set(true); } }); EXEC.submit(task); latch.await(); task.cancel(); assertThat(interrupted.get()).isFalse(); } }
1,709
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/TimeoutTestConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; import java.time.Duration; /** * Constants relevant for request timeout and client execution timeout tests */ public class TimeoutTestConstants { public static final int TEST_TIMEOUT = 25 * 1000; public static final Duration API_CALL_TIMEOUT = Duration.ofSeconds(1); public static final int SLOW_REQUEST_HANDLER_TIMEOUT = 2; /** * ScheduledThreadPoolExecutor isn't exact and can be delayed occasionally. For tests where we * are asserting that a certain timeout comes first (i.e. SocketTimeout is triggered before * Request timeout or Request Timeout is triggered before Client execution timeout) then we need * to add a comfortable margin to ensure tests don't fail. */ public static final int PRECISION_MULTIPLIER = 5; }
1,710
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/timers/ClientExecutionAndRequestTimerTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.timers; import static org.junit.Assert.assertEquals; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import java.net.URI; import java.util.Collections; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.NoopTestRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.ErrorDuringUnmarshallingResponseHandler; import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.metrics.MetricCollector; /** * Useful asserts and utilities for verifying behavior or the client execution timeout and request * timeout features */ public class ClientExecutionAndRequestTimerTestUtils { /** * Can take a little bit for ScheduledThreadPoolExecutor to update it's internal state */ private static final int WAIT_BEFORE_ASSERT_ON_EXECUTOR = 500; /** * Waits until a little after the thread pools keep alive time and then asserts that all thre * * @param timerExecutor Executor used by timer implementation */ public static void assertCoreThreadsShutDownAfterBeingIdle(ScheduledThreadPoolExecutor timerExecutor) { try { Thread.sleep(timerExecutor.getKeepAliveTime(TimeUnit.MILLISECONDS) + 1000); } catch (InterruptedException ignored) { // Ignored. } assertEquals(0, timerExecutor.getPoolSize()); } /** * If the request completes successfully then the timer task should be canceled and should be * removed from the thread pool to prevent build up of canceled tasks * * @param timerExecutor Executor used by timer implementation */ public static void assertCanceledTasksRemoved(ScheduledThreadPoolExecutor timerExecutor) { waitBeforeAssertOnExecutor(); assertEquals(0, timerExecutor.getQueue().size()); } /** * Asserts the timer never went off (I.E. no timeout was exceeded and no timer task was * executed) * * @param timerExecutor Executor used by timer implementation */ public static void assertTimerNeverTriggered(ScheduledThreadPoolExecutor timerExecutor) { assertNumberOfTasksTriggered(timerExecutor, 0); } private static void assertNumberOfTasksTriggered(ScheduledThreadPoolExecutor timerExecutor, int expectedNumberOfTasks) { waitBeforeAssertOnExecutor(); assertEquals(expectedNumberOfTasks, timerExecutor.getCompletedTaskCount()); } public static SdkHttpFullRequest.Builder createMockGetRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("http://localhost:0")) .method(SdkHttpMethod.GET); } /** * Execute the request with a dummy response handler and error response handler */ public static void execute(AmazonSyncHttpClient httpClient, SdkHttpFullRequest request) { httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(new ErrorDuringUnmarshallingResponseHandler(), new NullErrorResponseHandler())); } public static ExecutionContext executionContext(SdkHttpFullRequest request) { InterceptorContext incerceptorContext = InterceptorContext.builder() .request(NoopTestRequest.builder().build()) .httpRequest(request) .build(); return ExecutionContext.builder() .signer(new NoOpSigner()) .interceptorChain(new ExecutionInterceptorChain(Collections.emptyList())) .executionAttributes(new ExecutionAttributes()) .interceptorContext(incerceptorContext) .metricCollector(MetricCollector.create("ApiCall")) .build(); } private static void waitBeforeAssertOnExecutor() { try { Thread.sleep(WAIT_BEFORE_ASSERT_ON_EXECUTOR); } catch (InterruptedException ignored) { // Ignored. } } public static void interruptCurrentThreadAfterDelay(final long delay) { final Thread currentThread = Thread.currentThread(); new Thread() { public void run() { try { Thread.sleep(delay); currentThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } }
1,711
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/async/CombinedResponseAsyncHttpResponseHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.Response; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.http.SdkHttpFullResponse; class CombinedResponseAsyncHttpResponseHandlerTest { private CombinedResponseAsyncHttpResponseHandler<Void> responseHandler; private TransformingAsyncResponseHandler<Void> successResponseHandler; private TransformingAsyncResponseHandler<SdkClientException> errorResponseHandler; @BeforeEach public void setup() { successResponseHandler = Mockito.mock(TransformingAsyncResponseHandler.class); errorResponseHandler = Mockito.mock(TransformingAsyncResponseHandler.class); responseHandler = new CombinedResponseAsyncHttpResponseHandler<>(successResponseHandler, errorResponseHandler); } @Test void onStream_invokedWithoutPrepare_shouldThrowException() { assertThatThrownBy(() -> responseHandler.onStream(publisher())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("onStream() invoked"); } @Test void onHeaders_invokedWithoutPrepare_shouldThrowException() { assertThatThrownBy(() -> responseHandler.onHeaders(SdkHttpFullResponse.builder().build())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("onHeaders() invoked"); } @Test void onStream_invokedWithoutOnHeaders_shouldThrowException() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); responseHandler.prepare(); assertThatThrownBy(() -> responseHandler.onStream(publisher())) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("headersFuture is still not completed when onStream()"); } @Test void onStream_HeadersFutureCompleteSuccessfully_shouldNotThrowException() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); responseHandler.prepare(); responseHandler.onError(new RuntimeException("error")); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onStream(publisher); verify(successResponseHandler, times(0)).onStream(publisher); verify(errorResponseHandler, times(0)).onStream(publisher); } @Test void successResponse_shouldCompleteHeaderFuture() { when(successResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Response<Void>> future = responseHandler.prepare(); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(200) .build(); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onHeaders(sdkHttpFullResponse); responseHandler.onStream(publisher); verify(successResponseHandler).prepare(); verify(successResponseHandler).onStream(publisher); assertThat(future).isDone(); assertThat(future.join().httpResponse()).isEqualTo(sdkHttpFullResponse); } @Test void errorResponse_shouldCompleteHeaderFuture() { when(errorResponseHandler.prepare()).thenReturn(CompletableFuture.completedFuture(null)); CompletableFuture<Response<Void>> future = responseHandler.prepare(); SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder() .statusCode(400) .build(); Flowable<ByteBuffer> publisher = publisher(); responseHandler.onHeaders(sdkHttpFullResponse); responseHandler.onStream(publisher); verify(errorResponseHandler).prepare(); verify(errorResponseHandler).onStream(publisher); assertThat(future).isDone(); assertThat(future.join().httpResponse()).isEqualTo(sdkHttpFullResponse); } private static Flowable<ByteBuffer> publisher() { return Flowable.just(ByteBuffer.wrap("string".getBytes(StandardCharsets.UTF_8))); } }
1,712
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/async/SimpleRequestProviderTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.async; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.ByteBuffer; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * TCK verification test for {@link SimpleHttpContentPublisher}. */ public class SimpleRequestProviderTckTest extends PublisherVerification<ByteBuffer> { private static final byte[] CONTENT = new byte[4906]; public SimpleRequestProviderTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long l) { return new SimpleHttpContentPublisher(makeFullRequest()); } @Override public long maxElementsFromPublisher() { // SimpleRequestProvider is a one shot publisher return 1; } @Override public Publisher<ByteBuffer> createFailedPublisher() { return null; } private static SdkHttpFullRequest makeFullRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("https://aws.amazon.com")) .method(SdkHttpMethod.PUT) .contentStreamProvider(() -> new ByteArrayInputStream(CONTENT)) .build(); } }
1,713
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/loader/CachingSdkHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.loader; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.http.SdkHttpService; @RunWith(MockitoJUnitRunner.class) public class CachingSdkHttpServiceProviderTest { @Mock private SdkHttpServiceProvider<SdkHttpService> delegate; private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = new CachingSdkHttpServiceProvider<>(delegate); } @Test(expected = NullPointerException.class) public void nullDelegate_ThrowsException() { new CachingSdkHttpServiceProvider<>(null); } @Test public void delegateReturnsEmptyOptional_DelegateCalledOnce() { when(delegate.loadService()).thenReturn(Optional.empty()); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); } @Test public void delegateReturnsNonEmptyOptional_DelegateCalledOne() { when(delegate.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); provider.loadService(); provider.loadService(); verify(delegate, times(1)).loadService(); } }
1,714
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/loader/SdkHttpServiceProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.loader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.Test; import software.amazon.awssdk.http.SdkHttpService; public class SdkHttpServiceProviderChainTest { @Test(expected = NullPointerException.class) public void nullProviders_ThrowsException() { new SdkHttpServiceProviderChain<>(null); } @Test(expected = IllegalArgumentException.class) public void emptyProviders_ThrowsException() { new SdkHttpServiceProviderChain<>(); } @Test public void allProvidersReturnEmpty_ReturnsEmptyOptional() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.empty()); when(delegateTwo.loadService()).thenReturn(Optional.empty()); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isEmpty(); } @Test public void firstProviderReturnsNonEmpty_DoesNotCallSecondProvider() { SdkHttpServiceProvider<SdkHttpService> delegateOne = mock(SdkHttpServiceProvider.class); SdkHttpServiceProvider<SdkHttpService> delegateTwo = mock(SdkHttpServiceProvider.class); when(delegateOne.loadService()).thenReturn(Optional.of(mock(SdkHttpService.class))); final Optional<SdkHttpService> actual = new SdkHttpServiceProviderChain<>(delegateOne, delegateTwo).loadService(); assertThat(actual).isPresent(); verify(delegateTwo, never()).loadService(); } }
1,715
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/loader/SystemPropertyHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.loader; import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpService; public class SystemPropertyHttpServiceProviderTest { private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = SystemPropertyHttpServiceProvider.syncProvider(); } @After public void tearDown() { System.clearProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property()); } @Test public void systemPropertyNotSet_ReturnsEmptyOptional() { assertThat(provider.loadService()).isEmpty(); } @Test(expected = SdkClientException.class) public void systemPropertySetToInvalidClassName_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), "com.invalid.ClassName"); provider.loadService(); } @Test(expected = SdkClientException.class) public void systemPropertySetToNonServiceClass_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), getClass().getName()); provider.loadService(); } @Test(expected = SdkClientException.class) public void systemPropertySetToServiceClassWithNoDefaultCtor_ThrowsException() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), HttpServiceWithNoDefaultCtor.class.getName()); provider.loadService(); } @Test public void systemPropertySetToValidClass_ReturnsFulfulledOptional() { System.setProperty(SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL.property(), MockHttpService.class.getName()); assertThat(provider.loadService()).isPresent(); } public static final class MockHttpService implements SdkHttpService { @Override public SdkHttpClient.Builder createHttpClientBuilder() { return null; } } public static final class HttpServiceWithNoDefaultCtor implements SdkHttpService { HttpServiceWithNoDefaultCtor(String foo) { } @Override public SdkHttpClient.Builder createHttpClientBuilder() { return null; } } }
1,716
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/loader/ClasspathSdkHttpServiceProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.loader; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Iterator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpService; @RunWith(MockitoJUnitRunner.class) public class ClasspathSdkHttpServiceProviderTest { @Mock private SdkServiceLoader serviceLoader; private SdkHttpServiceProvider<SdkHttpService> provider; @Before public void setup() { provider = new ClasspathSdkHttpServiceProvider<>(serviceLoader, SdkSystemSetting.SYNC_HTTP_SERVICE_IMPL, SdkHttpService.class); } @Test public void noImplementationsFound_ReturnsEmptyOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf()); assertThat(provider.loadService()).isEmpty(); } @Test public void oneImplementationsFound_ReturnsFulfilledOptional() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class))); assertThat(provider.loadService()).isPresent(); } @Test(expected = SdkClientException.class) public void multipleImplementationsFound_ThrowsException() { when(serviceLoader.loadServices(SdkHttpService.class)) .thenReturn(iteratorOf(mock(SdkHttpService.class), mock(SdkHttpService.class))); provider.loadService(); } @SafeVarargs private final <T> Iterator<T> iteratorOf(T... items) { return Arrays.asList(items).iterator(); } }
1,717
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/http/request/SlowExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.http.request; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * Implementation of {@link ExecutionInterceptor} with configurable wait times */ public class SlowExecutionInterceptor implements ExecutionInterceptor { private int beforeTransmissionWait; private int afterTransmissionWait; private int onExecutionFailureWait; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { wait(beforeTransmissionWait); } @Override public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { wait(afterTransmissionWait); } @Override public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { wait(onExecutionFailureWait); } private void wait(int secondsToWait) { if (secondsToWait > 0) { try { Thread.sleep(secondsToWait * 1000); } catch (InterruptedException e) { // Be a good citizen an re-interrupt the current thread Thread.currentThread().interrupt(); } } } public SlowExecutionInterceptor beforeTransmissionWaitInSeconds(int beforeTransmissionWait) { this.beforeTransmissionWait = beforeTransmissionWait; return this; } public SlowExecutionInterceptor afterTransmissionWaitInSeconds(int afterTransmissionWait) { this.afterTransmissionWait = afterTransmissionWait; return this; } public SlowExecutionInterceptor onExecutionFailureWaitInSeconds(int onExecutionFailureWait) { this.onExecutionFailureWait = onExecutionFailureWait; return this; } }
1,718
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/compression/GzipCompressorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.compression; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.Is.is; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import org.junit.Test; public class GzipCompressorTest { private static final Compressor gzipCompressor = new GzipCompressor(); private static final String COMPRESSABLE_STRING = "RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest"; @Test public void compressedData_decompressesCorrectly() throws IOException { byte[] originalData = COMPRESSABLE_STRING.getBytes(StandardCharsets.UTF_8); byte[] compressedData = gzipCompressor.compress(originalData); int uncompressedSize = originalData.length; int compressedSize = compressedData.length; assertThat(compressedSize, lessThan(uncompressedSize)); ByteArrayInputStream bais = new ByteArrayInputStream(compressedData); GZIPInputStream gzipInputStream = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = gzipInputStream.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } gzipInputStream.close(); byte[] decompressedData = baos.toByteArray(); assertThat(decompressedData, is(originalData)); } }
1,719
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/sync/FileContentStreamProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.sync; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.jimfs.Jimfs; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * Tests for {@link FileContentStreamProvider}. */ public class FileContentStreamProviderTest { private static FileSystem testFs; private static Path testFile; @BeforeAll public static void setup() throws IOException { testFs = Jimfs.newFileSystem("FileContentStreamProviderTest"); testFile = testFs.getPath("test_file.dat"); try (OutputStream os = Files.newOutputStream(testFile)) { os.write("test".getBytes(StandardCharsets.UTF_8)); } } @AfterAll public static void teardown() throws IOException { testFs.close(); } @Test public void newStreamClosesPreviousStream() { FileContentStreamProvider provider = new FileContentStreamProvider(testFile); InputStream oldStream = provider.newStream(); provider.newStream(); assertThatThrownBy(oldStream::read).hasMessage("stream is closed"); } }
1,720
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/internal/checksum/CrtBasedChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.checksum; import static org.assertj.core.api.Assertions.assertThat; import java.util.zip.Checksum; import org.junit.Test; import software.amazon.awssdk.core.internal.checksums.factory.CrtBasedChecksumProvider; public class CrtBasedChecksumTest { @Test public void doNot_loadCrc32CrtPathClassesInCore() { Checksum checksum = CrtBasedChecksumProvider.createCrc32(); assertThat(checksum).isNull(); } @Test public void doNot_loadCrc32_C_CrtPathClassesInCore() { Checksum checksum = CrtBasedChecksumProvider.createCrc32C(); assertThat(checksum).isNull(); } }
1,721
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/waiters/WaiterOverrideConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public class WaiterOverrideConfigurationTest { @Test public void valuesProvided_shouldReturnOptionalValues() { WaiterOverrideConfiguration configuration = WaiterOverrideConfiguration.builder() .maxAttempts(10) .backoffStrategy(BackoffStrategy.none()) .waitTimeout(Duration.ofSeconds(1)) .build(); assertThat(configuration.backoffStrategy()).contains(BackoffStrategy.none()); assertThat(configuration.maxAttempts()).contains(10); assertThat(configuration.waitTimeout()).contains(Duration.ofSeconds(1)); } @Test public void valuesNotProvided_shouldReturnEmptyOptionalValues() { WaiterOverrideConfiguration configuration = WaiterOverrideConfiguration.builder().build(); assertThat(configuration.backoffStrategy()).isEmpty(); assertThat(configuration.maxAttempts()).isEmpty(); assertThat(configuration.waitTimeout()).isEmpty(); } @Test public void nonPositiveMaxWaitTime_shouldThrowException() { assertThatThrownBy(() -> WaiterOverrideConfiguration.builder() .waitTimeout(Duration.ZERO) .build()).hasMessageContaining("must be positive"); } @Test public void nonPositiveMaxAttempts_shouldThrowException() { assertThatThrownBy(() -> WaiterOverrideConfiguration.builder() .maxAttempts(-10) .build()).hasMessageContaining("must be positive"); } @Test public void toBuilder_shouldGenerateSameBuilder() { WaiterOverrideConfiguration overrideConfiguration = WaiterOverrideConfiguration.builder() .waitTimeout(Duration.ofSeconds(2)) .maxAttempts(10) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1))) .build(); WaiterOverrideConfiguration config = overrideConfiguration.toBuilder().build(); assertThat(overrideConfiguration).isEqualTo(config); assertThat(overrideConfiguration.hashCode()).isEqualTo(config.hashCode()); } }
1,722
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/waiters/WaiterAcceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.Predicate; import org.testng.annotations.Test; public class WaiterAcceptorTest { private static final String STRING_TO_MATCH = "foobar"; private static final Predicate<String> STRING_PREDICATE = s -> s.equals(STRING_TO_MATCH); private static final Predicate<Throwable> EXCEPTION_PREDICATE = s -> s.getMessage().equals(STRING_TO_MATCH); @Test public void successOnResponseAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .successOnResponseAcceptor(STRING_PREDICATE); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.SUCCESS); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnResponseAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnResponseAcceptorWithMsg() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE, "wrong response"); assertThat(objectWaiterAcceptor.matches(STRING_TO_MATCH)).isTrue(); assertThat(objectWaiterAcceptor.matches("blah")).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).contains("wrong response"); } @Test public void errorOnResponseAcceptor_nullMsg_shouldThrowException() { assertThatThrownBy(() -> WaiterAcceptor .errorOnResponseAcceptor(STRING_PREDICATE, null)).hasMessageContaining("message must not be null"); } @Test public void errorOnResponseAcceptor_nullPredicate_shouldThrowException() { assertThatThrownBy(() -> WaiterAcceptor .errorOnResponseAcceptor(null)).hasMessageContaining("responsePredicate must not be null"); } @Test public void successOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .successOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.SUCCESS); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void errorOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .errorOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.FAILURE); assertThat(objectWaiterAcceptor.message()).isEmpty(); } @Test public void retryOnExceptionAcceptor() { WaiterAcceptor<String> objectWaiterAcceptor = WaiterAcceptor .retryOnExceptionAcceptor(EXCEPTION_PREDICATE); assertThat(objectWaiterAcceptor.matches(new RuntimeException(STRING_TO_MATCH))).isTrue(); assertThat(objectWaiterAcceptor.matches(new RuntimeException("blah"))).isFalse(); assertThat(objectWaiterAcceptor.waiterState()).isEqualTo(WaiterState.RETRY); assertThat(objectWaiterAcceptor.message()).isEmpty(); } }
1,723
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/waiters/AsyncWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.BiFunction; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.utils.CompletableFutureUtils; public class AsyncWaiterTest extends BaseWaiterTest { @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ReturnResponseResource(count)).join(); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ThrowExceptionResource(count)).join(); } @Test public void matchException_exceptionIsWrapped_shouldReturnUnwrappedException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnWrappedExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).isExactlyInstanceOf(RuntimeException.class); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void missingScheduledExecutor_shouldThrowException() { assertThatThrownBy(() -> AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .build() .runAsync(() -> null)) .hasMessageContaining("executorService"); } @Test public void concurrentWaiterOperations_shouldBeThreadSafe() { AsyncWaiter<String> waiter = AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .scheduledExecutorService(executorService) .build(); CompletableFuture<WaiterResponse<String>> waiterResponse1 = waiter.runAsync(new ReturnResponseResource(2)); CompletableFuture<WaiterResponse<String>> waiterResponse2 = waiter.runAsync(new ReturnResponseResource(3)); CompletableFuture.allOf(waiterResponse1, waiterResponse2).join(); assertThat(waiterResponse1.join().attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse2.join().attemptsExecuted()).isEqualTo(3); } @Test public void requestOverrideConfig_shouldTakePrecedence() { AsyncWaiter<String> waiter = AsyncWaiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .scheduledExecutorService(executorService) .build(); assertThatThrownBy(() -> waiter.runAsync(new ReturnResponseResource(2), o -> o.maxAttempts(1)) .join()).hasMessageContaining("exceeded the max retry attempts: 1"); } private BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnWrappedExceptionWaiterOperation() { return (count, waiterConfiguration) -> AsyncWaiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()) .scheduledExecutorService(executorService) .build() .runAsync(new ThrowCompletionExceptionResource(count)).join(); } private static final class ReturnResponseResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ReturnResponseResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFuture.completedFuture(NON_SUCCESS_STATE_MESSAGE); } return CompletableFuture.completedFuture(SUCCESS_STATE_MESSAGE); } } private static final class ThrowExceptionResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ThrowExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFutureUtils.failedFuture(new RuntimeException(NON_SUCCESS_STATE_MESSAGE)); } return CompletableFutureUtils.failedFuture(new RuntimeException(SUCCESS_STATE_MESSAGE)); } } private static final class ThrowCompletionExceptionResource implements Supplier<CompletableFuture<String>> { private final int successAttemptIndex; private int count; public ThrowCompletionExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public CompletableFuture<String> get() { if (++count < successAttemptIndex) { return CompletableFutureUtils.failedFuture(new CompletionException(new RuntimeException(NON_SUCCESS_STATE_MESSAGE))); } return CompletableFutureUtils.failedFuture(new CompletionException(new RuntimeException(SUCCESS_STATE_MESSAGE))); } } }
1,724
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/waiters/BaseWaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiFunction; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public abstract class BaseWaiterTest { static final String SUCCESS_STATE_MESSAGE = "helloworld"; static final String NON_SUCCESS_STATE_MESSAGE = "other"; static ScheduledExecutorService executorService; @BeforeAll public static void setUp() { executorService = Executors.newScheduledThreadPool(2); } @AfterAll public static void tearDown() { executorService.shutdown(); } @Test public void successOnResponse_matchSuccessInFirstAttempt_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().response()).contains(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnResponse_matchError_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.errorOnResponseAcceptor(s -> s.equals(NON_SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnResponse_matchSuccessInSecondAttempt_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(2, waiterConfig); assertThat(response.matched().response()).contains(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(2); } @Test public void successOnResponse_noMatch_shouldReturnResponse() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("No acceptor was matched for the response"); } @Test public void successOnResponse_noMatchExceedsMaxAttempts_shouldRetryThreeTimesAndThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(4, waiterConfig)).hasMessageContaining("max retry attempts"); } @Test public void successOnResponse_multipleMatchingAcceptors_firstTakesPrecedence() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.errorOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(1, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnResponse_fixedBackOffStrategy() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); long start = System.currentTimeMillis(); WaiterResponse<String> response = successOnResponseWaiterOperation().apply(5, waiterConfig); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(4000L, 5000L); assertThat(response.attemptsExecuted()).isEqualTo(5); } @Test public void successOnResponse_waitTimeout() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5) .waitTimeout(Duration.ofSeconds(2)) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)); long start = System.currentTimeMillis(); assertThatThrownBy(() -> successOnResponseWaiterOperation().apply(5, waiterConfig)).hasMessageContaining("has exceeded the max wait time"); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(1000L, 3000L); } @Test public void successOnException_matchSuccessInFirstAttempt_shouldReturnException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnException_hasRetryAcceptorMatchSuccessInSecondAttempt_shouldReturnException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnExceptionAcceptor(s -> s.getMessage().contains(NON_SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(2, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(2); } @Test public void successOnException_unexpectedExceptionAndNoRetryAcceptor_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnExceptionWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("did not match"); } @Test public void successOnException_matchError_shouldThrowException() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.errorOnExceptionAcceptor(s -> s.getMessage().contains(NON_SUCCESS_STATE_MESSAGE))); assertThatThrownBy(() -> successOnExceptionWaiterOperation().apply(2, waiterConfig)).hasMessageContaining("transitioned the waiter to failure state"); } @Test public void successOnException_multipleMatchingAcceptors_firstTakesPrecedence() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(3).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.errorOnExceptionAcceptor(s -> s.getMessage().contains(SUCCESS_STATE_MESSAGE))); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(1, waiterConfig); assertThat(response.matched().exception().get()).hasMessageContaining(SUCCESS_STATE_MESSAGE); assertThat(response.attemptsExecuted()).isEqualTo(1); } @Test public void successOnException_fixedBackOffStrategy() { TestWaiterConfiguration waiterConfig = new TestWaiterConfiguration() .overrideConfiguration(p -> p.maxAttempts(5).backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofSeconds(1)))) .addAcceptor(WaiterAcceptor.retryOnExceptionAcceptor(s -> s.getMessage().equals(NON_SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(s -> s.getMessage().equals(SUCCESS_STATE_MESSAGE))); long start = System.currentTimeMillis(); WaiterResponse<String> response = successOnExceptionWaiterOperation().apply(5, waiterConfig); long end = System.currentTimeMillis(); assertThat((end - start)).isBetween(4000L, 5000L); assertThat(response.attemptsExecuted()).isEqualTo(5); } public abstract BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation(); public abstract BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation(); class TestWaiterConfiguration implements WaiterBuilder<String, TestWaiterConfiguration> { private List<WaiterAcceptor<? super String>> waiterAcceptors = new ArrayList<>(); private WaiterOverrideConfiguration overrideConfiguration; /** * @return */ public List<WaiterAcceptor<? super String>> getWaiterAcceptors() { return waiterAcceptors; } /** * @return */ public WaiterOverrideConfiguration getPollingStrategy() { return overrideConfiguration; } @Override public TestWaiterConfiguration acceptors(List<WaiterAcceptor<? super String>> waiterAcceptors) { this.waiterAcceptors = waiterAcceptors; return this; } @Override public TestWaiterConfiguration addAcceptor(WaiterAcceptor<? super String> waiterAcceptor) { waiterAcceptors.add(waiterAcceptor); return this; } @Override public TestWaiterConfiguration overrideConfiguration(WaiterOverrideConfiguration overrideConfiguration) { this.overrideConfiguration = overrideConfiguration; return this; } } }
1,725
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/waiters/WaiterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; public class WaiterTest extends BaseWaiterTest { private static final String SUCCESS_STATE_MESSAGE = "helloworld"; private static final String NON_SUCCESS_STATE_MESSAGE = "other"; private BackoffStrategy backoffStrategy; @BeforeEach public void setup() { backoffStrategy = FixedDelayBackoffStrategy.create(Duration.ofMillis(10)); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnResponseWaiterOperation() { return (count, waiterConfiguration) -> Waiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()).build().run(new ReturnResponseResource(count)); } @Override public BiFunction<Integer, TestWaiterConfiguration, WaiterResponse<String>> successOnExceptionWaiterOperation() { return (count, waiterConfiguration) -> Waiter.builder(String.class) .overrideConfiguration(waiterConfiguration.getPollingStrategy()) .acceptors(waiterConfiguration.getWaiterAcceptors()).build().run(new ThrowExceptionResource(count)); } @Test public void concurrentWaiterOperations_shouldBeThreadSafe() { Waiter<String> waiter = Waiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .build(); CompletableFuture<WaiterResponse<String>> waiterResponse1 = CompletableFuture.supplyAsync(() -> waiter.run(new ReturnResponseResource(2)), executorService); CompletableFuture<WaiterResponse<String>> waiterResponse2 = CompletableFuture.supplyAsync(() -> waiter.run(new ReturnResponseResource(3)), executorService); CompletableFuture.allOf(waiterResponse1, waiterResponse2).join(); assertThat(waiterResponse1.join().attemptsExecuted()).isEqualTo(2); assertThat(waiterResponse2.join().attemptsExecuted()).isEqualTo(3); } @Test public void requestOverrideConfig_shouldTakePrecedence() { Waiter<String> waiter = Waiter.builder(String.class) .overrideConfiguration(p -> p.maxAttempts(4).backoffStrategy(BackoffStrategy.none())) .addAcceptor(WaiterAcceptor.successOnResponseAcceptor(s -> s.equals(SUCCESS_STATE_MESSAGE))) .addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(i -> true)) .build(); assertThatThrownBy(() -> waiter.run(new ReturnResponseResource(2), o -> o.maxAttempts(1))) .hasMessageContaining("exceeded the max retry attempts: 1"); } private static final class ReturnResponseResource implements Supplier<String> { private final int successAttemptIndex; private int count; public ReturnResponseResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public String get() { if (++count < successAttemptIndex) { return NON_SUCCESS_STATE_MESSAGE; } return SUCCESS_STATE_MESSAGE; } } private static final class ThrowExceptionResource implements Supplier<String> { private final int successAttemptIndex; private int count; public ThrowExceptionResource(int successAttemptIndex) { this.successAttemptIndex = successAttemptIndex; } @Override public String get() { if (++count < successAttemptIndex) { throw new RuntimeException(NON_SUCCESS_STATE_MESSAGE); } throw new RuntimeException(SUCCESS_STATE_MESSAGE); } public int count() { return count; } } }
1,726
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/VoidDocumentVisitorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.document; import org.testng.annotations.Test; import software.amazon.awssdk.core.SdkNumber; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; public class VoidDocumentVisitorTest { @Test public void voidDocumentVisitor() { VoidDocumentVisitCount voidDocumentVisitor = new VoidDocumentVisitCount(); // Constructing a Document for CustomClass final Document build = getCustomDocument(); build.accept(voidDocumentVisitor); assertThat(voidDocumentVisitor.booleanVisitsVisits).isEqualTo(2); assertThat(voidDocumentVisitor.mapVisits).isEqualTo(2); assertThat(voidDocumentVisitor.nullVisits).isEqualTo(1); assertThat(voidDocumentVisitor.listVisits).isEqualTo(1); assertThat(voidDocumentVisitor.numberVisits).isEqualTo(4); assertThat(voidDocumentVisitor.stringVisits).isEqualTo(2); // Expected CustomClass } public Document getCustomDocument() { final Document build = Document.mapBuilder() .putDocument("customClassFromMap", Document.mapBuilder().putString("innerStringField", "innerValue") .putNumber("innerIntField", SdkNumber.fromLong(1)).build()) .putString("outerStringField", "outerValue") .putNull("nullKey") .putBoolean("boolOne", true) .putBoolean("boolTwo", false) .putList("listKey", listBuilder -> listBuilder.addNumber(SdkNumber.fromLong(2)).addNumber(SdkNumber.fromLong(3))) .putNumber("outerLongField", SdkNumber.fromDouble(4)).build(); return build; } private static class VoidDocumentVisitCount implements VoidDocumentVisitor { private int nullVisits = 0; private int mapVisits = 0; private int listVisits = 0; private int stringVisits = 0; private int numberVisits = 0; private int booleanVisitsVisits = 0; public int getNullVisits() { return nullVisits; } public int getMapVisits() { return mapVisits; } public int getListVisits() { return listVisits; } public int getStringVisits() { return stringVisits; } public int getNumberVisits() { return numberVisits; } public int getBooleanVisitsVisits() { return booleanVisitsVisits; } @Override public void visitNull() { nullVisits++; } @Override public void visitBoolean(Boolean document) { booleanVisitsVisits++; } @Override public void visitString(String document) { stringVisits++; } @Override public void visitNumber(SdkNumber document) { numberVisits++; } @Override public void visitMap(Map<String, Document> documentMap) { mapVisits++; documentMap.values().stream().forEach(val -> val.accept(this)); } @Override public void visitList(List<Document> documentList) { listVisits++; documentList.forEach(item -> item.accept(this)); } } @Test public void defaultVoidDocumentVisitor() { VoidDocumentVisitor voidDocumentVisitor = new VoidDocumentVisitor() { }; Document.fromNull().accept(voidDocumentVisitor); Document.fromNumber(2).accept(voidDocumentVisitor); Document.fromString("testString").accept(voidDocumentVisitor); Document.fromBoolean(true).accept(voidDocumentVisitor); Document.listBuilder().addNumber(4).build().accept(voidDocumentVisitor); Document.mapBuilder().putNumber("key", 4).build().accept(voidDocumentVisitor); } }
1,727
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/DocumentVisitorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.document; import java.io.Serializable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.testng.annotations.Test; import software.amazon.awssdk.core.SdkNumber; import static org.assertj.core.api.Assertions.assertThat; public class DocumentVisitorTest { @Test public void testACustomDocumentVisitor() { // Constructing a Document for CustomClass final Document build = Document.mapBuilder() .putDocument("customClassFromMap", Document.mapBuilder().putString("innerStringField", "innerValue") .putNumber("innerIntField", SdkNumber.fromLong(99)).build()) .putString("outerStringField", "outerValue") .putNumber("outerLongField", SdkNumber.fromDouble(1)).build(); final CustomClass customClassExtracted = build.accept(new CustomDocumentVisitor()); // Expected CustomClass final CustomClassFromMap innerMap = new CustomClassFromMap(); innerMap.setInnerIntField(99); innerMap.setInnerStringField("innerValue"); CustomClass expectedCustomClass = new CustomClass(); expectedCustomClass.setOuterLongField(1L); expectedCustomClass.setOuterStringField("outerValue"); expectedCustomClass.setCustomClassFromMap(innerMap); assertThat(customClassExtracted).isEqualTo(expectedCustomClass); } @Test public void testDocumentVisitorWhenMethodNotImplemented(){ DocumentVisitor<Object> documentVisitor = new DocumentVisitor<Object>() { @Override public Object visitNull() { return null; } @Override public Object visitBoolean(Boolean document) { return null; } @Override public Object visitString(String document) { return null; } @Override public Object visitNumber(SdkNumber document) { return null; } @Override public Object visitMap(Map<String, Document> documentMap) { return null; } @Override public Object visitList(List<Document> documentList) { return null; } }; assertThat(Document.fromNumber(2).accept(documentVisitor)).isNull(); assertThat(Document.fromString("2").accept(documentVisitor)).isNull(); assertThat(Document.fromNull().accept(documentVisitor)).isNull(); assertThat(Document.fromBoolean(true).accept(documentVisitor)).isNull(); assertThat(Document.fromMap(new LinkedHashMap<>()).accept(documentVisitor)).isNull(); assertThat(Document.fromList(new ArrayList<>()).accept(documentVisitor)).isNull(); } /* Below are auxiliary classes to test Custom class visitors. */ private static class CustomClassFromMap { String innerStringField; Integer innerIntField; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CustomClassFromMap)) return false; CustomClassFromMap that = (CustomClassFromMap) o; return Objects.equals(innerStringField, that.innerStringField) && Objects.equals(innerIntField, that.innerIntField); } @Override public int hashCode() { return Objects.hash(innerStringField, innerIntField); } public void setInnerStringField(String innerStringField) { this.innerStringField = innerStringField; } public void setInnerIntField(Integer innerIntField) { this.innerIntField = innerIntField; } } private static class CustomClass implements Serializable { String outerStringField; Long outerLongField; CustomClassFromMap customClassFromMap; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CustomClass)) return false; CustomClass that = (CustomClass) o; return Objects.equals(outerStringField, that.outerStringField) && Objects.equals(outerLongField, that.outerLongField) && Objects.equals(customClassFromMap, that.customClassFromMap); } public void setOuterStringField(String outerStringField) { this.outerStringField = outerStringField; } public void setOuterLongField(Long outerLongField) { this.outerLongField = outerLongField; } public void setCustomClassFromMap(CustomClassFromMap customClassFromMap) { this.customClassFromMap = customClassFromMap; } } /** * Visitor to fetch attribute values for CustomClassFromMap. */ private static class CustomMapDocumentVisitor implements DocumentVisitor<CustomClassFromMap> { @Override public CustomClassFromMap visitNull() { return null; } @Override public CustomClassFromMap visitBoolean(Boolean document) { return null; } @Override public CustomClassFromMap visitString(String document) { return null; } @Override public CustomClassFromMap visitNumber(SdkNumber document) { return null; } @Override public CustomClassFromMap visitMap(Map<String, Document> documentMap) { CustomClassFromMap customClassFromMap = new CustomClassFromMap(); documentMap.entrySet().stream().forEach(stringDocumentEntry -> { if ("innerStringField".equals(stringDocumentEntry.getKey())) { customClassFromMap.setInnerStringField(stringDocumentEntry.getValue().accept(new StringDocumentVisitor())); } else if ("innerIntField".equals(stringDocumentEntry.getKey())) { customClassFromMap.setInnerIntField(stringDocumentEntry.getValue().accept(new NumberDocumentVisitor()).intValue()); } }); return customClassFromMap; } @Override public CustomClassFromMap visitList(List<Document> documentList) { return null; } } /** * Visitor to fetch attribute values for CustomClass. */ private static class CustomDocumentVisitor implements DocumentVisitor<CustomClass> { private final CustomClass customClass = new CustomClass(); @Override public CustomClass visitNull() { return null; } @Override public CustomClass visitBoolean(Boolean document) { return null; } @Override public CustomClass visitString(String document) { return null; } @Override public CustomClass visitNumber(SdkNumber document) { return null; } @Override public CustomClass visitMap(Map<String, Document> documentMap) { documentMap.entrySet().stream().forEach(stringDocumentEntry -> { if ("customClassFromMap".equals(stringDocumentEntry.getKey())) { final CustomMapDocumentVisitor customMapDocumentVisitor = new CustomMapDocumentVisitor(); customClass.setCustomClassFromMap(stringDocumentEntry.getValue().accept(customMapDocumentVisitor)); } else if ("outerStringField".equals(stringDocumentEntry.getKey())) { customClass.setOuterStringField( stringDocumentEntry.getValue().accept(new StringDocumentVisitor())); } else if ("outerLongField".equals(stringDocumentEntry.getKey())) { customClass.setOuterLongField(stringDocumentEntry.getValue().accept(new NumberDocumentVisitor()).longValue()); } }); return customClass; } @Override public CustomClass visitList(List<Document> documentList) { return null; } } private static class StringDocumentVisitor implements DocumentVisitor<String> { @Override public String visitNull() { return null; } @Override public String visitBoolean(Boolean document) { return null; } @Override public String visitString(String document) { return document; } @Override public String visitNumber(SdkNumber document) { return null; } @Override public String visitMap(Map<String, Document> documentMap) { return null; } @Override public String visitList(List<Document> documentList) { return null; } } private static class NumberDocumentVisitor implements DocumentVisitor<SdkNumber> { @Override public SdkNumber visitNull() { return null; } @Override public SdkNumber visitBoolean(Boolean document) { return null; } @Override public SdkNumber visitString(String document) { return null; } @Override public SdkNumber visitNumber(SdkNumber document) { return document; } @Override public SdkNumber visitMap(Map<String, Document> documentMap) { return null; } @Override public SdkNumber visitList(List<Document> documentList) { return null; } } }
1,728
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/UnwrapDocumentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.document; import org.testng.annotations.Test; import software.amazon.awssdk.core.SdkNumber; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; public class UnwrapDocumentTest { @Test public void testMapDocumentUnwrap() { final Document mapDocument = Document.mapBuilder().putString("key", "stringValue") .putDocument("documentKey", Document.fromString("documentValue")) .build(); final Object unwrappedMapObject = mapDocument.unwrap(); final long unwrappedMapCountAsString = ((Map<?, ?>) unwrappedMapObject).entrySet().stream() .filter(k -> k.getKey() instanceof String && k.getValue() instanceof String).count(); final long unwrappedMapCountAsDocument = ((Map<?, ?>) unwrappedMapObject).entrySet().stream() .filter(k -> k.getKey() instanceof String && k.getValue() instanceof Document).count(); assertThat(unwrappedMapCountAsString).isEqualTo(2); assertThat(unwrappedMapCountAsDocument).isZero(); } @Test public void testListDocumentUnwrap() { final Document documentList = Document.fromList(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(1)), Document.fromNumber(SdkNumber.fromLong(2)))); final Object documentListAsObjects = documentList.unwrap(); final Optional strippedAsSDKNumber = ((List) documentListAsObjects) .stream().filter(e -> e instanceof String).findAny(); final Optional strippedAsDocuments = ((List) documentListAsObjects) .stream().filter(e -> e instanceof Document).findAny(); assertThat(strippedAsSDKNumber).isPresent(); assertThat(strippedAsDocuments).isNotPresent(); } @Test public void testStringDocumentUnwrap() { final Document testDocument = Document.fromString("testDocument"); assertThat(testDocument.unwrap()).isEqualTo("testDocument"); } @Test public void testNumberDocumentUnwrap() { final Document testDocument = Document.fromNumber(SdkNumber.fromLong(2)); assertThat(testDocument.unwrap()).isEqualTo(SdkNumber.fromLong(2).stringValue()); } @Test public void testBoolanDocumentUnwrap() { final Document testDocument = Document.fromBoolean(true); assertThat(testDocument.unwrap()).isEqualTo(true); } @Test public void testNullDocumentUnwrap() { final Document testDocument = Document.fromNull(); assertThat(testDocument.unwrap()).isNull(); } }
1,729
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/document/DocumentTypeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.document; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.internal.ListDocument; public class DocumentTypeTest { final static String TEST_STRING_VALUE = "testString"; final static Long TEST_LONG_VALUE = 99L; @Test public void nullDocument() { Document nullDocument = Document.fromNull(); assertThat(nullDocument.isNull()).isTrue(); assertThat(nullDocument.isString()).isFalse(); assertThat(nullDocument.isBoolean()).isFalse(); assertThat(nullDocument.isNumber()).isFalse(); assertThat(nullDocument.isMap()).isFalse(); assertThat(nullDocument.isList()).isFalse(); assertThat(nullDocument.toString()).hasToString("null"); assertThat(nullDocument).isEqualTo(Document.fromNull()); assertThat(nullDocument.equals(nullDocument)).isTrue(); assertThat(nullDocument.hashCode()).isEqualTo(Document.fromNull().hashCode()); assertThat(nullDocument).isNotEqualTo(Document.fromString("null")); assertThatThrownBy(() -> nullDocument.asBoolean()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> nullDocument.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> nullDocument.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> nullDocument.asNumber()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> nullDocument.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> nullDocument.asString()).isInstanceOf(UnsupportedOperationException.class); } @Test public void stringDocumentTest() { final Document testDocumentString = Document.fromString(TEST_STRING_VALUE); assertThat(testDocumentString.asString()).isEqualTo(TEST_STRING_VALUE); assertThat(testDocumentString.isString()).isTrue(); assertThat(testDocumentString.isBoolean()).isFalse(); assertThat(testDocumentString.isNumber()).isFalse(); assertThat(testDocumentString.isMap()).isFalse(); assertThat(testDocumentString.isNull()).isFalse(); assertThat(testDocumentString.isList()).isFalse(); assertThat(Document.fromString(TEST_STRING_VALUE).hashCode()).isEqualTo(testDocumentString.hashCode()); assertThat(testDocumentString.equals(testDocumentString)).isTrue(); assertThat(Document.fromString("2").equals(SdkNumber.fromInteger(2))).isFalse(); assertThatThrownBy(() -> testDocumentString.asBoolean()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentString.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentString.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentString.asNumber()).isInstanceOf(UnsupportedOperationException.class); } @Test public void booleanDocumentTest() { final Document testDocumentBoolean = Document.fromBoolean(true); assertThat(testDocumentBoolean.asBoolean()).isTrue(); assertThat(testDocumentBoolean.hashCode()).isEqualTo(Document.fromBoolean(true).hashCode()); assertThat(testDocumentBoolean).isNotEqualTo(Document.fromString("true")); assertThat(testDocumentBoolean).hasToString(Document.fromString("true").unwrap().toString()); assertThat(testDocumentBoolean.isString()).isFalse(); assertThat(testDocumentBoolean.isBoolean()).isTrue(); assertThat(testDocumentBoolean.isNumber()).isFalse(); assertThat(testDocumentBoolean.isMap()).isFalse(); assertThat(testDocumentBoolean.isNull()).isFalse(); assertThat(testDocumentBoolean.isList()).isFalse(); assertThatThrownBy(() -> testDocumentBoolean.asString()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentBoolean.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentBoolean.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> testDocumentBoolean.asNumber()).isInstanceOf(UnsupportedOperationException.class); } @Test public void numberDocumentTest() { final Document documentNumber = Document.fromNumber(SdkNumber.fromLong(TEST_LONG_VALUE)); assertThat(documentNumber.asNumber().longValue()).isEqualTo(TEST_LONG_VALUE); assertThat(documentNumber.asNumber()).isEqualTo(SdkNumber.fromLong(TEST_LONG_VALUE)); assertThat(documentNumber.isString()).isFalse(); assertThat(documentNumber.isBoolean()).isFalse(); assertThat(documentNumber.isNumber()).isTrue(); assertThat(documentNumber.isMap()).isFalse(); assertThat(documentNumber.isNull()).isFalse(); assertThat(documentNumber.isList()).isFalse(); assertThat(documentNumber.hashCode()).isEqualTo(Objects.hashCode(SdkNumber.fromLong(TEST_LONG_VALUE))); assertThat(documentNumber).isNotEqualTo(Document.fromString("99")); assertThat(documentNumber.equals(documentNumber)).isTrue(); assertThatThrownBy(() -> documentNumber.asString()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> documentNumber.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> documentNumber.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> documentNumber.asBoolean()).isInstanceOf(UnsupportedOperationException.class); } @Test public void numberDocumentFromPrimitive() throws ParseException { assertThat(Document.fromNumber("2").asNumber()).isEqualTo(SdkNumber.fromString("2")); assertThat(Document.fromNumber(2).asNumber()).isEqualTo(SdkNumber.fromInteger(2)); assertThat(Document.fromNumber(2L).asNumber()).isEqualTo(SdkNumber.fromLong(2)); assertThat(Document.fromNumber(2.0).asNumber()).isEqualTo(SdkNumber.fromDouble(2.0)); assertThat(Document.fromNumber(2.0f).asNumber()).isEqualTo(SdkNumber.fromFloat(2)); assertThat(Document.fromNumber(2.0f).asNumber()).isEqualTo(SdkNumber.fromFloat(2)); assertThat(Document.fromNumber(BigDecimal.ONE).asNumber()).isEqualTo(SdkNumber.fromBigDecimal(new BigDecimal(1))); assertThat(Document.fromNumber(BigInteger.TEN).asNumber()).isEqualTo(SdkNumber.fromBigInteger(new BigInteger("10"))); assertThatThrownBy(() -> Document.fromNumber("foo").asNumber().longValue()).isInstanceOf(NumberFormatException.class); } @Test public void mapDocumentFromPrimitiveNumberBuilders() { final Document actualDocumentMap = Document.mapBuilder().putNumber("int", 1) .putNumber("long", 2L) .putNumber("float", 3.0f) .putNumber("double", 4.00) .putNumber("string", "5") .putNumber("bigDecimal", BigDecimal.TEN) .putNumber("bigInteger", BigInteger.TEN).build(); Map<String, Document> numberMap = new LinkedHashMap<>(); numberMap.put("int", Document.fromNumber(1)); numberMap.put("long", Document.fromNumber(2L)); numberMap.put("float", Document.fromNumber(3.0f)); numberMap.put("double", Document.fromNumber(4.00)); numberMap.put("string", Document.fromNumber("5")); numberMap.put("bigDecimal",Document.fromNumber(BigDecimal.TEN)); numberMap.put("bigInteger", Document.fromNumber(BigInteger.TEN)); final Document expectedMap = Document.fromMap(numberMap); assertThat(actualDocumentMap).isEqualTo(expectedMap); final Document innerMapDoc = Document.mapBuilder().putMap("innerMapKey", mapBuilder -> mapBuilder.putNumber("key", 1)).build(); Map<String, Document> innerMap = new HashMap<>(); innerMap.put("innerMap", innerMapDoc); Document documentMap = Document.mapBuilder().putMap("mapKey", innerMap).build(); assertThat(documentMap).hasToString("{\"mapKey\": {\"innerMap\": {\"innerMapKey\": {\"key\": 1}}}}"); assertThat(Document.fromMap(new HashMap<>())).hasToString("{}"); assertThat(Document.fromMap(new HashMap<>()).toString().equals(Document.fromString("{}"))).isFalse(); assertThat(Document.fromMap(new HashMap<>()).hashCode()).isEqualTo(new HashMap<>().hashCode()); final Document listDoc = Document.mapBuilder().putList("listDoc", new ArrayList<>()).build(); assertThat(listDoc).hasToString("{\"listDoc\": []}"); } @Test public void listDocumentFromPrimitiveNumberBuilders() { final Document actualDocList = ListDocument.listBuilder() .addNumber(1) .addNumber(2L) .addNumber(3.0f) .addNumber(4.0) .addNumber(BigDecimal.TEN) .addNumber(BigInteger.TEN) .addNumber("1000") .build(); List<Document> numberList = new ArrayList<>(); numberList.add(Document.fromNumber(1)); numberList.add(Document.fromNumber(2l)); numberList.add(Document.fromNumber(3.0f)); numberList.add(Document.fromNumber(4.0)); numberList.add(Document.fromNumber(BigDecimal.TEN)); numberList.add(Document.fromNumber(BigInteger.TEN)); numberList.add(Document.fromNumber("1000")); assertThat(actualDocList.asList()).isEqualTo(numberList); assertThat(Document.listBuilder().addString("string").build()) .isNotEqualTo(Document.fromString("string")); assertThat(Document.listBuilder().addString("string").build()) .isEqualTo(Document.listBuilder().addString("string").build()); assertThat(Document.listBuilder().addString("string").build().hashCode()) .isEqualTo(Document.listBuilder().addString("string").build().hashCode()); assertThat(actualDocList.equals(actualDocList)).isTrue(); } @Test public void mapDocumentTestWithMapBuilders() { final Document actualDocumentMap = Document.mapBuilder() .putString("key", "value") .putNull("nullKey") .putNumber("numberKey", SdkNumber.fromBigDecimal(new BigDecimal(100.1234567))) .putList("listKey", listBuilder -> listBuilder.addNumber(SdkNumber.fromLong(9))) .build(); final LinkedHashMap<String, Object> expectedMapObject = new LinkedHashMap<>(); expectedMapObject.put("key", "value"); expectedMapObject.put("nullKey", null); expectedMapObject.put("numberKey", new BigDecimal(100.1234567).toString()); expectedMapObject.put("listKey", Arrays.asList("9")); assertThat(actualDocumentMap.isString()).isFalse(); assertThat(actualDocumentMap.isBoolean()).isFalse(); assertThat(actualDocumentMap.isNumber()).isFalse(); assertThat(actualDocumentMap.isMap()).isTrue(); assertThat(actualDocumentMap.isNull()).isFalse(); assertThat(actualDocumentMap.isList()).isFalse(); assertThat(actualDocumentMap.unwrap()).isEqualTo(expectedMapObject); assertThatThrownBy(() -> actualDocumentMap.asString()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asNumber()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asBoolean()).isInstanceOf(UnsupportedOperationException.class); } @Test public void mapDocumentTestFromMapConstructors() { final LinkedHashMap<String, Object> expectedMapObject = new LinkedHashMap<>(); expectedMapObject.put("key", "value"); expectedMapObject.put("nullKey", null); expectedMapObject.put("numberKey", new BigDecimal(100.1234567).toString()); expectedMapObject.put("listKey", Arrays.asList("9")); final LinkedHashMap<String, Document> map = new LinkedHashMap<>(); map.put("key", Document.fromString("value")); map.put("nullKey", Document.fromNull()); map.put("numberKey", Document.fromNumber(SdkNumber.fromBigDecimal(new BigDecimal(100.1234567)))); map.put("listKey", Document.fromList(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(9))))); Document actualDocumentMap = Document.fromMap(map); assertThat(actualDocumentMap.isString()).isFalse(); assertThat(actualDocumentMap.isBoolean()).isFalse(); assertThat(actualDocumentMap.isNumber()).isFalse(); assertThat(actualDocumentMap.isMap()).isTrue(); assertThat(actualDocumentMap.isNull()).isFalse(); assertThat(actualDocumentMap.isList()).isFalse(); assertThat(actualDocumentMap.unwrap()).isEqualTo(expectedMapObject); assertThatThrownBy(() -> actualDocumentMap.asString()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asList()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asNumber()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> actualDocumentMap.asBoolean()).isInstanceOf(UnsupportedOperationException.class); } @Test public void listDocumentTest() { final Document listBuilder = Document.listBuilder() .addDocument(Document.fromString("one")).addNumber(SdkNumber.fromLong(2)).addBoolean(true) .addMap(mapBuilder -> mapBuilder.putString("consumerKey", "consumerKeyMap")) .addString("string") .addNull() .build(); assertThat(listBuilder.isString()).isFalse(); assertThat(listBuilder.isBoolean()).isFalse(); assertThat(listBuilder.isNumber()).isFalse(); assertThat(listBuilder.isMap()).isFalse(); assertThat(listBuilder.isNull()).isFalse(); assertThat(listBuilder.isList()).isTrue(); assertThatThrownBy(() -> listBuilder.asString()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> listBuilder.asMap()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> listBuilder.asNumber()).isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> listBuilder.asBoolean()).isInstanceOf(UnsupportedOperationException.class); assertThat(listBuilder.asList().get(0).asString()).isEqualTo("one"); assertThat(listBuilder.asList().get(1).asNumber()).isEqualTo(SdkNumber.fromLong(2)); assertThat(listBuilder.asList().get(2).asBoolean()).isTrue(); assertThat(listBuilder.asList().get(3).isMap()).isTrue(); assertThat(listBuilder.asList().get(3)).isEqualTo(Document.mapBuilder().putString("consumerKey", "consumerKeyMap") .build()); assertThat(listBuilder.asList().get(4).isString()).isTrue(); assertThat(listBuilder.asList().get(4)).isEqualTo(Document.fromString("string")); assertThat(listBuilder.asList().get(5).isNull()).isTrue(); assertThat(listBuilder.asList().get(5)).isEqualTo(Document.fromNull()); assertThat(Document.listBuilder().addNumber(SdkNumber.fromLong(1)).addNumber(SdkNumber.fromLong(2)).addNumber(SdkNumber.fromLong(3)) .addNumber(SdkNumber.fromLong(4)).addNumber(SdkNumber.fromLong(5)).build().asList()) .isEqualTo(Arrays.asList(Document.fromNumber(SdkNumber.fromLong(1)), Document.fromNumber(SdkNumber.fromLong(2)), Document.fromNumber(SdkNumber.fromLong(3)), Document.fromNumber(SdkNumber.fromLong(4)), Document.fromNumber(SdkNumber.fromLong(5)))); } @Test public void testStringDocumentEscapeQuotes() { // Actual String is <start>"mid"<end> Document docWithQuotes = Document.fromString("<start>" + '\u0022' + "mid" + '\u0022' + "<end>"); //We expect the quotes <start>\"mid\"<end> assertThat(docWithQuotes).hasToString("\"<start>\\\"mid\\\"<end>\""); Document docWithNoQuotes = Document.fromString("testString"); assertThat(docWithNoQuotes).hasToString("\"testString\""); assertThat("\"" + docWithNoQuotes.asString() + "\"").isEqualTo(docWithNoQuotes.toString()); } @Test public void testStringDocumentEscapeBackSlash() { String testString = "test\\String"; Document document = Document.fromString(testString); assertThat(document).hasToString("\"test\\\\String\""); assertThat("\"" + document.asString() + "\"").isNotEqualTo(document.toString()); } }
1,730
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/NoopTestRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import java.util.Collections; import java.util.List; import java.util.Optional; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkRequestOverrideConfiguration; public class NoopTestRequest extends SdkRequest { private final SdkRequestOverrideConfiguration requestOverrideConfig; private NoopTestRequest(Builder builder) { this.requestOverrideConfig = builder.overrideConfiguration(); } @Override public Optional<SdkRequestOverrideConfiguration> overrideConfiguration() { return Optional.ofNullable(requestOverrideConfig); } @Override public Builder toBuilder() { return new BuilderImpl(); } public static Builder builder() { return new BuilderImpl(); } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } public interface Builder extends SdkRequest.Builder { @Override NoopTestRequest build(); @Override SdkRequestOverrideConfiguration overrideConfiguration(); Builder overrideConfiguration(SdkRequestOverrideConfiguration requestOverrideConfig); } private static class BuilderImpl implements Builder { private SdkRequestOverrideConfiguration requestOverrideConfig; @Override public SdkRequestOverrideConfiguration overrideConfiguration() { return requestOverrideConfig; } public Builder overrideConfiguration(SdkRequestOverrideConfiguration requestOverrideConfig) { this.requestOverrideConfig = requestOverrideConfig; return this; } @Override public NoopTestRequest build() { return new NoopTestRequest(this); } } }
1,731
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/InterruptFlagAlwaysClearsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.io.IOException; import java.time.Duration; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkSyncClientHandler; import software.amazon.awssdk.core.exception.AbortedException; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpResponse; import utils.HttpTestUtils; @RunWith(MockitoJUnitRunner.class) public class InterruptFlagAlwaysClearsTest { private static final Duration SERVICE_LATENCY = Duration.ofMillis(10); private static SdkSyncClientHandler syncHttpClient; @Mock private Marshaller<SdkRequest> marshaller; @Mock private HttpResponseHandler<SdkResponse> responseHandler; @Mock(lenient = true) private HttpResponseHandler<SdkServiceException> errorResponseHandler; @BeforeClass public static void setup() { SdkClientConfiguration clientConfiguration = HttpTestUtils.testClientConfiguration() .toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, new SleepyHttpClient()) .option(SdkClientOption.API_CALL_ATTEMPT_TIMEOUT, SERVICE_LATENCY) .build(); syncHttpClient = new TestClientHandler(clientConfiguration); } @Before public void methodSetup() throws Exception { when(marshaller.marshall(any(NoopTestRequest.class))) .thenReturn(SdkHttpFullRequest.builder() .protocol("http") .host("some-host.aws") .method(SdkHttpMethod.GET) .build()); when(errorResponseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))) .thenReturn(SdkServiceException.builder().message("BOOM").statusCode(400).build()); } @AfterClass public static void cleanup() { syncHttpClient.close(); } @Test public void interruptFlagClearsWithTimeoutCloseToLatency() { int numRuns = 100; int interruptCount = 0; for (int i = 0; i < numRuns; ++i) { // This request is expected to time out for some number of iterations executeRequestIgnoreErrors(syncHttpClient); // Check and clear interrupt flag if (Thread.interrupted()) { ++interruptCount; } } assertThat(interruptCount) .withFailMessage("Interrupt flags are leaking: %d of %d runs leaked interrupt flags.", interruptCount, numRuns) .isEqualTo(0); } private void executeRequestIgnoreErrors(SdkSyncClientHandler syncHttpClient) { try { syncHttpClient.execute(new ClientExecutionParams<SdkRequest, SdkResponse>() .withOperationName("SomeOperation") .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler) .withInput(NoopTestRequest.builder().build()) .withMarshaller(marshaller)); Assert.fail(); } catch (AbortedException | ApiCallAttemptTimeoutException | SdkServiceException e) { // Ignored } } private static class SleepyHttpClient implements SdkHttpClient { private static final HttpExecuteResponse RESPONSE = HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(400) .build()) .build(); @Override public ExecutableHttpRequest prepareRequest(HttpExecuteRequest request) { return new ExecutableHttpRequest() { @Override public HttpExecuteResponse call() throws IOException { try { Thread.sleep(SERVICE_LATENCY.toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted!", e); } return RESPONSE; } @Override public void abort() { } }; } @Override public void close() { } } private static class TestClientHandler extends SdkSyncClientHandler { protected TestClientHandler(SdkClientConfiguration clientConfiguration) { super(clientConfiguration); } } }
1,732
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/AmazonHttpClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import java.io.IOException; import java.net.URI; import java.util.concurrent.ExecutorService; import org.junit.Assert; import org.junit.Before; 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.core.ClientType; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.pipeline.stages.ApplyUserAgentStage; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpResponse; import utils.HttpTestUtils; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class AmazonHttpClientTest { @Mock private SdkHttpClient sdkHttpClient; @Mock private ExecutableHttpRequest abortableCallable; @Mock private ExecutorService executor; private AmazonSyncHttpClient client; @Before public void setUp() throws Exception { client = HttpTestUtils.testClientBuilder().httpClient(sdkHttpClient).build(); when(sdkHttpClient.prepareRequest(any())).thenReturn(abortableCallable); when(sdkHttpClient.clientName()).thenReturn("UNKNOWN"); stubSuccessfulResponse(); } @Test public void testRetryIoExceptionFromExecute() throws Exception { IOException ioException = new IOException("BOOM"); when(abortableCallable.call()).thenThrow(ioException); ExecutionContext context = ClientExecutionAndRequestTimerTestUtils.executionContext(null); try { client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(context) .execute(combinedSyncResponseHandler(null, null)); Assert.fail("No exception when request repeatedly fails!"); } catch (SdkClientException e) { Assert.assertSame(ioException, e.getCause()); } // Verify that we called execute 4 times. verify(sdkHttpClient, times(4)).prepareRequest(any()); } @Test public void testRetryIoExceptionFromHandler() throws Exception { final IOException exception = new IOException("BOOM"); HttpResponseHandler<?> mockHandler = mock(HttpResponseHandler.class); when(mockHandler.handle(any(), any())).thenThrow(exception); ExecutionContext context = ClientExecutionAndRequestTimerTestUtils.executionContext(null); try { client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(context) .execute(combinedSyncResponseHandler(mockHandler, null)); Assert.fail("No exception when request repeatedly fails!"); } catch (SdkClientException e) { Assert.assertSame(exception, e.getCause()); } // Verify that we called execute 4 times. verify(mockHandler, times(4)).handle(any(), any()); } @Test public void testUserAgentPrefixAndSuffixAreAdded() { String prefix = "somePrefix"; String suffix = "someSuffix-blah-blah"; HttpResponseHandler<?> handler = mock(HttpResponseHandler.class); String clientUserAgent = ApplyUserAgentStage.resolveClientUserAgent(prefix, "", ClientType.SYNC, sdkHttpClient, null, RetryPolicy.forRetryMode(RetryMode.STANDARD)); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkAdvancedClientOption.USER_AGENT_SUFFIX, suffix) .option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent) .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .build(); AmazonSyncHttpClient client = new AmazonSyncHttpClient(config); client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .execute(combinedSyncResponseHandler(handler, null)); ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture()); final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent") .orElseThrow(() -> new AssertionError("User-Agent header was not found")); Assert.assertTrue(userAgent.startsWith(prefix)); Assert.assertTrue(userAgent.endsWith(suffix)); } @Test public void testUserAgentContainsHttpClientInfo() { HttpResponseHandler<?> handler = mock(HttpResponseHandler.class); String clientUserAgent = ApplyUserAgentStage.resolveClientUserAgent(null, null, ClientType.SYNC, sdkHttpClient, null, RetryPolicy.forRetryMode(RetryMode.STANDARD)); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .option(SdkClientOption.CLIENT_TYPE, ClientType.SYNC) .option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent) .build(); AmazonSyncHttpClient client = new AmazonSyncHttpClient(config); client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .execute(combinedSyncResponseHandler(handler, null)); ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture()); final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent") .orElseThrow(() -> new AssertionError("User-Agent header was not found")); Assert.assertTrue(userAgent.contains("io/sync")); Assert.assertTrue(userAgent.contains("http/UNKNOWN")); } @Test public void testUserAgentContainsRetryModeInfo() { HttpResponseHandler<?> handler = mock(HttpResponseHandler.class); String clientUserAgent = ApplyUserAgentStage.resolveClientUserAgent(null, null, ClientType.SYNC, sdkHttpClient, null, RetryPolicy.forRetryMode(RetryMode.STANDARD)); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.CLIENT_USER_AGENT, clientUserAgent) .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .build(); AmazonSyncHttpClient client = new AmazonSyncHttpClient(config); client.requestExecutionBuilder() .request(ValidSdkObjects.sdkHttpFullRequest().build()) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(null)) .execute(combinedSyncResponseHandler(handler, null)); ArgumentCaptor<HttpExecuteRequest> httpRequestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); verify(sdkHttpClient).prepareRequest(httpRequestCaptor.capture()); final String userAgent = httpRequestCaptor.getValue().httpRequest().firstMatchingHeader("User-Agent") .orElseThrow(() -> new AssertionError("User-Agent header was not found")); Assert.assertTrue(userAgent.contains("cfg/retry-mode/standard")); } @Test public void closeClient_shouldCloseDependencies() { SdkClientConfiguration config = HttpTestUtils.testClientConfiguration() .toBuilder() .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, executor) .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .build(); AmazonSyncHttpClient client = new AmazonSyncHttpClient(config); client.close(); verify(sdkHttpClient).close(); verify(executor).shutdown(); } private void stubSuccessfulResponse() throws Exception { when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder().response(SdkHttpResponse.builder() .statusCode(200) .build()) .build()); } }
1,733
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/ContentStreamProviderWireMockTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler; import software.amazon.awssdk.core.io.SdkFilterInputStream; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import utils.HttpTestUtils; import utils.http.WireMockTestBase; /** * WireMock tests related to {@link ContentStreamProvider} usage. */ public class ContentStreamProviderWireMockTest extends WireMockTestBase { private static final String OPERATION = "/some-operation"; @Test public void closesAllCreatedInputStreamsFromProvider() { stubFor(any(urlPathEqualTo(OPERATION)).willReturn(aResponse().withStatus(500))); TestContentStreamProvider provider = new TestContentStreamProvider(); SdkHttpFullRequest request = newRequest(OPERATION) .contentStreamProvider(provider) .method(SdkHttpMethod.PUT) .build(); AmazonSyncHttpClient testClient = HttpTestUtils.testAmazonHttpClient(); try { sendRequest(request, testClient); fail("Should have thrown SdkServiceException"); } catch (SdkServiceException ignored) { } // The test client uses the default retry policy so there should be 4 // total attempts and an equal number created streams assertThat(provider.getCreatedStreams().size()).isEqualTo(4); for (CloseTrackingInputStream is : provider.getCreatedStreams()) { assertThat(is.isClosed()).isTrue(); } } private void sendRequest(SdkHttpFullRequest request, AmazonSyncHttpClient sut) { sut.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler())); } private static class TestContentStreamProvider implements ContentStreamProvider { private static final byte[] CONTENT_BYTES = "Hello".getBytes(StandardCharsets.UTF_8); private List<CloseTrackingInputStream> createdStreams = new ArrayList<>(); @Override public InputStream newStream() { closeCurrentStream(); CloseTrackingInputStream s = newContentStream(); createdStreams.add(s); return s; } List<CloseTrackingInputStream> getCreatedStreams() { return createdStreams; } private CloseTrackingInputStream newContentStream() { return new CloseTrackingInputStream(new ByteArrayInputStream(CONTENT_BYTES)); } private void closeCurrentStream() { if (createdStreams.isEmpty()) { return; } invokeSafely(() -> createdStreams.get(createdStreams.size() - 1).close()); } } private static class CloseTrackingInputStream extends SdkFilterInputStream { private boolean isClosed = false; CloseTrackingInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { super.close(); isClosed = true; } boolean isClosed() { return isClosed; } } }
1,734
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/SdkTransactionIdInHeaderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; 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.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.pipeline.stages.ApplyTransactionIdStage; import software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils; import software.amazon.awssdk.http.SdkHttpFullRequest; import utils.HttpTestUtils; import utils.http.WireMockTestBase; public class SdkTransactionIdInHeaderTest extends WireMockTestBase { private static final String RESOURCE_PATH = "/transaction-id/"; @Test public void retriedRequest_HasSameTransactionIdForAllRetries() throws Exception { stubFor(get(urlEqualTo(RESOURCE_PATH)).willReturn(aResponse().withStatus(500))); executeRequest(); assertTransactionIdIsUnchangedAcrossRetries(); } private void assertTransactionIdIsUnchangedAcrossRetries() { String previousTransactionId = null; for (LoggedRequest request : findAll(getRequestedFor(urlEqualTo(RESOURCE_PATH)))) { final String currentTransactionId = request.getHeader(ApplyTransactionIdStage.HEADER_SDK_TRANSACTION_ID); // Transaction ID should always be set assertNotNull(currentTransactionId); // Transaction ID should be the same across retries if (previousTransactionId != null) { assertEquals(previousTransactionId, currentTransactionId); } previousTransactionId = currentTransactionId; } } private void executeRequest() throws Exception { AmazonSyncHttpClient httpClient = HttpTestUtils.testAmazonHttpClient(); try { SdkHttpFullRequest request = newGetRequest(RESOURCE_PATH).build(); httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(ClientExecutionAndRequestTimerTestUtils.executionContext(request)) .execute(combinedSyncResponseHandler(null, stubErrorHandler())); fail("Expected exception"); } catch (SdkServiceException expected) { // Ignored or expected. } } }
1,735
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/UnresponsiveMockServerTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import software.amazon.awssdk.core.http.server.MockServer; public abstract class UnresponsiveMockServerTestBase extends MockServerTestBase { @Override protected MockServer buildMockServer() { return MockServer.createMockServer(MockServer.ServerBehavior.UNRESPONSIVE); } }
1,736
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/Crc32ValidationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.util.zip.GZIPInputStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import org.unitils.util.ReflectionUtils; import software.amazon.awssdk.core.internal.util.Crc32ChecksumValidatingInputStream; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.StringInputStream; @RunWith(MockitoJUnitRunner.class) public class Crc32ValidationTest { @Test public void adapt_InputStreamWithNoGzipOrCrc32_NotWrappedWhenAdapted() { InputStream content = new StringInputStream("content"); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = adapt(httpResponse); InputStream in = adapted.content().get().delegate(); assertThat(in).isEqualTo(content); } @Test public void adapt_InputStreamWithCrc32Header_WrappedWithValidatingStream() throws UnsupportedEncodingException { InputStream content = new StringInputStream("content"); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("x-amz-crc32", "1234") .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = adapt(httpResponse); InputStream in = adapted.content().get().delegate(); assertThat(in).isInstanceOf((Crc32ChecksumValidatingInputStream.class)); } @Test public void adapt_InputStreamWithGzipEncoding_WrappedWithDecompressingStream() throws IOException { try (InputStream content = getClass().getResourceAsStream("/resources/compressed_json_body.gz")) { SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("Content-Encoding", "gzip") .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = adapt(httpResponse); InputStream in = adapted.content().get().delegate(); assertThat(in).isInstanceOf((GZIPInputStream.class)); } } @Test public void adapt_CalculateCrcFromCompressed_WrapsWithCrc32ThenGzip() throws IOException { try (InputStream content = getClass().getResourceAsStream("/resources/compressed_json_body.gz")) { SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("Content-Encoding", "gzip") .putHeader("x-amz-crc32", "1234") .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = Crc32Validation.validate(true, httpResponse); InputStream in = adapted.content().get().delegate(); assertThat(in).isInstanceOf((GZIPInputStream.class)); } } @Test(expected = UncheckedIOException.class) public void adapt_InvalidGzipContent_ThrowsException() throws UnsupportedEncodingException { InputStream content = new StringInputStream("this isn't GZIP"); SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("Content-Encoding", "gzip") .content(AbortableInputStream.create(content)) .build(); SdkHttpFullResponse adapted = adapt(httpResponse); InputStream in = adapted.content().get().delegate(); assertThat(in).isInstanceOf((GZIPInputStream.class)); } @Test public void adapt_ResponseWithCrc32Header_And_NoContent_DoesNotThrowNPE() throws UnsupportedEncodingException { SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("x-amz-crc32", "1234") .build(); SdkHttpFullResponse adapted = adapt(httpResponse); assertThat(adapted.content().isPresent()).isFalse(); } @Test public void adapt_ResponseGzipEncoding_And_NoContent_DoesNotThrowNPE() throws IOException { SdkHttpFullResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(200) .putHeader("Content-Encoding", "gzip") .build(); SdkHttpFullResponse adapted = adapt(httpResponse); assertThat(adapted.content().isPresent()).isFalse(); } private SdkHttpFullResponse adapt(SdkHttpFullResponse httpResponse) { return Crc32Validation.validate(false, httpResponse); } @SuppressWarnings("unchecked") private static <T> T getField(Object obj, String fieldName) { try { Field field = ReflectionUtils.getFieldWithName(obj.getClass(), fieldName, false); field.setAccessible(true); return (T) field.get(obj); } catch (Exception e) { throw new RuntimeException(e); } } }
1,737
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/AmazonHttpClientWireMockTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.optionsRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import utils.HttpTestUtils; import utils.http.WireMockTestBase; public class AmazonHttpClientWireMockTest extends WireMockTestBase { private static final String OPERATION = "/some-operation"; private static final String HEADER = "Some-Header"; private static final String CONFIG_HEADER_VALUE = "client config header value"; private static final String REQUEST_HEADER_VALUE = "request header value"; @Before public void setUp() { stubFor(any(urlPathEqualTo(OPERATION)).willReturn(aResponse())); } @Test public void headersSpecifiedInClientConfigurationArePutOnRequest() { SdkHttpFullRequest request = newGetRequest(OPERATION).build(); AmazonSyncHttpClient sut = createClient(HEADER, CONFIG_HEADER_VALUE); sendRequest(request, sut); verify(getRequestedFor(urlPathEqualTo(OPERATION)).withHeader(HEADER, matching(CONFIG_HEADER_VALUE))); } @Test public void headersOnRequestsWinOverClientConfigurationHeaders() { SdkHttpFullRequest request = newGetRequest(OPERATION) .putHeader(HEADER, REQUEST_HEADER_VALUE) .build(); AmazonSyncHttpClient sut = createClient(HEADER, CONFIG_HEADER_VALUE); sendRequest(request, sut); verify(getRequestedFor(urlPathEqualTo(OPERATION)).withHeader(HEADER, matching(REQUEST_HEADER_VALUE))); } @Test public void canHandleOptionsRequest() { SdkHttpFullRequest request = newRequest(OPERATION) .method(SdkHttpMethod.OPTIONS) .build(); AmazonSyncHttpClient sut = HttpTestUtils.testAmazonHttpClient(); sendRequest(request, sut); verify(optionsRequestedFor(urlPathEqualTo(OPERATION))); } private void sendRequest(SdkHttpFullRequest request, AmazonSyncHttpClient sut) { sut.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler())); } private AmazonSyncHttpClient createClient(String headerName, String headerValue) { return HttpTestUtils.testClientBuilder().additionalHeader(headerName, headerValue).build(); } }
1,738
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/MockServerTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import org.junit.After; import org.junit.Before; import software.amazon.awssdk.core.http.server.MockServer; public abstract class MockServerTestBase { protected MockServer server; @Before public void setupBaseFixture() { server = buildMockServer(); server.startServer(); } @After public void tearDownBaseFixture() { server.stopServer(); } /** * Implemented by test subclasses to build the correct type of {@link MockServer} */ protected abstract MockServer buildMockServer(); }
1,739
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/http/server/MockServer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.http.server; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.URI; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringInputStream; /** * MockServer implementation with several different configurable behaviors */ public class MockServer { private final ServerBehaviorStrategy serverBehaviorStrategy; /** * The server socket which the test service will listen to. */ private ServerSocket serverSocket; private Thread listenerThread; public MockServer(final ServerBehaviorStrategy serverBehaviorStrategy) { this.serverBehaviorStrategy = serverBehaviorStrategy; } public static MockServer createMockServer(ServerBehavior serverBehavior) { switch (serverBehavior) { case UNRESPONSIVE: return new MockServer(new UnresponsiveServerBehavior()); case OVERLOADED: return new MockServer(new OverloadedServerBehavior()); default: throw new IllegalArgumentException("Unsupported implementation for server issue: " + serverBehavior); } } public void startServer() { try { serverSocket = new ServerSocket(0); // auto-assign a port at localhost System.out.println("Listening on port " + serverSocket.getLocalPort()); } catch (IOException e) { throw new RuntimeException("Unable to start the server socker.", e); } listenerThread = new MockServerListenerThread(serverSocket, serverBehaviorStrategy); listenerThread.setDaemon(true); listenerThread.start(); } public void stopServer() { listenerThread.interrupt(); try { listenerThread.join(10 * 1000); } catch (InterruptedException e1) { System.err.println("The listener thread didn't terminate " + "after waiting for 10 seconds."); } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { throw new RuntimeException("Unable to stop the server socket.", e); } } } public int getPort() { return serverSocket.getLocalPort(); } public SdkHttpFullRequest.Builder configureHttpsEndpoint(SdkHttpFullRequest.Builder request) { return request.uri(URI.create("https://localhost")) .port(getPort()); } public SdkHttpFullRequest.Builder configureHttpEndpoint(SdkHttpFullRequest.Builder request) { return request.uri(URI.create("http://localhost")) .port(getPort()); } public enum ServerBehavior { UNRESPONSIVE, OVERLOADED, DUMMY_RESPONSE; } public interface ServerBehaviorStrategy { void runServer(ServerSocket serverSocket); } private static class MockServerListenerThread extends Thread { /** The server socket which this thread listens and responds to. */ private final ServerSocket serverSocket; private final ServerBehaviorStrategy behaviorStrategy; public MockServerListenerThread(ServerSocket serverSocket, ServerBehaviorStrategy behaviorStrategy) { super(behaviorStrategy.getClass().getName()); this.serverSocket = serverSocket; this.behaviorStrategy = behaviorStrategy; setDaemon(true); } @Override public void run() { this.behaviorStrategy.runServer(serverSocket); } } /** * A daemon thread which runs a simple server that listens to a specific server socket. Whenever * a connection is created, the server simply keeps holding the connection open while * periodically writing data. The test client talking to this server is expected to timeout * appropriately, instead of hanging and waiting for the response forever. */ public static class OverloadedServerBehavior implements ServerBehaviorStrategy { @Override public void runServer(ServerSocket serverSocket) { try { while (true) { Socket socket = null; try { socket = serverSocket.accept(); try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) { out.writeBytes("HTTP/1.1 200 OK\r\n"); out.writeBytes("Content-Type: text/html\r\n"); out.writeBytes("Content-Length: 500\r\n\r\n"); out.writeBytes("<html><head></head><body><h1>Hello."); while (true) { Thread.sleep(1 * 1000); out.writeBytes("Hi."); } } } catch (SocketException se) { // Ignored or expected. } finally { if (socket != null) { socket.close(); } } } } catch (IOException e) { throw new RuntimeException("Error when waiting for new socket connection.", e); } catch (InterruptedException e) { System.err.println("Socket listener thread interrupted. Terminating the thread..."); return; } } } /** * A daemon thread which runs a simple server that listens to a specific server socket. Whenever * a connection is created, the server simply keeps holding the connection open and no byte will * be written to the socket. The test client talking to this server is expected to timeout * appropriately, instead of hanging and waiting for the response forever. */ public static class UnresponsiveServerBehavior implements ServerBehaviorStrategy { @Override public void runServer(ServerSocket serverSocket) { Socket socket = null; try { socket = serverSocket.accept(); System.out.println("Socket created on port " + socket.getLocalPort()); while (true) { System.out.println("I don't want to talk."); Thread.sleep(10 * 1000); } } catch (IOException e) { throw new RuntimeException("Error when waiting for new socket connection.", e); } catch (InterruptedException e) { System.err.println("Socket listener thread interrupted. Terminating the thread..."); return; } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { throw new RuntimeException("Fail to close the socket", e); } } } } public static class DummyResponseServerBehavior implements ServerBehaviorStrategy { private final HttpResponse response; private String content; public DummyResponseServerBehavior(HttpResponse response) { this.response = response; try { this.content = IoUtils.toUtf8String(response.getEntity().getContent()); } catch (Exception e) { // Ignored or expected. } } public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) { HttpResponse response = new BasicHttpResponse( new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage)); setEntity(response, content); response.addHeader("Content-Length", String.valueOf(content.getBytes().length)); response.addHeader("Connection", "close"); return new DummyResponseServerBehavior(response); } private static void setEntity(HttpResponse response, String content) { BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new StringInputStream(content)); response.setEntity(entity); } @Override public void runServer(ServerSocket serverSocket) { try { while (true) { Socket socket = null; try { socket = serverSocket.accept(); try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) { StringBuilder builder = new StringBuilder(); builder.append(response.getStatusLine().toString() + "\r\n"); for (Header header : response.getAllHeaders()) { builder.append(header.getName() + ":" + header.getValue() + "\r\n"); } builder.append("\r\n"); builder.append(content); System.out.println(builder.toString()); out.writeBytes(builder.toString()); } } catch (SocketException se) { // Ignored or expected. } finally { if (socket != null) { socket.close(); } } } } catch (IOException e) { throw new RuntimeException("Error when waiting for new socket connection.", e); } } } }
1,740
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/compression/CompressorTypeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.compression; import static org.assertj.core.api.Assertions.assertThat; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.compression.CompressorType; public class CompressorTypeTest { @Test public void equalsHashcode() { EqualsVerifier.forClass(CompressorType.class) .withNonnullFields("id") .verify(); } @Test public void compressorType_gzip() { CompressorType gzip = CompressorType.GZIP; CompressorType gzipFromString = CompressorType.of("gzip"); assertThat(gzip).isSameAs(gzipFromString); assertThat(gzip).isEqualTo(gzipFromString); } @Test public void compressorType_usesSameInstance_when_sameCompressorTypeOfSameValue() { CompressorType brotliFromString = CompressorType.of("brotli"); CompressorType brotliFromStringDuplicate = CompressorType.of("brotli"); assertThat(brotliFromString).isSameAs(brotliFromStringDuplicate); assertThat(brotliFromString).isEqualTo(brotliFromStringDuplicate); } }
1,741
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/sync/RequestBodyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.sync; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringInputStream; public class RequestBodyTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void stringConstructorUsesUTF8ByteLength() { // U+03A9 U+03C9 final String multibyteChars = "Ωω"; RequestBody rb = RequestBody.fromString(multibyteChars); assertThat(rb.contentLength()).isEqualTo(4L); } @Test public void stringConstructorHasCorrectContentType() { RequestBody requestBody = RequestBody.fromString("hello world"); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=UTF-8"); } @Test public void stringConstructorWithCharsetHasCorrectContentType() { RequestBody requestBody = RequestBody.fromString("hello world", StandardCharsets.US_ASCII); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_TEXT_PLAIN + "; charset=US-ASCII"); } @Test public void fileConstructorHasCorrectContentType() throws IOException { FileSystem fs = Jimfs.newFileSystem(Configuration.unix()); Path path = fs.getPath("./test"); Files.write(path, "hello world".getBytes()); RequestBody requestBody = RequestBody.fromFile(path); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void streamConstructorHasCorrectContentType() { StringInputStream inputStream = new StringInputStream("hello world"); RequestBody requestBody = RequestBody.fromInputStream(inputStream, 11); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); IoUtils.closeQuietly(inputStream, null); } @Test public void nonMarkSupportedInputStreamContentType() throws IOException { File file = folder.newFile(); try (FileWriter writer = new FileWriter(file)) { writer.write("hello world"); } InputStream inputStream = Files.newInputStream(file.toPath()); RequestBody requestBody = RequestBody.fromInputStream(inputStream, 11); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); assertThat(requestBody.contentStreamProvider().newStream()).isNotNull(); IoUtils.closeQuietly(inputStream, null); } @Test public void bytesArrayConstructorHasCorrectContentType() { RequestBody requestBody = RequestBody.fromBytes("hello world".getBytes()); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void bytesBufferConstructorHasCorrectContentType() { ByteBuffer byteBuffer = ByteBuffer.wrap("hello world".getBytes()); RequestBody requestBody = RequestBody.fromByteBuffer(byteBuffer); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void emptyBytesConstructorHasCorrectContentType() { RequestBody requestBody = RequestBody.empty(); assertThat(requestBody.contentType()).isEqualTo(Mimetype.MIMETYPE_OCTET_STREAM); } @Test public void contentProviderConstuctorWithNullContentLength_NoContentLength() { byte[] bytes = new byte[0]; RequestBody requestBody = RequestBody.fromContentProvider(() -> new ByteArrayInputStream(bytes), Mimetype.MIMETYPE_OCTET_STREAM); assertThat(requestBody.optionalContentLength().isPresent()).isFalse(); assertThatThrownBy(() -> requestBody.contentLength()).isInstanceOf(IllegalStateException.class); } @Test public void remainingByteBufferConstructorOnlyRemainingBytesCopied() throws IOException { ByteBuffer bb = ByteBuffer.allocate(4); bb.put(new byte[]{1, 2, 3, 4}); bb.flip(); bb.get(); bb.get(); int originalRemaining = bb.remaining(); RequestBody requestBody = RequestBody.fromRemainingByteBuffer(bb); assertThat(requestBody.contentLength()).isEqualTo(originalRemaining); byte[] requestBodyBytes = IoUtils.toByteArray(requestBody.contentStreamProvider().newStream()); assertThat(ByteBuffer.wrap(requestBodyBytes)).isEqualTo(bb); } }
1,742
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/checksum/AwsChunkedEncodingInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.checksum; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.core.internal.util.ChunkContentUtils.calculateChecksumTrailerLength; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.internal.io.AwsChunkedEncodingInputStream; import software.amazon.awssdk.core.internal.io.AwsUnsignedChunkedEncodingInputStream; import software.amazon.awssdk.core.internal.util.ChunkContentUtils; public class AwsChunkedEncodingInputStreamTest { private static final String CRLF = "\r\n"; final private static Algorithm SHA256_ALGORITHM = Algorithm.SHA256; final private String SHA256_HEADER_NAME = "x-amz-checksum-sha-256"; @Test public void readAwsUnsignedChunkedEncodingInputStream() throws IOException { String initialString = "Hello world"; InputStream targetStream = new ByteArrayInputStream(initialString.getBytes()); final AwsChunkedEncodingInputStream checksumCalculatingInputStream = AwsUnsignedChunkedEncodingInputStream.builder() .inputStream(targetStream) .sdkChecksum(SdkChecksum.forAlgorithm(SHA256_ALGORITHM)) .checksumHeaderForTrailer(SHA256_HEADER_NAME) .build(); StringBuilder sb = new StringBuilder(); for (int ch; (ch = checksumCalculatingInputStream.read()) != -1; ) { sb.append((char) ch); } assertThat(sb).hasToString("b" + CRLF + initialString +CRLF + "0" + CRLF + "x-amz-checksum-sha-256:ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=" + CRLF+CRLF); } @Test public void lengthsOfCalculateByChecksumCalculatingInputStream(){ String initialString = "Hello world"; long calculateChunkLength = ChunkContentUtils.calculateStreamContentLength(initialString.length(), AwsChunkedEncodingInputStream.DEFAULT_CHUNK_SIZE); long checksumContentLength = calculateChecksumTrailerLength(SHA256_ALGORITHM, SHA256_HEADER_NAME); assertThat(calculateChunkLength).isEqualTo(19); assertThat(checksumContentLength).isEqualTo(71); } @Test public void markAndResetAwsChunkedEncodingInputStream() throws IOException { String initialString = "Hello world"; InputStream targetStream = new ByteArrayInputStream(initialString.getBytes()); final AwsChunkedEncodingInputStream checksumCalculatingInputStream = AwsUnsignedChunkedEncodingInputStream.builder() .inputStream(targetStream) .sdkChecksum(SdkChecksum.forAlgorithm(SHA256_ALGORITHM)) .checksumHeaderForTrailer(SHA256_HEADER_NAME) .build(); StringBuilder sb = new StringBuilder(); checksumCalculatingInputStream.mark(3); boolean marked = true; int count = 0; for (int ch; (ch = checksumCalculatingInputStream.read()) != -1; ) { sb.append((char) ch); if(marked && count++ == 5){ checksumCalculatingInputStream.reset(); sb = new StringBuilder(); marked = false; } } assertThat(sb).hasToString("b" + CRLF + initialString +CRLF + "0" + CRLF + "x-amz-checksum-sha-256:ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=" + CRLF+CRLF); } }
1,743
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/checksum/ChecksumInstantiationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.checksum; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigInteger; import java.nio.charset.StandardCharsets; 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.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.utils.BinaryUtils; class ChecksumInstantiationTest { static final String TEST_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static Stream<Arguments> provideAlgorithmAndTestStringChecksums() { return Stream.of( Arguments.of(Algorithm.SHA1, "761c457bf73b14d27e9e9265c46f4b4dda11f940"), Arguments.of(Algorithm.SHA256, "db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0"), Arguments.of(Algorithm.CRC32, "000000000000000000000000000000001fc2e6d2"), Arguments.of(Algorithm.CRC32C, "00000000000000000000000000000000a245d57d") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndTestStringChecksums") void validateCheckSumValues(Algorithm algorithm, String expectedValue) { final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); final byte[] bytes = TEST_STRING.getBytes(StandardCharsets.UTF_8); sdkChecksum.update(bytes, 0, bytes.length); assertThat(getAsString(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue); } private static Stream<Arguments> provideAlgorithmAndTestBaseEncodedValue() { return Stream.of( Arguments.of(Algorithm.CRC32C, "Nks/tw=="), Arguments.of(Algorithm.CRC32, "NSRBwg=="), Arguments.of(Algorithm.SHA1, "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="), Arguments.of(Algorithm.SHA256, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndTestBaseEncodedValue") void validateEncodedBase64ForAlgorithm(Algorithm algorithm, String expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update("abc".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()); assertThat(toBase64).isEqualTo(expectedValue); } private static Stream<Arguments> provideAlgorithmAndTestMarkReset() { return Stream.of( Arguments.of(Algorithm.CRC32C, "Nks/tw=="), Arguments.of(Algorithm.CRC32, "NSRBwg=="), Arguments.of(Algorithm.SHA1, "qZk+NkcGgWq6PiVxeFDCbJzQ2J0="), Arguments.of(Algorithm.SHA256, "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndTestMarkReset") void validateMarkAndResetForAlgorithm(Algorithm algorithm, String expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update("ab".getBytes(StandardCharsets.UTF_8)); sdkChecksum.mark(3); sdkChecksum.update("xyz".getBytes(StandardCharsets.UTF_8)); sdkChecksum.reset(); sdkChecksum.update("c".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()); assertThat(toBase64).isEqualTo(expectedValue); } private static Stream<Arguments> provideAlgorithmAndTestMarkNoReset() { return Stream.of( Arguments.of(Algorithm.CRC32C, "crUfeA=="), Arguments.of(Algorithm.CRC32, "i9aeUg=="), Arguments.of(Algorithm.SHA1, "e1AsOh9IyGCa4hLN+2Od7jlnP14="), Arguments.of(Algorithm.SHA256, "ZOyIygCyaOW6GjVnihtTFtIS9PNmskdyMlNKiuyjfzw=") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndTestMarkNoReset") void validateMarkForMarkNoReset(Algorithm algorithm, String expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update("Hello ".getBytes(StandardCharsets.UTF_8)); sdkChecksum.mark(3); sdkChecksum.update("world".getBytes(StandardCharsets.UTF_8)); String toBase64 = BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()); assertThat(toBase64).isEqualTo(expectedValue); } private static Stream<Arguments> provideAlgorithmAndIntChecksums() { return Stream.of( Arguments.of(Algorithm.CRC32, "MtcGkw=="), Arguments.of(Algorithm.SHA256, "AbpHGcgLb+kRsJGnwFEktk7uzpZOCcBY74+YBdrKVGs="), Arguments.of(Algorithm.CRC32C, "OZ97aQ=="), Arguments.of(Algorithm.SHA1, "rcg7GeeTSRscbqD9i0bNnzLlkvw=") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndIntChecksums") void validateChecksumWithIntAsInput(Algorithm algorithm, String expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update(10); assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue); } private static Stream<Arguments> provide_SHA_AlgorithmAndExpectedException() { return Stream.of( Arguments.of(Algorithm.SHA256), Arguments.of(Algorithm.SHA1) ); } @ParameterizedTest @MethodSource("provide_SHA_AlgorithmAndExpectedException") void validateShaChecksumWithIntAsInput(Algorithm algorithm) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update(10); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> sdkChecksum.getValue()); } private static Stream<Arguments> provide_CRC_AlgorithmAndExpectedValues() { return Stream.of( Arguments.of(Algorithm.CRC32, 852952723L), Arguments.of(Algorithm.CRC32C, 966753129L) ); } @ParameterizedTest @MethodSource("provide_CRC_AlgorithmAndExpectedValues") void validateCrcChecksumWithIntAsInput(Algorithm algorithm, long expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update(10); assertThat(sdkChecksum.getValue()).isEqualTo(expectedValue); } private static Stream<Arguments> provideAlgorithmAndResetWithNoMark() { return Stream.of( Arguments.of(Algorithm.CRC32C, "AAAAAA=="), Arguments.of(Algorithm.CRC32, "AAAAAA=="), Arguments.of(Algorithm.SHA1, "2jmj7l5rSw0yVb/vlWAYkK/YBwk="), Arguments.of(Algorithm.SHA256, "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=") ); } @ParameterizedTest @MethodSource("provideAlgorithmAndResetWithNoMark") void validateChecksumWithResetAndNoMark(Algorithm algorithm, String expectedValue) { SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm); sdkChecksum.update("abc".getBytes(StandardCharsets.UTF_8)); sdkChecksum.reset(); assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedValue); } private String getAsString(byte[] checksumBytes) { return String.format("%040x", new BigInteger(1, checksumBytes)); } }
1,744
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/exception/SdkExceptionMessageTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.exception; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; /** * Verifies the ways in which a message in an {@link SdkException} can be populated. */ public class SdkExceptionMessageTest { @Test public void noMessage_noCause_implies_noMessage() { assertThat(SdkException.builder().build().getMessage()).isEqualTo(null); } @Test public void message_noCause_implies_messageFromMessage() { assertThat(SdkException.builder().message("foo").build().getMessage()).isEqualTo("foo"); } @Test public void message_cause_implies_messageFromMessage() { assertThat(SdkException.builder().message("foo").cause(new Exception("bar")).build().getMessage()).isEqualTo("foo"); } @Test public void noMessage_causeWithoutMessage_implies_noMessage() { assertThat(SdkException.builder().cause(new Exception()).build().getMessage()).isEqualTo(null); } @Test public void noMessage_causeWithMessage_implies_messageFromCause() { assertThat(SdkException.builder().cause(new Exception("bar")).build().getMessage()).isEqualTo("bar"); } }
1,745
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/AsyncClientHandlerInterceptorExceptionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.stubbing.Answer; import org.testng.Assert; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.utils.CompletableFutureUtils; import utils.HttpTestUtils; import utils.ValidSdkObjects; /** * Tests to ensure that any failures thrown from calling into the {@link * software.amazon.awssdk.core.interceptor.ExecutionInterceptor}s is reported * through the returned {@link java.util.concurrent.CompletableFuture}. */ @RunWith(Parameterized.class) public class AsyncClientHandlerInterceptorExceptionTest { private final SdkRequest request = mock(SdkRequest.class); private final SdkAsyncHttpClient asyncHttpClient = mock(SdkAsyncHttpClient.class); private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class); private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class); private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class); private final Hook hook; private SdkAsyncClientHandler clientHandler; private ClientExecutionParams<SdkRequest, SdkResponse> executionParams; @Parameterized.Parameters(name = "Interceptor Hook: {0}") public static Collection<Object> data() { return Arrays.asList(Hook.values()); } public AsyncClientHandlerInterceptorExceptionTest(Hook hook) { this.hook = hook; } @Before public void testSetup() throws Exception { executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(hook.interceptor())) .option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.none()) .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .build(); clientHandler = new SdkAsyncClientHandler(config); when(request.overrideConfiguration()).thenReturn(Optional.empty()); when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build()); when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))) .thenReturn(VoidSdkResponse.builder().build()); Answer<CompletableFuture<Void>> prepareRequestAnswer; if (hook != Hook.ON_EXECUTION_FAILURE) { prepareRequestAnswer = invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler(); handler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .build()); handler.onStream(new EmptyPublisher<>()); return CompletableFuture.completedFuture(null); }; } else { prepareRequestAnswer = invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler(); RuntimeException error = new RuntimeException("Something went horribly wrong!"); handler.onError(error); return CompletableFutureUtils.failedFuture(error); }; } when(asyncHttpClient.execute(any(AsyncExecuteRequest.class))) .thenAnswer(prepareRequestAnswer); } @Test public void test() { if (hook != Hook.ON_EXECUTION_FAILURE) { doVerify(() -> clientHandler.execute(executionParams), (t) -> ExceptionUtils.getRootCause(t).getMessage() .equals(hook.name())); } else { // ON_EXECUTION_FAILURE is handled differently because we don't // want an exception thrown from the interceptor to replace the // original exception. doVerify(() -> clientHandler.execute(executionParams), (t) -> { for (; t != null; t = t.getCause()) { if (Hook.ON_EXECUTION_FAILURE.name().equals(t.getMessage())) { return false; } } return true; }); } } private void doVerify(Supplier<CompletableFuture<?>> s, Predicate<Throwable> assertFn) { CompletableFuture<?> cf = s.get(); try { cf.join(); Assert.fail("get() method did not fail as expected."); } catch (Throwable t) { assertTrue(assertFn.test(t)); } } public enum Hook { BEFORE_EXECUTION(new ExecutionInterceptor() { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { throw new RuntimeException(BEFORE_EXECUTION.name()); } }), MODIFY_REQUEST(new ExecutionInterceptor() { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { throw new RuntimeException(MODIFY_REQUEST.name()); } }), BEFORE_MARSHALLING(new ExecutionInterceptor() { @Override public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { throw new RuntimeException(BEFORE_MARSHALLING.name()); } }), AFTER_MARSHALLING(new ExecutionInterceptor() { @Override public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { throw new RuntimeException(AFTER_MARSHALLING.name()); } }), MODIFY_HTTP_REQUEST(new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { throw new RuntimeException(MODIFY_HTTP_REQUEST.name()); } }), BEFORE_TRANSMISSION(new ExecutionInterceptor() { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { throw new RuntimeException(BEFORE_TRANSMISSION.name()); } }), AFTER_TRANSMISSION(new ExecutionInterceptor() { @Override public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { throw new RuntimeException(AFTER_TRANSMISSION.name()); } }), MODIFY_HTTP_RESPONSE(new ExecutionInterceptor() { @Override public SdkHttpFullResponse modifyHttpResponse(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { throw new RuntimeException(MODIFY_HTTP_RESPONSE.name()); } }), BEFORE_UNMARSHALLING(new ExecutionInterceptor() { @Override public void beforeUnmarshalling(Context.BeforeUnmarshalling context, ExecutionAttributes executionAttributes) { throw new RuntimeException(BEFORE_UNMARSHALLING.name()); } }), AFTER_UNMARSHALLING(new ExecutionInterceptor() { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { throw new RuntimeException(AFTER_UNMARSHALLING.name()); } }), MODIFY_RESPONSE(new ExecutionInterceptor() { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { throw new RuntimeException(MODIFY_RESPONSE.name()); } }), AFTER_EXECUTION(new ExecutionInterceptor() { @Override public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) { throw new RuntimeException(AFTER_EXECUTION.name()); } }), ON_EXECUTION_FAILURE(new ExecutionInterceptor() { @Override public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) { throw new RuntimeException(ON_EXECUTION_FAILURE.name()); } }) ; private ExecutionInterceptor interceptor; Hook(ExecutionInterceptor interceptor) { this.interceptor = interceptor; } public ExecutionInterceptor interceptor() { return interceptor; } } }
1,746
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/AsyncClientHandlerExceptionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.fail; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import utils.HttpTestUtils; import utils.ValidSdkObjects; /** * Tests to verify that when exceptions are thrown during various stages of * execution within the handler, they are reported through the returned {@link * java.util.concurrent.CompletableFuture}. * * @see AsyncClientHandlerInterceptorExceptionTest */ public class AsyncClientHandlerExceptionTest { private final SdkRequest request = mock(SdkRequest.class); private final SdkAsyncHttpClient asyncHttpClient = mock(SdkAsyncHttpClient.class); private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class); private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class); private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class); private SdkAsyncClientHandler clientHandler; private ClientExecutionParams<SdkRequest, SdkResponse> executionParams; @BeforeEach public void methodSetup() throws Exception { executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.none()) .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .build(); clientHandler = new SdkAsyncClientHandler(config); when(request.overrideConfiguration()).thenReturn(Optional.empty()); when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build()); when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))) .thenReturn(VoidSdkResponse.builder().build()); when(asyncHttpClient.execute(any(AsyncExecuteRequest.class))).thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler(); handler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .build()); handler.onStream(new EmptyPublisher<>()); return CompletableFuture.completedFuture(null); }); } @Test public void marshallerThrowsReportedThroughFuture() throws Exception { final SdkClientException e = SdkClientException.create("Could not marshall"); when(marshaller.marshall(any(SdkRequest.class))).thenThrow(e); doVerify(() -> clientHandler.execute(executionParams), e); } @Test public void responseHandlerThrowsReportedThroughFuture() throws Exception { final SdkClientException e = SdkClientException.create("Could not handle response"); when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))).thenThrow(e); doVerify(() -> clientHandler.execute(executionParams), e); } @Test public void streamingRequest_marshallingException_shouldInvokeExceptionOccurred() throws Exception { AsyncResponseTransformer asyncResponseTransformer = mock(AsyncResponseTransformer.class); CompletableFuture<?> future = new CompletableFuture<>(); when(asyncResponseTransformer.prepare()).thenReturn(future); SdkClientException exception = SdkClientException.create("Could not handle response"); when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception); doVerify(() -> clientHandler.execute(executionParams, asyncResponseTransformer), exception); verify(asyncResponseTransformer, times(1)).prepare(); verify(asyncResponseTransformer, times(1)).exceptionOccurred(exception); } private void doVerify(Supplier<CompletableFuture<?>> s, final Throwable expectedException) { doVerify(s, (thrown) -> thrown.getCause() == expectedException); } private void doVerify(Supplier<CompletableFuture<?>> s, Predicate<Throwable> assertFn) { CompletableFuture<?> cf = s.get(); try { cf.get(); fail("get() method did not fail as expected."); } catch (Throwable t) { assertTrue(assertFn.test(t)); } } }
1,747
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerTransformerVerificationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.handler; import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.junit.Before; import org.junit.Test; import org.mockito.stubbing.Answer; import org.reactivestreams.Publisher; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.DrainingSubscriber; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import utils.HttpTestUtils; import utils.ValidSdkObjects; /** * Verification tests to ensure that the behavior of {@link SdkAsyncClientHandler} is in line with the * {@link AsyncResponseTransformer} interface. */ public class AsyncClientHandlerTransformerVerificationTest { private static final RetryPolicy RETRY_POLICY = RetryPolicy.defaultRetryPolicy(); private final SdkRequest request = mock(SdkRequest.class); private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class); private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class); private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class); private SdkAsyncHttpClient mockClient; private SdkAsyncClientHandler clientHandler; private ClientExecutionParams<SdkRequest, SdkResponse> executionParams; @Before public void testSetup() throws Exception { mockClient = mock(SdkAsyncHttpClient.class); executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, mockClient) .option(SdkClientOption.RETRY_POLICY, RETRY_POLICY) .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .build(); clientHandler = new SdkAsyncClientHandler(config); when(request.overrideConfiguration()).thenReturn(Optional.empty()); when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build()); when(responseHandler.handle(any(), any())).thenReturn(VoidSdkResponse.builder().build()); } @Test public void marshallerThrowsException_shouldTriggerExceptionOccurred() { SdkClientException exception = SdkClientException.create("Could not handle response"); when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception); AtomicBoolean exceptionOccurred = new AtomicBoolean(false); executeAndWaitError(new TestTransformer<SdkResponse, Void>(){ @Override public void exceptionOccurred(Throwable error) { exceptionOccurred.set(true); super.exceptionOccurred(error); } }); assertThat(exceptionOccurred.get()).isTrue(); } @Test public void nonRetryableErrorDoesNotTriggerRetry() { mockSuccessfulResponse(); AtomicLong prepareCalls = new AtomicLong(0); executeAndWaitError(new TestTransformer<SdkResponse, Void>() { @Override public CompletableFuture<Void> prepare() { prepareCalls.incrementAndGet(); return super.prepare(); } @Override public void onStream(SdkPublisher<ByteBuffer> stream) { super.transformFuture().completeExceptionally(new RuntimeException("some error")); } }); assertThat(prepareCalls.get()).isEqualTo(1L); } @Test public void prepareCallsEqualToExecuteAttempts() { mockSuccessfulResponse(); AtomicLong prepareCalls = new AtomicLong(0); executeAndWaitError(new TestTransformer<SdkResponse, Void>() { @Override public CompletableFuture<Void> prepare() { prepareCalls.incrementAndGet(); return super.prepare(); } @Override public void onStream(SdkPublisher<ByteBuffer> stream) { stream.subscribe(new DrainingSubscriber<ByteBuffer>() { @Override public void onComplete() { transformFuture().completeExceptionally(RetryableException.builder().message("retry me please: " + prepareCalls.get()).build()); } }); } }); assertThat(prepareCalls.get()).isEqualTo(1 + RETRY_POLICY.numRetries()); } @Test//(timeout = 1000L) public void handlerExecutionCompletesIndependentlyOfRequestExecution_CompleteAfterResponse() { mockSuccessfulResponse_NonSignalingStream(); // Since we never signal any elements on the response stream, if the async client handler waited for the stream to // finish before completing the future, this would never return. assertThat(execute(new TestTransformer<SdkResponse, SdkResponse>() { @Override public void onResponse(SdkResponse response) { transformFuture().complete(response); } })).isNotNull(); } @Test(timeout = 1000L) public void handlerExecutionCompletesIndependentlyOfRequestExecution_CompleteAfterStream() { mockSuccessfulResponse_NonSignalingStream(); // Since we never signal any elements on the response stream, if the async client handler waited for the stream to // finish before completing the future, this would never return. assertThat(execute(new TestTransformer<SdkResponse, Publisher<ByteBuffer>>() { @Override public void onStream(SdkPublisher<ByteBuffer> stream) { transformFuture().complete(stream); } })).isNotNull(); } private void mockSuccessfulResponse() { Answer<CompletableFuture<Void>> executeAnswer = invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler(); handler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .build()); handler.onStream(new EmptyPublisher<>()); return CompletableFuture.completedFuture(null); }; reset(mockClient); when(mockClient.execute(any(AsyncExecuteRequest.class))).thenAnswer(executeAnswer); } /** * Mock a response with success status (200), but with a stream that never signals anything on the Subscriber. This * roughly emulates a very slow response. */ private void mockSuccessfulResponse_NonSignalingStream() { Answer<CompletableFuture<Void>> executeAnswer = invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgument(0, AsyncExecuteRequest.class).responseHandler(); handler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .build()); handler.onStream(subscriber -> { // never signal onSubscribe }); return CompletableFuture.completedFuture(null); }; reset(mockClient); when(mockClient.execute(any())).thenAnswer(executeAnswer); } private void executeAndWaitError(AsyncResponseTransformer<SdkResponse, ?> transformer) { try { execute(transformer); fail("Client execution should have completed exceptionally"); } catch (CompletionException e) { // ignored } } private <ResultT> ResultT execute(AsyncResponseTransformer<SdkResponse, ResultT> transformer) { return clientHandler.execute(executionParams, transformer).join(); } private static class TestTransformer<ResponseT, ResultT> implements AsyncResponseTransformer<ResponseT, ResultT> { private volatile CompletableFuture<ResultT> transformFuture; @Override public CompletableFuture<ResultT> prepare() { this.transformFuture = new CompletableFuture<>(); return transformFuture; } @Override public void onResponse(ResponseT response) { } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { publisher.subscribe(new DrainingSubscriber<ByteBuffer>() { @Override public void onComplete() { transformFuture.complete(null); } }); } @Override public void exceptionOccurred(Throwable error) { transformFuture.completeExceptionally(error); } CompletableFuture<ResultT> transformFuture() { return transformFuture; } } }
1,748
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/SyncClientHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.handler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.AbortedException; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpResponse; import utils.HttpTestUtils; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class SyncClientHandlerTest { private SdkSyncClientHandler syncClientHandler; @Mock private SdkRequest request; @Mock private Marshaller<SdkRequest> marshaller; private SdkHttpFullRequest marshalledRequest = ValidSdkObjects.sdkHttpFullRequest().build(); @Mock private SdkHttpClient httpClient; @Mock private ExecutableHttpRequest httpClientCall; @Mock private HttpResponseHandler<SdkResponse> responseHandler; @Mock private HttpResponseHandler<SdkServiceException> errorResponseHandler; @Mock private ResponseTransformer<SdkResponse, ?> responseTransformer; @Before public void setup() { this.syncClientHandler = new SdkSyncClientHandler(clientConfiguration()); when(request.overrideConfiguration()).thenReturn(Optional.empty()); } @Test public void successfulExecutionCallsResponseHandler() throws Exception { SdkResponse expected = VoidSdkResponse.builder().build(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); // Given expectRetrievalFromMocks(); when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .headers(headers) .build()) .build()); // Successful HTTP call when(responseHandler.handle(any(), any())).thenReturn(expected); // Response handler call // When SdkResponse actual = syncClientHandler.execute(clientExecutionParams()); // Then verifyNoMoreInteractions(errorResponseHandler); // No error handler calls assertThat(actual.sdkHttpResponse().statusCode()).isEqualTo(200); assertThat(actual.sdkHttpResponse().headers()).isEqualTo(headers); } @Test public void failedExecutionCallsErrorResponseHandler() throws Exception { SdkServiceException exception = SdkServiceException.builder().message("Uh oh!").statusCode(500).build(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); // Given expectRetrievalFromMocks(); when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(500) .headers(headers) .build()) .build()); // Failed HTTP call when(errorResponseHandler.handle(any(), any())).thenReturn(exception); // Error response handler call // When assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams())).isEqualToComparingFieldByField(exception); // Then verifyNoMoreInteractions(responseHandler); // No response handler calls } @Test public void responseTransformerThrowsRetryableException_shouldPropogate() throws Exception { mockSuccessfulApiCall(); when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow( RetryableException.create("test")); assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer)) .isInstanceOf(RetryableException.class); } @Test public void responseTransformerThrowsInterruptedException_shouldPropagate() throws Exception { try { verifyResponseTransformerPropagateException(new InterruptedException()); } finally { Thread.interrupted(); } } @Test public void responseTransformerThrowsAbortedException_shouldPropagate() throws Exception { verifyResponseTransformerPropagateException(AbortedException.create("")); } @Test public void responseTransformerThrowsOtherException_shouldWrapWithNonRetryableException() throws Exception { mockSuccessfulApiCall(); when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow( new RuntimeException()); assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer)) .hasCauseInstanceOf(NonRetryableException.class); } private void verifyResponseTransformerPropagateException(Exception exception) throws Exception { mockSuccessfulApiCall(); when(responseTransformer.transform(any(SdkResponse.class), any(AbortableInputStream.class))).thenThrow( exception); assertThatThrownBy(() -> syncClientHandler.execute(clientExecutionParams(), responseTransformer)) .hasCauseInstanceOf(exception.getClass()); } private void mockSuccessfulApiCall() throws Exception { expectRetrievalFromMocks(); when(httpClientCall.call()).thenReturn(HttpExecuteResponse.builder() .responseBody(AbortableInputStream.create(new ByteArrayInputStream("TEST".getBytes()))) .response(SdkHttpResponse.builder().statusCode(200).build()) .build()); when(responseHandler.handle(any(), any())).thenReturn(VoidSdkResponse.builder().build()); } private void expectRetrievalFromMocks() { when(marshaller.marshall(request)).thenReturn(marshalledRequest); when(httpClient.prepareRequest(any())).thenReturn(httpClientCall); } private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); } public SdkClientConfiguration clientConfiguration() { return HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, httpClient) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.none()) .build(); } }
1,749
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.handler; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import org.junit.Before; 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.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import utils.HttpTestUtils; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class AsyncClientHandlerTest { private SdkAsyncClientHandler asyncClientHandler; @Mock private SdkRequest request; @Mock private Marshaller<SdkRequest> marshaller; private SdkHttpFullRequest marshalledRequest = ValidSdkObjects.sdkHttpFullRequest().build(); @Mock private SdkAsyncHttpClient httpClient; private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null); @Mock private HttpResponseHandler<SdkResponse> responseHandler; @Mock private HttpResponseHandler<SdkServiceException> errorResponseHandler; @Before public void setup() { this.asyncClientHandler = new SdkAsyncClientHandler(clientConfiguration()); when(request.overrideConfiguration()).thenReturn(Optional.empty()); } @Test public void successfulExecutionCallsResponseHandler() throws Exception { // Given SdkResponse expected = VoidSdkResponse.builder().build(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); ArgumentCaptor<AsyncExecuteRequest> executeRequest = ArgumentCaptor.forClass(AsyncExecuteRequest.class); expectRetrievalFromMocks(); when(httpClient.execute(executeRequest.capture())).thenReturn(httpClientFuture); when(responseHandler.handle(any(), any())).thenReturn(expected); // Response handler call // When CompletableFuture<SdkResponse> responseFuture = asyncClientHandler.execute(clientExecutionParams()); SdkAsyncHttpResponseHandler capturedHandler = executeRequest.getValue().responseHandler(); capturedHandler.onHeaders(SdkHttpFullResponse.builder().statusCode(200) .headers(headers).build()); capturedHandler.onStream(new EmptyPublisher<>()); SdkResponse actualResponse = responseFuture.get(1, TimeUnit.SECONDS); // Then verifyNoMoreInteractions(errorResponseHandler); // No error handler calls assertThat(actualResponse.sdkHttpResponse().statusCode()).isEqualTo(200); assertThat(actualResponse.sdkHttpResponse().headers()).isEqualTo(headers); } @Test public void failedExecutionCallsErrorResponseHandler() throws Exception { SdkServiceException exception = SdkServiceException.builder().message("Uh oh!").statusCode(500).build(); // Given ArgumentCaptor<AsyncExecuteRequest> executeRequest = ArgumentCaptor.forClass(AsyncExecuteRequest.class); expectRetrievalFromMocks(); when(httpClient.execute(executeRequest.capture())).thenReturn(httpClientFuture); when(errorResponseHandler.handle(any(), any())).thenReturn(exception); // Error response handler call // When CompletableFuture<SdkResponse> responseFuture = asyncClientHandler.execute(clientExecutionParams()); SdkAsyncHttpResponseHandler capturedHandler = executeRequest.getValue().responseHandler(); capturedHandler.onHeaders(SdkHttpFullResponse.builder().statusCode(500).build()); capturedHandler.onStream(new EmptyPublisher<>()); assertThatThrownBy(() -> responseFuture.get(1, TimeUnit.SECONDS)).hasCause(exception); // Then verifyNoMoreInteractions(responseHandler); // Response handler is not called } private void expectRetrievalFromMocks() { when(marshaller.marshall(request)).thenReturn(marshalledRequest); } private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); } public SdkClientConfiguration clientConfiguration() { return HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, httpClient) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.none()) .build(); } }
1,750
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/ClientHandlerSignerValidationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.handler; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import utils.HttpTestUtils; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class ClientHandlerSignerValidationTest { private final SdkRequest request = ValidSdkObjects.sdkRequest(); @Mock private Marshaller<SdkRequest> marshaller; @Mock private SdkHttpClient httpClient; @Mock private Signer signer; @Mock private HttpResponseHandler<SdkResponse> responseHandler; private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null); @Mock private ExecutableHttpRequest httpClientCall; @Before public void setup() throws Exception { when(httpClient.prepareRequest(any(HttpExecuteRequest.class))).thenReturn(httpClientCall); when(httpClientCall.call()).thenReturn( HttpExecuteResponse.builder() .response(SdkHttpFullResponse.builder() .statusCode(200) .build()) .build()); when(signer.credentialType()).thenReturn(CredentialType.TOKEN); SdkResponse mockSdkResponse = VoidSdkResponse.builder().build(); when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse); } @Test public void execute_requestHasHttpEndpoint_usesBearerAuth_fails() { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); SdkClientConfiguration config = testClientConfiguration(); SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config); assertThatThrownBy(() -> sdkSyncClientHandler.execute(executionParams())) .isInstanceOf(SdkClientException.class) .hasMessageContaining("plaintext HTTP endpoint"); } @Test public void execute_interceptorChangesToHttp_usesBearerAuth_fails() { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); ExecutionInterceptor interceptor = new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest() .toBuilder() .protocol("http") .build(); } }; SdkClientConfiguration config = testClientConfiguration() .toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor)) .build(); SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config); assertThatThrownBy(() -> sdkSyncClientHandler.execute(executionParams())) .isInstanceOf(SdkClientException.class) .hasMessageContaining("plaintext HTTP endpoint"); } @Test public void execute_interceptorChangesToHttps_usesBearerAuth_succeeds() { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.sign(any(), any())).thenReturn(httpRequest); ExecutionInterceptor interceptor = new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest() .toBuilder() .protocol("https") .build(); } }; SdkClientConfiguration config = testClientConfiguration() .toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor)) .build(); SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(config); assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams())); } @Test public void execute_requestHasHttpsEndpoint_usesBearerAuth_succeeds(){ SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.sign(any(), any())).thenReturn(httpRequest); SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(testClientConfiguration()); assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams())); } @Test public void execute_requestHasHttpEndpoint_doesNotBearerAuth_succeeds(){ SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.sign(any(), any())).thenReturn(httpRequest); when(signer.credentialType()).thenReturn(CredentialType.of("AWS")); SdkSyncClientHandler sdkSyncClientHandler = new SdkSyncClientHandler(testClientConfiguration()); assertThatNoException().isThrownBy(() -> sdkSyncClientHandler.execute(executionParams())); } private ClientExecutionParams<SdkRequest, SdkResponse> executionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler); } private SdkClientConfiguration testClientConfiguration() { return HttpTestUtils.testClientConfiguration() .toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, httpClient) .option(SdkAdvancedClientOption.SIGNER, signer) .build(); } }
1,751
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/handler/AsyncClientHandlerSignerValidationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.handler; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.junit.Before; 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.core.CredentialType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import utils.HttpTestUtils; import utils.ValidSdkObjects; @RunWith(MockitoJUnitRunner.class) public class AsyncClientHandlerSignerValidationTest { private final SdkRequest request = ValidSdkObjects.sdkRequest(); @Mock private Marshaller<SdkRequest> marshaller; @Mock private SdkAsyncHttpClient httpClient; @Mock private Signer signer; @Mock private HttpResponseHandler<SdkResponse> responseHandler; private CompletableFuture<Void> httpClientFuture = CompletableFuture.completedFuture(null); private ArgumentCaptor<AsyncExecuteRequest> executeRequestCaptor = ArgumentCaptor.forClass(AsyncExecuteRequest.class); @Before public void setup() { when(httpClient.execute(executeRequestCaptor.capture())).thenReturn(httpClientFuture); when(signer.credentialType()).thenReturn(CredentialType.TOKEN); } @Test public void execute_requestHasHttpEndpoint_usesBearerAuth_fails() { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); SdkClientConfiguration config = testClientConfiguration(); SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config); CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams()); assertThatThrownBy(execute::get) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("plaintext HTTP endpoint"); } @Test public void execute_interceptorChangesToHttp_usesBearerAuth_fails() { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); ExecutionInterceptor interceptor = new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest() .toBuilder() .protocol("http") .build(); } }; SdkClientConfiguration config = testClientConfiguration() .toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor)) .build(); SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config); CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams()); assertThatThrownBy(execute::get) .hasCauseInstanceOf(SdkClientException.class) .hasMessageContaining("plaintext HTTP endpoint"); } @Test public void execute_interceptorChangesToHttps_usesBearerAuth_succeeds() throws Exception { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.sign(any(), any())).thenReturn(httpRequest); SdkResponse mockSdkResponse = VoidSdkResponse.builder().build(); when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse); ExecutionInterceptor interceptor = new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { return context.httpRequest() .toBuilder() .protocol("https") .build(); } }; SdkClientConfiguration config = testClientConfiguration() .toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, Collections.singletonList(interceptor)) .build(); SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(config); CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams()); SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); capturedHandler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .headers(headers) .build()); capturedHandler.onStream(new EmptyPublisher<>()); assertThatNoException().isThrownBy(execute::get); } @Test public void execute_requestHasHttpsEndpoint_usesBearerAuth_succeeds() throws Exception { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("https").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.sign(any(), any())).thenReturn(httpRequest); SdkResponse mockSdkResponse = VoidSdkResponse.builder().build(); when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse); SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(testClientConfiguration()); CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams()); SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); capturedHandler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .headers(headers) .build()); capturedHandler.onStream(new EmptyPublisher<>()); assertThatNoException().isThrownBy(execute::get); } @Test public void execute_requestHasHttpEndpoint_doesNotBearerAuth_succeeds() throws Exception { SdkHttpFullRequest httpRequest = ValidSdkObjects.sdkHttpFullRequest().protocol("http").build(); when(marshaller.marshall(any(SdkRequest.class))).thenReturn(httpRequest); when(signer.credentialType()).thenReturn(CredentialType.of("AWS")); when(signer.sign(any(), any())).thenReturn(httpRequest); SdkResponse mockSdkResponse = VoidSdkResponse.builder().build(); when(responseHandler.handle(any(), any())).thenReturn(mockSdkResponse); SdkAsyncClientHandler sdkAsyncClientHandler = new SdkAsyncClientHandler(testClientConfiguration()); CompletableFuture<SdkResponse> execute = sdkAsyncClientHandler.execute(executionParams()); SdkAsyncHttpResponseHandler capturedHandler = executeRequestCaptor.getValue().responseHandler(); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", Arrays.asList("bar")); capturedHandler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .headers(headers) .build()); capturedHandler.onStream(new EmptyPublisher<>()); assertThatNoException().isThrownBy(execute::get); } private ClientExecutionParams<SdkRequest, SdkResponse> executionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler); } private SdkClientConfiguration testClientConfiguration() { return HttpTestUtils.testClientConfiguration() .toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, httpClient) .option(SdkAdvancedClientOption.SIGNER, signer) .build(); } }
1,752
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/ClientOverrideConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.config; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.junit.jupiter.api.Test; 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.internal.http.request.SlowExecutionInterceptor; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.utils.ImmutableMap; public class ClientOverrideConfigurationTest { private static final ConcurrentMap<String, ExecutionAttribute<Object>> ATTR_POOL = new ConcurrentHashMap<>(); private static ExecutionAttribute<Object> attr(String name) { name = ClientOverrideConfigurationTest.class.getName() + ":" + name; return ATTR_POOL.computeIfAbsent(name, ExecutionAttribute::new); } @Test public void addingSameItemTwice_shouldOverride() { ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder() .putHeader("value", "foo") .putHeader("value", "bar") .putAdvancedOption(SdkAdvancedClientOption .USER_AGENT_SUFFIX, "foo") .putAdvancedOption(SdkAdvancedClientOption .USER_AGENT_SUFFIX, "bar") .build(); assertThat(configuration.headers().get("value")).containsExactly("bar"); assertThat(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX).get()).isEqualTo("bar"); ClientOverrideConfiguration anotherConfig = configuration.toBuilder().putHeader("value", "foobar").build(); assertThat(anotherConfig.headers().get("value")).containsExactly("foobar"); } @Test public void settingCollection_shouldOverrideAddItem() { ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder() .putHeader("value", "foo") .headers(ImmutableMap.of("value", Arrays.asList ("hello", "world"))) .putAdvancedOption(SdkAdvancedClientOption .USER_AGENT_SUFFIX, "test") .advancedOptions(new HashMap<>()) .putAdvancedOption(SdkAdvancedClientOption .USER_AGENT_PREFIX, "test") .addExecutionInterceptor(new SlowExecutionInterceptor()) .executionInterceptors(new ArrayList<>()) .build(); assertThat(configuration.headers().get("value")).containsExactly("hello", "world"); assertFalse(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_SUFFIX).isPresent()); assertThat(configuration.advancedOption(SdkAdvancedClientOption.USER_AGENT_PREFIX).get()).isEqualTo("test"); assertTrue(configuration.executionInterceptors().isEmpty()); } @Test public void addSameItemAfterSetCollection_shouldOverride() { ImmutableMap<String, List<String>> map = ImmutableMap.of("value", Arrays.asList("hello", "world")); ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder() .headers(map) .putHeader("value", "blah") .build(); assertThat(configuration.headers().get("value")).containsExactly("blah"); } @Test public void shouldGuaranteeImmutability() { List<String> headerValues = new ArrayList<>(); headerValues.add("bar"); Map<String, List<String>> headers = new HashMap<>(); headers.put("foo", headerValues); List<ExecutionInterceptor> executionInterceptors = new ArrayList<>(); SlowExecutionInterceptor slowExecutionInterceptor = new SlowExecutionInterceptor(); executionInterceptors.add(slowExecutionInterceptor); ClientOverrideConfiguration.Builder configurationBuilder = ClientOverrideConfiguration.builder().executionInterceptors(executionInterceptors) .headers(headers); headerValues.add("test"); headers.put("new header", Collections.singletonList("new value")); executionInterceptors.clear(); assertThat(configurationBuilder.headers().size()).isEqualTo(1); assertThat(configurationBuilder.headers().get("foo")).containsExactly("bar"); assertThat(configurationBuilder.executionInterceptors()).containsExactly(slowExecutionInterceptor); } @Test public void metricPublishers_createsCopy() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); List<MetricPublisher> toModify = new ArrayList<>(publishers); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .metricPublishers(toModify) .build(); toModify.clear(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_maintainsAllAdded() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); publishers.forEach(builder::addMetricPublisher); ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void metricPublishers_overwritesPreviouslyAdded() { MetricPublisher firstAdded = mock(MetricPublisher.class); List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); builder.addMetricPublisher(firstAdded); builder.metricPublishers(publishers); ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).isEqualTo(publishers); } @Test public void addMetricPublisher_listPreviouslyAdded_appendedToList() { List<MetricPublisher> publishers = new ArrayList<>(); publishers.add(mock(MetricPublisher.class)); publishers.add(mock(MetricPublisher.class)); MetricPublisher thirdAdded = mock(MetricPublisher.class); ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); builder.metricPublishers(publishers); builder.addMetricPublisher(thirdAdded); ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.metricPublishers()).containsExactly(publishers.get(0), publishers.get(1), thirdAdded); } @Test public void executionAttributes_createsCopy() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); executionAttributes.putAttribute(testAttribute, "Value2"); assertThat(overrideConfig.executionAttributes().getAttribute(testAttribute)).isEqualTo(expectedValue); } @Test public void executionAttributes_isImmutable() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); ExecutionAttribute testAttribute = attr("TestAttribute"); String expectedValue = "Value1"; executionAttributes.putAttribute(testAttribute, expectedValue); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .executionAttributes(executionAttributes) .build(); try { overrideConfig.executionAttributes().putAttribute(testAttribute, 2); fail("Expected unsupported operation exception"); } catch(Exception ex) { assertThat(ex instanceof UnsupportedOperationException).isTrue(); } } @Test public void executionAttributes_maintainsAllAdded() { Map<ExecutionAttribute, Object> executionAttributeObjectMap = new HashMap<>(); for (int i = 0; i < 5; i++) { executionAttributeObjectMap.put(attr("Attribute" + i), mock(Object.class)); } ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); for (Map.Entry<ExecutionAttribute, Object> attributeObjectEntry : executionAttributeObjectMap.entrySet()) { builder.putExecutionAttribute(attributeObjectEntry.getKey(), attributeObjectEntry.getValue()); } ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributeObjectMap); } @Test public void executionAttributes_overwritesPreviouslyAdded() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); builder.putExecutionAttribute(attr("AddedAttribute"), mock(Object.class)); builder.executionAttributes(executionAttributes); ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes()); } @Test public void executionAttributes_listPreviouslyAdded_appendedToList() { ExecutionAttributes executionAttributes = new ExecutionAttributes(); for (int i = 0; i < 5; i++) { executionAttributes.putAttribute(attr("Attribute" + i), mock(Object.class)); } ClientOverrideConfiguration.Builder builder = ClientOverrideConfiguration.builder(); builder.executionAttributes(executionAttributes); ExecutionAttribute addedAttribute = attr("AddedAttribute"); Object addedValue = mock(Object.class); builder.putExecutionAttribute(addedAttribute, addedValue); ClientOverrideConfiguration overrideConfig = builder.build(); assertThat(overrideConfig.executionAttributes().getAttribute(addedAttribute)).isEqualTo(addedValue); } }
1,753
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/SdkClientConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.config; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.utils.AttributeMap; public class SdkClientConfigurationTest { @Test public void equalsHashcode() { AttributeMap one = AttributeMap.empty(); AttributeMap two = AttributeMap.builder().put(SdkClientOption.CLIENT_TYPE, ClientType.SYNC).build(); EqualsVerifier.forClass(SdkClientConfiguration.class) .withNonnullFields("attributes") .withPrefabValues(AttributeMap.class, one, two) .verify(); } }
1,754
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/config/ConfigurationBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.config; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; /** * Validate the functionality of the Client*Configuration classes */ public class ConfigurationBuilderTest { @Test public void overrideConfigurationClassHasExpectedMethods() throws Exception { assertConfigurationClassIsValid(ClientOverrideConfiguration.class); } private void assertConfigurationClassIsValid(Class<?> configurationClass) throws Exception { // Builders should be instantiable from the configuration class Method createBuilderMethod = configurationClass.getMethod("builder"); Object builder = createBuilderMethod.invoke(null); // Builders should implement the configuration class's builder interface Class<?> builderInterface = Class.forName(configurationClass.getName() + "$Builder"); assertThat(builder).isInstanceOf(builderInterface); Class<?> builderClass = builder.getClass(); Method[] builderMethods = builderClass.getDeclaredMethods(); // Builder's build methods should return the configuration object Optional<Method> buildMethod = Arrays.stream(builderMethods).filter(m -> m.getName().equals("build")).findFirst(); assertThat(buildMethod).isPresent(); Object builtObject = buildMethod.get().invoke(builder); assertThat(builtObject).isInstanceOf(configurationClass); // Analyze the builder for compliance with the bean specification BeanInfo builderBeanInfo = Introspector.getBeanInfo(builderClass); Map<String, PropertyDescriptor> builderProperties = Arrays.stream(builderBeanInfo.getPropertyDescriptors()) .collect(toMap(PropertyDescriptor::getName, p -> p)); // Validate method names for (Field field : configurationClass.getFields()) { // Ignore generated fields (eg. by Jacoco) if (field.isSynthetic()) { continue; } String builderPropertyName = builderClass.getSimpleName() + "'s " + field.getName() + " property"; PropertyDescriptor builderProperty = builderProperties.get(field.getName()); // Builders should have a bean-style write method for each field assertThat(builderProperty).as(builderPropertyName).isNotNull(); assertThat(builderProperty.getReadMethod()).as(builderPropertyName + "'s read method").isNull(); assertThat(builderProperty.getWriteMethod()).as(builderPropertyName + "'s write method").isNotNull(); // Builders should have a fluent write method for each field Arrays.stream(builderMethods) .filter(builderMethod -> matchesSignature(field.getName(), builderProperty, builderMethod)) .findAny() .orElseThrow(() -> new AssertionError(builderClass + " can't write " + field.getName())); } } private boolean matchesSignature(String methodName, PropertyDescriptor property, Method builderMethod) { return builderMethod.getName().equals(methodName) && builderMethod.getParameters().length == 1 && builderMethod.getParameters()[0].getType().equals(property.getPropertyType()); } }
1,755
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/client/builder/DefaultClientBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.client.builder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_PREFIX; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.USER_AGENT_SUFFIX; import static software.amazon.awssdk.core.client.config.SdkClientOption.ADDITIONAL_HTTP_HEADERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_ATTEMPT_TIMEOUT; import static software.amazon.awssdk.core.client.config.SdkClientOption.API_CALL_TIMEOUT; import static software.amazon.awssdk.core.client.config.SdkClientOption.ENDPOINT_OVERRIDDEN; import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_ATTRIBUTES; import static software.amazon.awssdk.core.client.config.SdkClientOption.EXECUTION_INTERCEPTORS; import static software.amazon.awssdk.core.client.config.SdkClientOption.METRIC_PUBLISHERS; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_FILE_SUPPLIER; import static software.amazon.awssdk.core.client.config.SdkClientOption.PROFILE_NAME; import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY; import static software.amazon.awssdk.core.client.config.SdkClientOption.SCHEDULED_EXECUTOR_SERVICE; import static software.amazon.awssdk.core.internal.SdkInternalTestAdvancedClientOption.ENDPOINT_OVERRIDDEN_OVERRIDE; import com.google.common.collect.ImmutableSet; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Supplier; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; 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.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.StringInputStream; /** * Validate the functionality of the {@link SdkDefaultClientBuilder}. */ @RunWith(MockitoJUnitRunner.class) public class DefaultClientBuilderTest { private static final AttributeMap MOCK_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "prefix"; private static final URI DEFAULT_ENDPOINT = URI.create("https://defaultendpoint.com"); private static final URI ENDPOINT = URI.create("https://example.com"); private static final NoOpSigner TEST_SIGNER = new NoOpSigner(); @Mock private SdkHttpClient.Builder defaultHttpClientFactory; @Mock private SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory; @Before public void setup() { when(defaultHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class)); when(defaultAsyncHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkAsyncHttpClient.class)); } @Test public void overrideConfigurationIsNeverNull() { ClientOverrideConfiguration config = testClientBuilder().overrideConfiguration(); assertThat(config).isNotNull(); config = testClientBuilder().overrideConfiguration((ClientOverrideConfiguration) null).overrideConfiguration(); assertThat(config).isNotNull(); } @Test public void overrideConfigurationReturnsSetValues() { List<ExecutionInterceptor> interceptors = new ArrayList<>(); RetryPolicy retryPolicy = RetryPolicy.builder().build(); Map<String, List<String>> headers = new HashMap<>(); List<MetricPublisher> metricPublishers = new ArrayList<>(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); Signer signer = (request, execAttributes) -> request; String suffix = "suffix"; String prefix = "prefix"; Duration apiCallTimeout = Duration.ofMillis(42); Duration apiCallAttemptTimeout = Duration.ofMillis(43); ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build(); Supplier<ProfileFile> profileFileSupplier = () -> profileFile; String profileName = "name"; ScheduledExecutorService scheduledExecutorService = mock(ScheduledExecutorService.class); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .executionInterceptors(interceptors) .retryPolicy(retryPolicy) .headers(headers) .putAdvancedOption(SIGNER, signer) .putAdvancedOption(USER_AGENT_SUFFIX, suffix) .putAdvancedOption(USER_AGENT_PREFIX, prefix) .apiCallTimeout(apiCallTimeout) .apiCallAttemptTimeout(apiCallAttemptTimeout) .putAdvancedOption(DISABLE_HOST_PREFIX_INJECTION, Boolean.TRUE) .defaultProfileFileSupplier(profileFileSupplier) .defaultProfileName(profileName) .metricPublishers(metricPublishers) .executionAttributes(executionAttributes) .putAdvancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE, Boolean.TRUE) .scheduledExecutorService(scheduledExecutorService) .build(); TestClientBuilder builder = testClientBuilder().overrideConfiguration(overrideConfig); ClientOverrideConfiguration builderOverrideConfig = builder.overrideConfiguration(); assertThat(builderOverrideConfig.executionInterceptors()).isEqualTo(interceptors); assertThat(builderOverrideConfig.retryPolicy()).isEqualTo(Optional.of(retryPolicy)); assertThat(builderOverrideConfig.headers()).isEqualTo(headers); assertThat(builderOverrideConfig.advancedOption(SIGNER)).isEqualTo(Optional.of(signer)); assertThat(builderOverrideConfig.advancedOption(USER_AGENT_SUFFIX)).isEqualTo(Optional.of(suffix)); assertThat(builderOverrideConfig.apiCallTimeout()).isEqualTo(Optional.of(apiCallTimeout)); assertThat(builderOverrideConfig.apiCallAttemptTimeout()).isEqualTo(Optional.of(apiCallAttemptTimeout)); assertThat(builderOverrideConfig.advancedOption(DISABLE_HOST_PREFIX_INJECTION)).isEqualTo(Optional.of(Boolean.TRUE)); assertThat(builderOverrideConfig.defaultProfileFileSupplier()).hasValue(profileFileSupplier); assertThat(builderOverrideConfig.defaultProfileFile()).isEqualTo(Optional.of(profileFile)); assertThat(builderOverrideConfig.defaultProfileName()).isEqualTo(Optional.of(profileName)); assertThat(builderOverrideConfig.metricPublishers()).isEqualTo(metricPublishers); assertThat(builderOverrideConfig.executionAttributes().getAttributes()).isEqualTo(executionAttributes.getAttributes()); assertThat(builderOverrideConfig.advancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE)).isEqualTo(Optional.of(Boolean.TRUE)); Runnable runnable = () -> { }; builderOverrideConfig.scheduledExecutorService().get().submit(runnable); verify(scheduledExecutorService).submit(runnable); } @Test public void overrideConfigurationOmitsUnsetValues() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .build(); TestClientBuilder builder = testClientBuilder().overrideConfiguration(overrideConfig); ClientOverrideConfiguration builderOverrideConfig = builder.overrideConfiguration(); assertThat(builderOverrideConfig.executionInterceptors()).isEmpty(); assertThat(builderOverrideConfig.retryPolicy()).isEmpty(); assertThat(builderOverrideConfig.headers()).isEmpty(); assertThat(builderOverrideConfig.advancedOption(SIGNER)).isEmpty(); assertThat(builderOverrideConfig.advancedOption(USER_AGENT_SUFFIX)).isEmpty(); assertThat(builderOverrideConfig.apiCallTimeout()).isEmpty(); assertThat(builderOverrideConfig.apiCallAttemptTimeout()).isEmpty(); assertThat(builderOverrideConfig.advancedOption(DISABLE_HOST_PREFIX_INJECTION)).isEmpty(); assertThat(builderOverrideConfig.defaultProfileFileSupplier()).isEmpty(); assertThat(builderOverrideConfig.defaultProfileFile()).isEmpty(); assertThat(builderOverrideConfig.defaultProfileName()).isEmpty(); assertThat(builderOverrideConfig.metricPublishers()).isEmpty(); assertThat(builderOverrideConfig.executionAttributes().getAttributes()).isEmpty(); assertThat(builderOverrideConfig.advancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE)).isEmpty(); assertThat(builderOverrideConfig.scheduledExecutorService()).isEmpty(); } @Test public void buildIncludesClientOverrides() { List<ExecutionInterceptor> interceptors = new ArrayList<>(); ExecutionInterceptor interceptor = new ExecutionInterceptor() {}; interceptors.add(interceptor); RetryPolicy retryPolicy = RetryPolicy.builder().build(); ScheduledExecutorService scheduledExecutorService = Mockito.spy(Executors.newScheduledThreadPool(1)); Map<String, List<String>> headers = new HashMap<>(); List<String> headerValues = new ArrayList<>(); headerValues.add("value"); headers.put("client-override-test", headerValues); List<MetricPublisher> metricPublishers = new ArrayList<>(); MetricPublisher metricPublisher = new MetricPublisher() { @Override public void publish(MetricCollection metricCollection) { } @Override public void close() { } }; metricPublishers.add(metricPublisher); ExecutionAttribute<String> execAttribute = new ExecutionAttribute<>("test"); ExecutionAttributes executionAttributes = ExecutionAttributes.builder().put(execAttribute, "value").build(); Signer signer = (request, execAttributes) -> request; String suffix = "suffix"; String prefix = "prefix"; Duration apiCallTimeout = Duration.ofMillis(42); Duration apiCallAttemptTimeout = Duration.ofMillis(43); ProfileFile profileFile = ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build(); String profileName = "name"; ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .executionInterceptors(interceptors) .retryPolicy(retryPolicy) .headers(headers) .putAdvancedOption(SIGNER, signer) .putAdvancedOption(USER_AGENT_SUFFIX, suffix) .putAdvancedOption(USER_AGENT_PREFIX, prefix) .apiCallTimeout(apiCallTimeout) .apiCallAttemptTimeout(apiCallAttemptTimeout) .putAdvancedOption(DISABLE_HOST_PREFIX_INJECTION, Boolean.TRUE) .defaultProfileFile(profileFile) .defaultProfileName(profileName) .metricPublishers(metricPublishers) .executionAttributes(executionAttributes) .putAdvancedOption(ENDPOINT_OVERRIDDEN_OVERRIDE, Boolean.TRUE) .scheduledExecutorService(scheduledExecutorService) .build(); SdkClientConfiguration config = testClientBuilder().overrideConfiguration(overrideConfig).build().clientConfiguration; assertThat(config.option(EXECUTION_INTERCEPTORS)).contains(interceptor); assertThat(config.option(RETRY_POLICY)).isEqualTo(retryPolicy); assertThat(config.option(ADDITIONAL_HTTP_HEADERS).get("client-override-test")).isEqualTo(headerValues); assertThat(config.option(SIGNER)).isEqualTo(signer); assertThat(config.option(USER_AGENT_SUFFIX)).isEqualTo(suffix); assertThat(config.option(USER_AGENT_PREFIX)).isEqualTo(prefix); assertThat(config.option(API_CALL_TIMEOUT)).isEqualTo(apiCallTimeout); assertThat(config.option(API_CALL_ATTEMPT_TIMEOUT)).isEqualTo(apiCallAttemptTimeout); assertThat(config.option(DISABLE_HOST_PREFIX_INJECTION)).isEqualTo(Boolean.TRUE); assertThat(config.option(PROFILE_FILE)).isEqualTo(profileFile); assertThat(config.option(PROFILE_FILE_SUPPLIER).get()).isEqualTo(profileFile); assertThat(config.option(PROFILE_NAME)).isEqualTo(profileName); assertThat(config.option(METRIC_PUBLISHERS)).contains(metricPublisher); assertThat(config.option(EXECUTION_ATTRIBUTES).getAttribute(execAttribute)).isEqualTo("value"); assertThat(config.option(ENDPOINT_OVERRIDDEN)).isEqualTo(Boolean.TRUE); // Ensure that the SDK won't close the scheduled executor service we provided. config.close(); config.option(SCHEDULED_EXECUTOR_SERVICE).shutdownNow(); config.option(SCHEDULED_EXECUTOR_SERVICE).shutdown(); Mockito.verify(scheduledExecutorService, never()).shutdown(); Mockito.verify(scheduledExecutorService, never()).shutdownNow(); } @Test public void buildIncludesServiceDefaults() { TestClient client = testClientBuilder().build(); assertThat(client.clientConfiguration.option(SIGNER)) .isEqualTo(TEST_SIGNER); } @Test public void buildWithEndpointShouldHaveCorrectEndpointAndSigningRegion() { TestClient client = testClientBuilder().endpointOverride(ENDPOINT).build(); assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)).isEqualTo(ENDPOINT); } @Test public void buildWithEndpointWithoutScheme_shouldThrowException() { assertThatThrownBy(() -> testClientBuilder().endpointOverride(URI.create("localhost")).build()) .hasMessageContaining("The URI scheme of endpointOverride must not be null"); } @Test public void noClientProvided_DefaultHttpClientIsManagedBySdk() { TestClient client = testClientBuilder().build(); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class); verify(defaultHttpClientFactory, times(1)).buildWithDefaults(any()); } @Test public void noAsyncClientProvided_DefaultAsyncHttpClientIsManagedBySdk() { TestAsyncClient client = testAsyncClientBuilder().build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); verify(defaultAsyncHttpClientFactory, times(1)).buildWithDefaults(any()); } @Test public void clientFactoryProvided_ClientIsManagedBySdk() { TestClient client = testClientBuilder().httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { Assertions.assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS); return mock(SdkHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class); verify(defaultHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void asyncHttpClientFactoryProvided_ClientIsManagedBySdk() { TestAsyncClient client = testAsyncClientBuilder() .httpClientBuilder((SdkAsyncHttpClient.Builder) serviceDefaults -> { assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS); return mock(SdkAsyncHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isNotInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void explicitClientProvided_ClientIsNotManagedBySdk() { TestClient client = testClientBuilder() .httpClient(mock(SdkHttpClient.class)) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isInstanceOf(SdkDefaultClientBuilder.NonManagedSdkHttpClient.class); verify(defaultHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void explicitAsyncHttpClientProvided_ClientIsNotManagedBySdk() { TestAsyncClient client = testAsyncClientBuilder() .httpClient(mock(SdkAsyncHttpClient.class)) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isInstanceOf(SdkDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void clientBuilderFieldsHaveBeanEquivalents() throws Exception { // Mutating properties might not have bean equivalents. This is probably fine, since very few customers require // bean-equivalent methods and it's not clear what they'd expect them to be named anyway. Ignore these methods for now. Set<String> NON_BEAN_EQUIVALENT_METHODS = ImmutableSet.of("addPlugin", "plugins", "putAuthScheme"); SdkClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder(); BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass()); Method[] clientBuilderMethods = SdkClientBuilder.class.getDeclaredMethods(); Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> { String propertyName = builderMethod.getName(); if (NON_BEAN_EQUIVALENT_METHODS.contains(propertyName)) { return; } Optional<PropertyDescriptor> propertyForMethod = Arrays.stream(beanInfo.getPropertyDescriptors()) .filter(property -> property.getName().equals(propertyName)) .findFirst(); assertThat(propertyForMethod).as(propertyName + " property").hasValueSatisfying(property -> { assertThat(property.getReadMethod()).as(propertyName + " getter").isNull(); assertThat(property.getWriteMethod()).as(propertyName + " setter").isNotNull(); }); }); } @Test public void defaultProfileFileSupplier_isStaticOrHasIdentityCaching() { SdkClientConfiguration config = testClientBuilder().build().clientConfiguration; Supplier<ProfileFile> defaultProfileFileSupplier = config.option(PROFILE_FILE_SUPPLIER); ProfileFile firstGet = defaultProfileFileSupplier.get(); ProfileFile secondGet = defaultProfileFileSupplier.get(); assertThat(secondGet).isSameAs(firstGet); } private SdkDefaultClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, TEST_SIGNER) .build(); return new TestClientBuilder().overrideConfiguration(overrideConfig); } private SdkDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, TEST_SIGNER) .build(); return new TestAsyncClientBuilder().overrideConfiguration(overrideConfig); } private static class TestClient { private final SdkClientConfiguration clientConfiguration; private TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestClientWithoutEndpointDefaultBuilder extends SdkDefaultClientBuilder<TestClientBuilder, TestClient> implements SdkClientBuilder<TestClientBuilder, TestClient> { public TestClientWithoutEndpointDefaultBuilder() { super(defaultHttpClientFactory, null); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) { return configuration.merge(c -> c.option(SdkAdvancedClientOption.SIGNER, TEST_SIGNER)); } @Override protected AttributeMap childHttpConfig() { return MOCK_DEFAULTS; } } private class TestClientBuilder extends SdkDefaultClientBuilder<TestClientBuilder, TestClient> implements SdkClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientFactory, null); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) { return configuration.merge(c -> c.option(SdkClientOption.ENDPOINT, DEFAULT_ENDPOINT)); } @Override protected AttributeMap childHttpConfig() { return MOCK_DEFAULTS; } } private static class TestAsyncClient { private final SdkClientConfiguration clientConfiguration; private TestAsyncClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestAsyncClientBuilder extends SdkDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> implements SdkClientBuilder<TestAsyncClientBuilder, TestAsyncClient> { public TestAsyncClientBuilder() { super(defaultHttpClientFactory, defaultAsyncHttpClientFactory); } @Override protected TestAsyncClient buildClient() { return new TestAsyncClient(super.asyncClientConfiguration()); } @Override protected SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) { return configuration.merge(c -> c.option(SdkClientOption.ENDPOINT, DEFAULT_ENDPOINT)); } @Override protected AttributeMap childHttpConfig() { return MOCK_DEFAULTS; } } }
1,756
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/interceptor/ExecutionAttributesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.interceptor; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class ExecutionAttributesTest { private static final ExecutionAttribute<String> ATTR_1 = new ExecutionAttribute<>("Attr1"); private static final ExecutionAttribute<String> ATTR_2 = new ExecutionAttribute<>("Attr2"); @Test public void equals_identity_returnsTrue() { ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); assertThat(executionAttributes.equals(executionAttributes)).isTrue(); } @Test public void equals_sameAttributes_returnsTrue() { ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); assertThat(executionAttributes1).isEqualTo(executionAttributes2); assertThat(executionAttributes2).isEqualTo(executionAttributes1); } @Test public void equals_differentAttributes_returnsFalse() { ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder() .put(ATTR_1, "HELLO") .put(ATTR_2, "WORLD") .build(); ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); assertThat(executionAttributes1).isNotEqualTo(executionAttributes2); assertThat(executionAttributes2).isNotEqualTo(executionAttributes1); } @Test public void hashCode_objectsEqual_valuesEqual() { ExecutionAttributes executionAttributes1 = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); ExecutionAttributes executionAttributes2 = ExecutionAttributes.builder() .put(ATTR_1, "hello") .put(ATTR_2, "world") .build(); assertThat(executionAttributes1.hashCode()).isEqualTo(executionAttributes2.hashCode()); } }
1,757
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/test/java/software/amazon/awssdk/core/interceptor/ExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.interceptor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ExecutionAttributeTest { @Test @DisplayName("Ensure that two different ExecutionAttributes are not allowed to have the same name (and hash key)") void testUniqueness() { String name = "ExecutionAttributeTest"; ExecutionAttribute<Integer> first = new ExecutionAttribute<>(name); assertThatThrownBy(() -> { ExecutionAttribute<Integer> second = new ExecutionAttribute<>(name); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(name); } }
1,758
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/AmazonHttpClientSslHandshakeTimeoutTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import java.io.IOException; import java.time.Duration; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.NullErrorResponseHandler; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.apache.ApacheHttpClient; import utils.HttpTestUtils; /** * This test is to verify that the apache-httpclient library has fixed the bug where socket timeout configuration is * incorrectly ignored during SSL handshake. This test is expected to hang (and fail after the junit timeout) if run * against the problematic httpclient version (e.g. 4.3). * * @link https://issues.apache.org/jira/browse/HTTPCLIENT-1478 */ public class AmazonHttpClientSslHandshakeTimeoutTest extends UnresponsiveMockServerTestBase { private static final Duration CLIENT_SOCKET_TO = Duration.ofSeconds(1); @Test(timeout = 60 * 1000) public void testSslHandshakeTimeout() { AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder() .retryPolicy(RetryPolicy.none()) .httpClient(ApacheHttpClient.builder() .socketTimeout(CLIENT_SOCKET_TO) .build()) .build(); System.out.println("Sending request to localhost..."); try { SdkHttpFullRequest request = server.configureHttpsEndpoint(SdkHttpFullRequest.builder()) .method(SdkHttpMethod.GET) .build(); httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(null, new NullErrorResponseHandler())); fail("Client-side socket read timeout is expected!"); } catch (SdkClientException e) { e.printStackTrace(); /** * Http client catches the SocketTimeoutException and throws a * ConnectTimeoutException. * {@link DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost, * InetSocketAddress, int, SocketConfig, HttpContext)} */ assertThat(e).hasCauseInstanceOf(IOException.class); } } }
1,759
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/ConnectionPoolMaxConnectionsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.executionContext; import static software.amazon.awssdk.core.internal.util.ResponseHandlerTestUtils.combinedSyncResponseHandler; import java.time.Duration; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.server.MockServer; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.response.EmptySdkResponseHandler; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.apache.ApacheHttpClient; import utils.HttpTestUtils; public class ConnectionPoolMaxConnectionsIntegrationTest { private static MockServer server; @BeforeClass public static void setup() { server = MockServer.createMockServer(MockServer.ServerBehavior.OVERLOADED); server.startServer(); } @AfterClass public static void tearDown() { if (server != null) { server.stopServer(); } } @Test(timeout = 60 * 1000) public void leasing_a_new_connection_fails_with_connection_pool_timeout() { AmazonSyncHttpClient httpClient = HttpTestUtils.testClientBuilder() .retryPolicy(RetryPolicy.none()) .httpClient(ApacheHttpClient.builder() .connectionTimeout(Duration.ofMillis(100)) .maxConnections(1) .build()) .build(); SdkHttpFullRequest request = server.configureHttpEndpoint(SdkHttpFullRequest.builder()) .method(SdkHttpMethod.GET) .build(); // Block the first connection in the pool with this request. httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(new EmptySdkResponseHandler(), null)); try { // A new connection will be leased here which would fail in // ConnectionPoolTimeoutException. httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestRequest.builder().build()) .executionContext(executionContext(request)) .execute(combinedSyncResponseHandler(null, null)); Assert.fail("Connection pool timeout exception is expected!"); } catch (SdkClientException e) { Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException); } } }
1,760
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/timers
Create_ds/aws-sdk-java-v2/core/sdk-core/src/it/java/software/amazon/awssdk/core/http/timers/client/AbortedExceptionClientExecutionTimerIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.http.timers.client; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.createMockGetRequest; import static software.amazon.awssdk.core.internal.http.timers.ClientExecutionAndRequestTimerTestUtils.execute; import java.time.Duration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.exception.AbortedException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpResponse; import utils.HttpTestUtils; @RunWith(MockitoJUnitRunner.class) public class AbortedExceptionClientExecutionTimerIntegrationTest { private AmazonSyncHttpClient httpClient; @Mock private SdkHttpClient sdkHttpClient; @Mock private ExecutableHttpRequest abortableCallable; @Before public void setup() throws Exception { when(sdkHttpClient.prepareRequest(any())).thenReturn(abortableCallable); httpClient = HttpTestUtils.testClientBuilder().httpClient(sdkHttpClient) .apiCallTimeout(Duration.ofMillis(1000)) .build(); when(abortableCallable.call()).thenReturn(HttpExecuteResponse.builder().response(SdkHttpResponse.builder() .statusCode(200) .build()) .build()); } @Test(expected = AbortedException.class) public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_not_expired() throws Exception { when(abortableCallable.call()).thenThrow(AbortedException.builder().build()); execute(httpClient, createMockGetRequest().build()); } @Test(expected = ApiCallTimeoutException.class) public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_expired() throws Exception { // Simulate a slow HTTP request when(abortableCallable.call()).thenAnswer(i -> { Thread.sleep(10_000); return null; }); execute(httpClient, createMockGetRequest().build()); } }
1,761
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/FileRequestBodyConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.nio.file.Path; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration options for {@link AsyncRequestBody#fromFile(FileRequestBodyConfiguration)} to configure how the SDK * should read the file. * * @see #builder() */ @SdkPublicApi public final class FileRequestBodyConfiguration implements ToCopyableBuilder<FileRequestBodyConfiguration.Builder, FileRequestBodyConfiguration> { private final Integer chunkSizeInBytes; private final Long position; private final Long numBytesToRead; private final Path path; private FileRequestBodyConfiguration(DefaultBuilder builder) { this.path = Validate.notNull(builder.path, "path"); this.chunkSizeInBytes = Validate.isPositiveOrNull(builder.chunkSizeInBytes, "chunkSizeInBytes"); this.position = Validate.isNotNegativeOrNull(builder.position, "position"); this.numBytesToRead = Validate.isNotNegativeOrNull(builder.numBytesToRead, "numBytesToRead"); } /** * Create a {@link Builder}, used to create a {@link FileRequestBodyConfiguration}. */ public static Builder builder() { return new DefaultBuilder(); } /** * @return the size of each chunk to read from the file */ public Integer chunkSizeInBytes() { return chunkSizeInBytes; } /** * @return the file position at which the request body begins. */ public Long position() { return position; } /** * @return the number of bytes to read from this file. */ public Long numBytesToRead() { return numBytesToRead; } /** * @return the file path */ public Path path() { return path; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileRequestBodyConfiguration that = (FileRequestBodyConfiguration) o; if (!Objects.equals(chunkSizeInBytes, that.chunkSizeInBytes)) { return false; } if (!Objects.equals(position, that.position)) { return false; } if (!Objects.equals(numBytesToRead, that.numBytesToRead)) { return false; } return Objects.equals(path, that.path); } @Override public int hashCode() { int result = chunkSizeInBytes != null ? chunkSizeInBytes.hashCode() : 0; result = 31 * result + (position != null ? position.hashCode() : 0); result = 31 * result + (numBytesToRead != null ? numBytesToRead.hashCode() : 0); result = 31 * result + (path != null ? path.hashCode() : 0); return result; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } public interface Builder extends CopyableBuilder<Builder, FileRequestBodyConfiguration> { /** * Sets the {@link Path} to the file containing data to send to the service * * @param path Path to file to read. * @return This builder for method chaining. */ Builder path(Path path); /** * Sets the size of chunks read from the file. Increasing this will cause more data to be buffered into memory but * may yield better latencies. Decreasing this will reduce memory usage but may cause reduced latency. Setting this value * is very dependent on upload speed and requires some performance testing to tune. * * <p>The default chunk size is 16 KiB</p> * * @param chunkSize New chunk size in bytes. * @return This builder for method chaining. */ Builder chunkSizeInBytes(Integer chunkSize); /** * Sets the file position at which the request body begins. * * <p>By default, it's 0, i.e., reading from the beginning. * * @param position the position of the file * @return The builder for method chaining. */ Builder position(Long position); /** * Sets the number of bytes to read from this file. * * <p>By default, it's same as the file length. * * @param numBytesToRead number of bytes to read * @return The builder for method chaining. */ Builder numBytesToRead(Long numBytesToRead); } private static final class DefaultBuilder implements Builder { private Long position; private Path path; private Integer chunkSizeInBytes; private Long numBytesToRead; private DefaultBuilder(FileRequestBodyConfiguration configuration) { this.position = configuration.position; this.path = configuration.path; this.chunkSizeInBytes = configuration.chunkSizeInBytes; this.numBytesToRead = configuration.numBytesToRead; } private DefaultBuilder() { } @Override public Builder path(Path path) { this.path = path; return this; } @Override public Builder chunkSizeInBytes(Integer chunkSizeInBytes) { this.chunkSizeInBytes = chunkSizeInBytes; return this; } @Override public Builder position(Long position) { this.position = position; return this; } @Override public Builder numBytesToRead(Long numBytesToRead) { this.numBytesToRead = numBytesToRead; return this; } @Override public FileRequestBodyConfiguration build() { return new FileRequestBodyConfiguration(this); } } }
1,762
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ResponseInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.io.SdkFilterInputStream; import software.amazon.awssdk.http.Abortable; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.utils.Validate; /** * Input stream that provides access to the unmarshalled POJO response returned by the service in addition to the streamed * contents. This input stream should be closed to release the underlying connection back to the connection pool. * * <p> * If it is not desired to read remaining data from the stream, you can explicitly abort the connection via {@link #abort()}. * Note that this will close the underlying connection and require establishing an HTTP connection which may outweigh the * cost of reading the additional data. * </p> */ @SdkPublicApi public final class ResponseInputStream<ResponseT> extends SdkFilterInputStream implements Abortable { private final ResponseT response; private final Abortable abortable; public ResponseInputStream(ResponseT resp, AbortableInputStream in) { super(in); this.response = Validate.paramNotNull(resp, "response"); this.abortable = Validate.paramNotNull(in, "abortableInputStream"); } public ResponseInputStream(ResponseT resp, InputStream in) { super(in); this.response = Validate.paramNotNull(resp, "response"); this.abortable = in instanceof Abortable ? (Abortable) in : null; } /** * @return The unmarshalled POJO response associated with this content. */ public ResponseT response() { return response; } @Override public void abort() { if (abortable != null) { abortable.abort(); } } }
1,763
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/Response.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Response wrapper that indicates success or failure with the associated unmarshalled response object or exception * object. This object is used by the core request/response pipeline to pass response metadata alongside the actual * deserialized response object through different stages of the pipeline. * * @param <T> the modelled SDK response type. */ @SdkProtectedApi public final class Response<T> { private final Boolean isSuccess; private final T response; private final SdkException exception; private final SdkHttpFullResponse httpResponse; private Response(Builder<T> builder) { this.isSuccess = builder.isSuccess; this.response = builder.response; this.exception = builder.exception; this.httpResponse = builder.httpResponse; } /** * Returns a newly initialized builder object for a {@link Response} * @param <T> Modelled response type. */ public static <T> Builder<T> builder() { return new Builder<>(); } /** * Creates a new builder with initial values pulled from the current object. */ public Builder<T> toBuilder() { return new Builder<T>().isSuccess(this.isSuccess) .response(this.response) .exception(this.exception) .httpResponse(this.httpResponse); } /** * The modelled response object returned by the service. If the response was a failure, this value is likely to * be null. */ public T response() { return response; } /** * The modelled exception returned by the service. If the response was not a failure, this value is likely to * be null. */ public SdkException exception() { return exception; } /** * The HTTP response that was received by the SDK prior to determining the result. */ public SdkHttpFullResponse httpResponse() { return httpResponse; } /** * Indicates whether the result indicates success or failure of the original request. A true value indicates * success; a false value indicates failure. */ public Boolean isSuccess() { return isSuccess; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Response<?> response1 = (Response<?>) o; if (isSuccess != null ? ! isSuccess.equals(response1.isSuccess) : response1.isSuccess != null) { return false; } if (response != null ? ! response.equals(response1.response) : response1.response != null) { return false; } if (exception != null ? ! exception.equals(response1.exception) : response1.exception != null) { return false; } return httpResponse != null ? httpResponse.equals(response1.httpResponse) : response1.httpResponse == null; } @Override public int hashCode() { int result = isSuccess != null ? isSuccess.hashCode() : 0; result = 31 * result + (response != null ? response.hashCode() : 0); result = 31 * result + (exception != null ? exception.hashCode() : 0); result = 31 * result + (httpResponse != null ? httpResponse.hashCode() : 0); return result; } public static final class Builder<T> { private Boolean isSuccess; private T response; private SdkException exception; private SdkHttpFullResponse httpResponse; private Builder() { } /** * Indicates whether the result indicates success or failure of the original request. A true value indicates * success; a false value indicates failure. */ public Builder<T> isSuccess(Boolean success) { isSuccess = success; return this; } /** * The modelled response object returned by the service. If the response was a failure, this value is likely to * be null. */ public Builder<T> response(T response) { this.response = response; return this; } /** * The modelled exception returned by the service. If the response was not a failure, this value is likely to * be null. */ public Builder<T> exception(SdkException exception) { this.exception = exception; return this; } /** * The HTTP response that was received by the SDK prior to determining the result. */ public Builder<T> httpResponse(SdkHttpFullResponse httpResponse) { this.httpResponse = httpResponse; return this; } /** * Builds a {@link Response} object based on the values held by this builder. */ public Response<T> build() { return new Response<>(this); } } }
1,764
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkSystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.utils.SystemSetting; /** * System properties to configure the SDK runtime. */ @SdkProtectedApi public enum SdkSystemSetting implements SystemSetting { /** * Configure the AWS access key ID. * * This value will not be ignored if the {@link #AWS_SECRET_ACCESS_KEY} is not specified. */ AWS_ACCESS_KEY_ID("aws.accessKeyId", null), /** * Configure the AWS secret access key. * * This value will not be ignored if the {@link #AWS_ACCESS_KEY_ID} is not specified. */ AWS_SECRET_ACCESS_KEY("aws.secretAccessKey", null), /** * Configure the AWS session token. */ AWS_SESSION_TOKEN("aws.sessionToken", null), /** * Configure the AWS web identity token file path. */ AWS_WEB_IDENTITY_TOKEN_FILE("aws.webIdentityTokenFile", null), /** * Configure the AWS role arn. */ AWS_ROLE_ARN("aws.roleArn", null), /** * Configure the session name for a role. */ AWS_ROLE_SESSION_NAME("aws.roleSessionName", null), /** * Configure the default region. */ AWS_REGION("aws.region", null), /** * Whether to load information such as credentials, regions from EC2 Metadata instance service. */ AWS_EC2_METADATA_DISABLED("aws.disableEc2Metadata", "false"), /** * The EC2 instance metadata service endpoint. * * This allows a service running in EC2 to automatically load its credentials and region without needing to configure them * in the SdkClientBuilder. */ AWS_EC2_METADATA_SERVICE_ENDPOINT("aws.ec2MetadataServiceEndpoint", "http://169.254.169.254"), AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE("aws.ec2MetadataServiceEndpointMode", "IPv4"), /** * The elastic container metadata service endpoint that should be called by the ContainerCredentialsProvider * when loading data from the container metadata service. * * This allows a service running in an elastic container to automatically load its credentials without needing to configure * them in the SdkClientBuilder. * * This is not used if the {@link #AWS_CONTAINER_CREDENTIALS_RELATIVE_URI} is not specified. */ AWS_CONTAINER_SERVICE_ENDPOINT("aws.containerServiceEndpoint", "http://169.254.170.2"), /** * The elastic container metadata service path that should be called by the ContainerCredentialsProvider when * loading credentials form the container metadata service. If this is not specified, credentials will not be automatically * loaded from the container metadata service. * * @see #AWS_CONTAINER_SERVICE_ENDPOINT */ AWS_CONTAINER_CREDENTIALS_RELATIVE_URI("aws.containerCredentialsPath", null), /** * The full URI path to a localhost metadata service to be used. */ AWS_CONTAINER_CREDENTIALS_FULL_URI("aws.containerCredentialsFullUri", null), /** * An authorization token to pass to a container metadata service, only used when {@link #AWS_CONTAINER_CREDENTIALS_FULL_URI} * is specified. * * @see #AWS_CONTAINER_CREDENTIALS_FULL_URI */ AWS_CONTAINER_AUTHORIZATION_TOKEN("aws.containerAuthorizationToken", null), /** * Explicitly identify the default synchronous HTTP implementation the SDK will use. Useful * when there are multiple implementations on the classpath or as a performance optimization * since implementation discovery requires classpath scanning. */ SYNC_HTTP_SERVICE_IMPL("software.amazon.awssdk.http.service.impl", null), /** * Explicitly identify the default Async HTTP implementation the SDK will use. Useful * when there are multiple implementations on the classpath or as a performance optimization * since implementation discovery requires classpath scanning. */ ASYNC_HTTP_SERVICE_IMPL("software.amazon.awssdk.http.async.service.impl", null), /** * Whether CBOR optimization should automatically be used if its support is found on the classpath and the service supports * CBOR-formatted JSON. */ CBOR_ENABLED("aws.cborEnabled", "true"), /** * Whether binary ION representation optimization should automatically be used if the service supports ION. */ BINARY_ION_ENABLED("aws.binaryIonEnabled", "true"), /** * The execution environment of the SDK user. This is automatically set in certain environments by the underlying AWS service. * For example, AWS Lambda will automatically specify a runtime indicating that the SDK is being used within Lambda. */ AWS_EXECUTION_ENV("aws.executionEnvironment", null), /** * Whether endpoint discovery should be enabled. */ AWS_ENDPOINT_DISCOVERY_ENABLED("aws.endpointDiscoveryEnabled", null), /** * The S3 regional endpoint setting for the {@code us-east-1} region. Setting the value to {@code regional} causes * the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the {@code US_EAST_1} region instead of * the global {@code s3.amazonaws.com}. Using the regional endpoint is disabled by default. */ AWS_S3_US_EAST_1_REGIONAL_ENDPOINT("aws.s3UseUsEast1RegionalEndpoint", null), /** * Which {@link RetryMode} to use for the default {@link RetryPolicy}, when one is not specified at the client level. */ AWS_RETRY_MODE("aws.retryMode", null), /** * Defines the default value for {@link RetryPolicy.Builder#numRetries(Integer)}, if the retry count is not overridden in the * retry policy configured via {@link ClientOverrideConfiguration.Builder#retryPolicy(RetryPolicy)}. This is one more than * the number of retries, so aws.maxAttempts = 1 is 0 retries. */ AWS_MAX_ATTEMPTS("aws.maxAttempts", null), /** * Which {@code DefaultsMode} to use, case insensitive */ AWS_DEFAULTS_MODE("aws.defaultsMode", null), /** * Defines whether dualstack endpoints should be resolved during default endpoint resolution instead of non-dualstack * endpoints. */ AWS_USE_DUALSTACK_ENDPOINT("aws.useDualstackEndpoint", null), /** * Defines whether fips endpoints should be resolved during default endpoint resolution instead of non-fips endpoints. */ AWS_USE_FIPS_ENDPOINT("aws.useFipsEndpoint", null), /** * Whether request compression is disabled for operations marked with the RequestCompression trait. The default value is * false, i.e., request compression is enabled. */ AWS_DISABLE_REQUEST_COMPRESSION("aws.disableRequestCompression", null), /** * Defines the minimum compression size in bytes, inclusive, for a request to be compressed. The default value is 10_240. * The value must be non-negative and no greater than 10_485_760. */ AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES("aws.requestMinCompressionSizeBytes", null), ; private final String systemProperty; private final String defaultValue; SdkSystemSetting(String systemProperty, String defaultValue) { this.systemProperty = systemProperty; this.defaultValue = defaultValue; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return name(); } @Override public String defaultValue() { return defaultValue; } }
1,765
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/CredentialType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Class that identifies the type of credentials typically used by the service to authorize an api request. */ @SdkPublicApi public final class CredentialType { /** * Credential type that uses Bearer Token Authorization to authorize a request. * <p>For more details, see: * <a href="https://oauth.net/2/bearer-tokens/"> * https://oauth.net/2/bearer-tokens/</a></p> */ public static final CredentialType TOKEN = of("TOKEN"); private final String value; private CredentialType(String value) { this.value = value; } /** * Retrieves the Credential Type for a given value. * @param value Teh value to get CredentialType for. * @return {@link CredentialType} for the given value. */ public static CredentialType of(String value) { Validate.paramNotNull(value, "value"); return CredentialTypeCache.put(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CredentialType that = (CredentialType) o; return Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hashCode(value); } @Override public String toString() { return ToString.builder("CredentialType{" + "value='" + value + '\'' + '}').build(); } private static class CredentialTypeCache { private static final ConcurrentHashMap<String, CredentialType> VALUES = new ConcurrentHashMap<>(); private CredentialTypeCache() { } private static CredentialType put(String value) { return VALUES.computeIfAbsent(value, v -> new CredentialType(value)); } } }
1,766
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/FileTransformerConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.nio.channels.AsynchronousChannelGroup; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Path; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration options for {@link AsyncResponseTransformer#toFile(Path, FileTransformerConfiguration)} to configure how the SDK * should write the file and if the SDK should delete the file when an exception occurs. * * @see #builder() * @see FileWriteOption * @see FailureBehavior */ @SdkPublicApi public final class FileTransformerConfiguration implements ToCopyableBuilder<FileTransformerConfiguration.Builder, FileTransformerConfiguration> { private final FileWriteOption fileWriteOption; private final FailureBehavior failureBehavior; private final ExecutorService executorService; private FileTransformerConfiguration(DefaultBuilder builder) { this.fileWriteOption = Validate.paramNotNull(builder.fileWriteOption, "fileWriteOption"); this.failureBehavior = Validate.paramNotNull(builder.failureBehavior, "failureBehavior"); this.executorService = builder.executorService; } /** * The configured {@link FileWriteOption} */ public FileWriteOption fileWriteOption() { return fileWriteOption; } /** * The configured {@link FailureBehavior} */ public FailureBehavior failureBehavior() { return failureBehavior; } /** * The configured {@link ExecutorService} the writes should be executed on. * <p> * If not set, the default thread pool defined by the underlying {@link java.nio.file.spi.FileSystemProvider} will be used. * This will typically be the thread pool defined by the {@link AsynchronousChannelGroup}. */ public Optional<ExecutorService> executorService() { return Optional.ofNullable(executorService); } /** * Create a {@link Builder}, used to create a {@link FileTransformerConfiguration}. */ public static Builder builder() { return new DefaultBuilder(); } /** * Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_NEW} * <p> * Always create a new file. If the file already exists, {@link FileAlreadyExistsException} will be thrown. * In the event of an error, the SDK will attempt to delete the file (whatever has been written to it so far). */ public static FileTransformerConfiguration defaultCreateNew() { return builder().fileWriteOption(FileWriteOption.CREATE_NEW) .failureBehavior(FailureBehavior.DELETE) .build(); } /** * Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_OR_REPLACE_EXISTING} * <p> * Create a new file if it doesn't exist, otherwise replace the existing file. * In the event of an error, the SDK will NOT attempt to delete the file, leaving it as-is */ public static FileTransformerConfiguration defaultCreateOrReplaceExisting() { return builder().fileWriteOption(FileWriteOption.CREATE_OR_REPLACE_EXISTING) .failureBehavior(FailureBehavior.LEAVE) .build(); } /** * Returns the default {@link FileTransformerConfiguration} for {@link FileWriteOption#CREATE_OR_APPEND_TO_EXISTING} * <p> * Create a new file if it doesn't exist, otherwise append to the existing file. * In the event of an error, the SDK will NOT attempt to delete the file, leaving it as-is */ public static FileTransformerConfiguration defaultCreateOrAppend() { return builder().fileWriteOption(FileWriteOption.CREATE_OR_APPEND_TO_EXISTING) .failureBehavior(FailureBehavior.LEAVE) .build(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileTransformerConfiguration that = (FileTransformerConfiguration) o; if (fileWriteOption != that.fileWriteOption) { return false; } if (failureBehavior != that.failureBehavior) { return false; } return Objects.equals(executorService, that.executorService); } @Override public int hashCode() { int result = fileWriteOption != null ? fileWriteOption.hashCode() : 0; result = 31 * result + (failureBehavior != null ? failureBehavior.hashCode() : 0); result = 31 * result + (executorService != null ? executorService.hashCode() : 0); return result; } /** * Defines how the SDK should write the file */ public enum FileWriteOption { /** * Always create a new file. If the file already exists, {@link FileAlreadyExistsException} will be thrown. */ CREATE_NEW, /** * Create a new file if it doesn't exist, otherwise replace the existing file. */ CREATE_OR_REPLACE_EXISTING, /** * Create a new file if it doesn't exist, otherwise append to the existing file. */ CREATE_OR_APPEND_TO_EXISTING } /** * Defines how the SDK should handle the file if there is an exception */ public enum FailureBehavior { /** * In the event of an error, the SDK will attempt to delete the file and whatever has been written to it so far. */ DELETE, /** * In the event of an error, the SDK will NOT attempt to delete the file and leave the file as-is (with whatever has been * written to it so far) */ LEAVE } public interface Builder extends CopyableBuilder<Builder, FileTransformerConfiguration> { /** * Configures how to write the file * * @param fileWriteOption the file write option * @return This object for method chaining. */ Builder fileWriteOption(FileWriteOption fileWriteOption); /** * Configures the {@link FailureBehavior} in the event of an error * * @param failureBehavior the failure behavior * @return This object for method chaining. */ Builder failureBehavior(FailureBehavior failureBehavior); /** * Configures the {@link ExecutorService} the writes should be executed on. * * @param executorService the executor service to use, or null if using the default thread pool. * @return This object for method chaining. */ Builder executorService(ExecutorService executorService); } private static final class DefaultBuilder implements Builder { private FileWriteOption fileWriteOption; private FailureBehavior failureBehavior; private ExecutorService executorService; private DefaultBuilder() { } private DefaultBuilder(FileTransformerConfiguration fileTransformerConfiguration) { this.fileWriteOption = fileTransformerConfiguration.fileWriteOption; this.failureBehavior = fileTransformerConfiguration.failureBehavior; this.executorService = fileTransformerConfiguration.executorService; } @Override public Builder fileWriteOption(FileWriteOption fileWriteOption) { this.fileWriteOption = fileWriteOption; return this; } @Override public Builder failureBehavior(FailureBehavior failureBehavior) { this.failureBehavior = failureBehavior; return this; } @Override public Builder executorService(ExecutorService executorService) { this.executorService = executorService; return this; } @Override public FileTransformerConfiguration build() { return new FileTransformerConfiguration(this); } } }
1,767
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkStandardLogger.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS; import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZ_ID_2_HEADER; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.Logger; /** * A centralized set of loggers that used across the SDK to log particular types of events. SDK users can then specifically enable * just these loggers to get the type of that they want instead of having to enable all logging. */ @SdkProtectedApi public final class SdkStandardLogger { /** * Logger providing detailed information on requests/responses. Users can enable this logger to get access to AWS request IDs * for responses, individual requests and parameters sent to AWS, etc. */ public static final Logger REQUEST_LOGGER = Logger.loggerFor("software.amazon.awssdk.request"); /** * Logger used for the purpose of logging the request id extracted either from the * http response header or from the response body. */ public static final Logger REQUEST_ID_LOGGER = Logger.loggerFor("software.amazon.awssdk.requestId"); private SdkStandardLogger() { } /** * Log the response status code and request ID */ public static void logRequestId(SdkHttpResponse response) { Supplier<String> logStatement = () -> { String placeholder = "not available"; String requestId = "Request ID: " + response.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS).orElse(placeholder) + ", " + "Extended Request ID: " + response.firstMatchingHeader(X_AMZ_ID_2_HEADER).orElse(placeholder); String responseState = response.isSuccessful() ? "successful" : "failed"; return "Received " + responseState + " response: " + response.statusCode() + ", " + requestId; }; REQUEST_ID_LOGGER.debug(logStatement); REQUEST_LOGGER.debug(logStatement); } }
1,768
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkBytes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.InputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * An in-memory representation of data being given to a service or being returned by a service. * * This can be created via static methods, like {@link SdkBytes#fromByteArray(byte[])}. This can be converted to binary types * via instance methods, like {@link SdkBytes#asByteArray()}. */ @SdkPublicApi public final class SdkBytes extends BytesWrapper implements Serializable { private static final long serialVersionUID = 1L; // Needed for serialization private SdkBytes() { super(); } /** * @see #fromByteArray(byte[]) * @see #fromByteBuffer(ByteBuffer) * @see #fromInputStream(InputStream) * @see #fromUtf8String(String) * @see #fromString(String, Charset) */ private SdkBytes(byte[] bytes) { super(bytes); } /** * Create {@link SdkBytes} from a Byte buffer. This will read the remaining contents of the byte buffer. */ public static SdkBytes fromByteBuffer(ByteBuffer byteBuffer) { Validate.paramNotNull(byteBuffer, "byteBuffer"); return new SdkBytes(BinaryUtils.copyBytesFrom(byteBuffer)); } /** * Create {@link SdkBytes} from a Byte array. This will copy the contents of the byte array. */ public static SdkBytes fromByteArray(byte[] bytes) { Validate.paramNotNull(bytes, "bytes"); return new SdkBytes(Arrays.copyOf(bytes, bytes.length)); } /** * Create {@link SdkBytes} from a Byte array <b>without</b> copying the contents of the byte array. This introduces * concurrency risks, allowing: (1) the caller to modify the byte array stored in this {@code SdkBytes} implementation AND * (2) any users of {@link #asByteArrayUnsafe()} to modify the byte array passed into this {@code SdkBytes} implementation. * * <p>As the method name implies, this is unsafe. Use {@link #fromByteArray(byte[])} unless you're sure you know the risks. */ public static SdkBytes fromByteArrayUnsafe(byte[] bytes) { Validate.paramNotNull(bytes, "bytes"); return new SdkBytes(bytes); } /** * Create {@link SdkBytes} from a string, using the provided charset. */ public static SdkBytes fromString(String string, Charset charset) { Validate.paramNotNull(string, "string"); Validate.paramNotNull(charset, "charset"); return new SdkBytes(string.getBytes(charset)); } /** * Create {@link SdkBytes} from a string, using the UTF-8 charset. */ public static SdkBytes fromUtf8String(String string) { return fromString(string, StandardCharsets.UTF_8); } /** * Create {@link SdkBytes} from an input stream. This will read all of the remaining contents of the stream, but will not * close it. */ public static SdkBytes fromInputStream(InputStream inputStream) { Validate.paramNotNull(inputStream, "inputStream"); return new SdkBytes(invokeSafely(() -> IoUtils.toByteArray(inputStream))); } @Override public String toString() { return ToString.builder("SdkBytes") .add("bytes", asByteArrayUnsafe()) .build(); } }
1,769
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/Protocol.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Represents the communication protocol to use when sending requests to AWS. * <p> * Communication over HTTPS is the default, and is more secure than HTTP, which * is why AWS recommends using HTTPS. HTTPS connections can use more system * resources because of the extra work to encrypt network traffic, so the option * to use HTTP is available in case users need it. */ @SdkProtectedApi public enum Protocol { /** * HTTP Protocol - Using the HTTP protocol is less secure than HTTPS, but * can slightly reduce the system resources used when communicating with * AWS. */ HTTP("http"), /** * HTTPS Protocol - Using the HTTPS protocol is more secure than using the * HTTP protocol, but may use slightly more system resources. AWS recommends * using HTTPS for maximize security. */ HTTPS("https"); private final String protocol; Protocol(String protocol) { this.protocol = protocol; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return protocol; } }
1,770
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/CompressionConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration options for operations with the RequestCompression trait to disable request configuration and set the minimum * compression threshold in bytes. */ @SdkPublicApi public final class CompressionConfiguration implements ToCopyableBuilder<CompressionConfiguration.Builder, CompressionConfiguration> { private final Boolean requestCompressionEnabled; private final Integer minimumCompressionThresholdInBytes; private CompressionConfiguration(DefaultBuilder builder) { this.requestCompressionEnabled = builder.requestCompressionEnabled; this.minimumCompressionThresholdInBytes = builder.minimumCompressionThresholdInBytes; } /** * If set, returns true if request compression is enabled, else false if request compression is disabled. */ public Boolean requestCompressionEnabled() { return requestCompressionEnabled; } /** * If set, returns the minimum compression threshold in bytes, inclusive, in order to trigger request compression. */ public Integer minimumCompressionThresholdInBytes() { return minimumCompressionThresholdInBytes; } /** * Create a {@link CompressionConfiguration.Builder}, used to create a {@link CompressionConfiguration}. */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } @Override public String toString() { return ToString.builder("CompressionConfiguration") .add("requestCompressionEnabled", requestCompressionEnabled) .add("minimumCompressionThresholdInBytes", minimumCompressionThresholdInBytes) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompressionConfiguration that = (CompressionConfiguration) o; if (!Objects.equals(requestCompressionEnabled, that.requestCompressionEnabled)) { return false; } return Objects.equals(minimumCompressionThresholdInBytes, that.minimumCompressionThresholdInBytes); } @Override public int hashCode() { int result = requestCompressionEnabled != null ? requestCompressionEnabled.hashCode() : 0; result = 31 * result + (minimumCompressionThresholdInBytes != null ? minimumCompressionThresholdInBytes.hashCode() : 0); return result; } public interface Builder extends CopyableBuilder<Builder, CompressionConfiguration> { /** * Configures whether request compression is enabled or not, for operations that the service has designated as * supporting compression. The default value is true. * * @param requestCompressionEnabled * @return This object for method chaining. */ Builder requestCompressionEnabled(Boolean requestCompressionEnabled); /** * Configures the minimum compression threshold, inclusive, in bytes. A request whose size is less than the threshold * will not be compressed, even if the compression trait is present. The default value is 10_240. The value must be * non-negative and no greater than 10_485_760. * * @param minimumCompressionThresholdInBytes * @return This object for method chaining. */ Builder minimumCompressionThresholdInBytes(Integer minimumCompressionThresholdInBytes); } private static final class DefaultBuilder implements Builder { private Boolean requestCompressionEnabled; private Integer minimumCompressionThresholdInBytes; private DefaultBuilder() { } private DefaultBuilder(CompressionConfiguration compressionConfiguration) { this.requestCompressionEnabled = compressionConfiguration.requestCompressionEnabled; this.minimumCompressionThresholdInBytes = compressionConfiguration.minimumCompressionThresholdInBytes; } @Override public Builder requestCompressionEnabled(Boolean requestCompressionEnabled) { this.requestCompressionEnabled = requestCompressionEnabled; return this; } @Override public Builder minimumCompressionThresholdInBytes(Integer minimumCompressionThresholdInBytes) { this.minimumCompressionThresholdInBytes = minimumCompressionThresholdInBytes; return this; } @Override public CompressionConfiguration build() { return new CompressionConfiguration(this); } } }
1,771
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SelectedAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.utils.Validate; /** * A container for the identity resolver, signer and auth option that we selected for use with this service call attempt. */ @SdkProtectedApi public final class SelectedAuthScheme<T extends Identity> { private final CompletableFuture<? extends T> identity; private final HttpSigner<T> signer; private final AuthSchemeOption authSchemeOption; public SelectedAuthScheme(CompletableFuture<? extends T> identity, HttpSigner<T> signer, AuthSchemeOption authSchemeOption) { this.identity = Validate.paramNotNull(identity, "identity"); this.signer = Validate.paramNotNull(signer, "signer"); this.authSchemeOption = Validate.paramNotNull(authSchemeOption, "authSchemeOption"); } public CompletableFuture<? extends T> identity() { return identity; } public HttpSigner<T> signer() { return signer; } public AuthSchemeOption authSchemeOption() { return authSchemeOption; } }
1,772
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ServiceConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface ServiceConfiguration { }
1,773
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPlugin.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkPreviewApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * A plugin modifies a client's configuration when the client is created or at request execution * time. */ @SdkPreviewApi @SdkPublicApi @ThreadSafe @FunctionalInterface public interface SdkPlugin extends SdkAutoCloseable { /** * Modify the provided client configuration. */ void configureClient(SdkServiceClientConfiguration.Builder config); @Override default void close() { } }
1,774
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkNumber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * An in-memory representation of Number being given to a service or being returned by a service. * This is a SDK representation of a Number. This allows conversion to any desired numeric type by providing constructors * as below * <ul> * <li>{@link #fromBigDecimal(BigDecimal)} to create from a BigDecimal.</li> * <li>{@link #fromBigInteger(BigInteger)} to create from a BigInteger.</li> * <li>{@link #fromDouble(double)} to create from a double</li> * <li>{@link #fromFloat(float)} to create from a float.</li> * <li>{@link #fromLong(long)} to create from a long.</li> * <li>{@link #fromShort(short)} to create from a short.</li> * <li>{@link #fromInteger(int)} to create from an integer.</li> * <li>{@link #fromString(String)} to create from a String</li> * </ul> * * Thus, by doing this, this class is able to preserve arbitrary precision of any given number. * <p> * If {@link SdkNumber} is expected in a particular number format then its corresponding getter methods can be used. * <p> * Example for a {@link SdkNumber} created with {@link BigDecimal} the * {@link #fromBigDecimal(BigDecimal)} can be used. */ @SdkPublicApi @Immutable public final class SdkNumber extends Number implements Serializable { private static final long serialVersionUID = 1L; private final Number numberValue; private final String stringValue; /** * @param value Number value as passed in the from COnstructor. * @see #fromBigDecimal(BigDecimal) * @see #fromBigInteger(BigInteger) * @see #fromDouble(double) * @see #fromFloat(float) * @see #fromLong(long) * @see #fromShort(short) * @see #fromInteger(int) */ private SdkNumber(Number value) { this.numberValue = value; this.stringValue = null; } /** * . * * @param stringValue String value. * @see #fromString(String) */ private SdkNumber(String stringValue) { this.stringValue = stringValue; this.numberValue = null; } private static boolean isNumberValueNaN(Number numberValue) { return (numberValue instanceof Double && Double.isNaN((double) numberValue)) || (numberValue instanceof Float && Float.isNaN((float) numberValue)); } private static boolean isNumberValueInfinite(Number numberValue) { return (numberValue instanceof Double && Double.isInfinite((double) numberValue)) || (numberValue instanceof Float && Float.isInfinite((float) numberValue)); } private static Number valueOf(Number numberValue) { Number valueOfInfiniteOrNaN = valueOfInfiniteOrNaN(numberValue); return valueOfInfiniteOrNaN != null ? valueOfInfiniteOrNaN : valueInBigDecimal(numberValue); } private static Number valueOfInfiniteOrNaN(Number numberValue) { if (numberValue instanceof Double && (Double.isInfinite((double) numberValue) || Double.isNaN((double) numberValue))) { return Double.valueOf(numberValue.doubleValue()); } else if ((numberValue instanceof Float && (Float.isInfinite((float) numberValue) || Float.isNaN((float) numberValue)))) { return Float.valueOf(numberValue.floatValue()); } else { return null; } } /** * This function converts a given number to BigDecimal Number where the caller can convert to an primitive number. * This is done to keep the precision. * * @param numberValue The number value. * @return Big Decimal value for the given number. */ private static BigDecimal valueInBigDecimal(Number numberValue) { if (numberValue instanceof Double) { return BigDecimal.valueOf((double) numberValue); } else if (numberValue instanceof Float) { return BigDecimal.valueOf((float) numberValue); } else if (numberValue instanceof Integer) { return new BigDecimal((int) numberValue); } else if (numberValue instanceof Short) { return new BigDecimal((short) numberValue); } else if (numberValue instanceof Long) { return BigDecimal.valueOf((Long) numberValue); } else if (numberValue instanceof BigDecimal) { return (BigDecimal) numberValue; } else if (numberValue instanceof BigInteger) { return new BigDecimal((BigInteger) numberValue); } else { return new BigDecimal(numberValue.toString()); } } /** * Create {@link SdkNumber} from a integer value. * * @param integerValue Integer value. * @return new {@link SdkNumber} for the given int value. */ public static SdkNumber fromInteger(int integerValue) { return new SdkNumber(integerValue); } /** * Create {@link SdkNumber} from a BigInteger value. * * @param bigIntegerValue BigInteger value. * @return new {@link SdkNumber} for the given BigInteger value. */ public static SdkNumber fromBigInteger(BigInteger bigIntegerValue) { return new SdkNumber(bigIntegerValue); } /** * Create {@link SdkNumber} from a BigDecimal value. * * @param bigDecimalValue BigInteger value. * @return new {@link SdkNumber} for the given BigDecimal value. */ public static SdkNumber fromBigDecimal(BigDecimal bigDecimalValue) { Validate.notNull(bigDecimalValue, "BigDecimal cannot be null"); return new SdkNumber(bigDecimalValue); } /** * Create {@link SdkNumber} from a long Value. * * @param longValue long value. * @return new {@link SdkNumber} for the given long value. */ public static SdkNumber fromLong(long longValue) { return new SdkNumber(longValue); } /** * Create {@link SdkNumber} from a double Value. * * @param doubleValue long value. * @return new {@link SdkNumber} for the given double value. */ public static SdkNumber fromDouble(double doubleValue) { return new SdkNumber(doubleValue); } /** * Create {@link SdkNumber} from a long Value. * * @param shortValue long value. * @return new {@link SdkNumber} for the given long value. */ public static SdkNumber fromShort(short shortValue) { return new SdkNumber(shortValue); } /** * Create {@link SdkNumber} from a float Value. * * @param floatValue float value. * @return new {@link SdkNumber} for the given float value. */ public static SdkNumber fromFloat(float floatValue) { return new SdkNumber(floatValue); } /** * Create {@link SdkNumber} from a long Value. * * @param stringValue String value. * @return new {@link SdkNumber} for the given stringValue value. */ public static SdkNumber fromString(String stringValue) { return new SdkNumber(stringValue); } /** * Gets the integer value of the {@link SdkNumber}. * If we do a intValue() for {@link SdkNumber} constructed * from float, double, long, BigDecimal, BigInteger number type then it * may result in loss of magnitude and a loss of precision. * The result may lose some of the least significant bits of the value. * Precision is not lost while getting a {@link SdkNumber} which was constructed as * lower precision number type like short, byte, integer. * * @return integer value of {@link SdkNumber} . */ @Override public int intValue() { return numberValue instanceof Integer ? numberValue.intValue() : stringValue != null ? new BigDecimal(stringValue).intValue() : valueOf(numberValue).intValue(); } /** * Gets the long value of the {@link SdkNumber}. * If we do a longValue() for {@link SdkNumber} constructed from * float, double, BigDecimal, BigInteger number type then it * may result in loss of magnitude and a loss of precision. * Precision is not lost while getting a {@link SdkNumber} which was constructed from * lower precision type like short, byte, integer. * * @return long value of {@link SdkNumber}. */ @Override public long longValue() { return numberValue instanceof Long ? numberValue.longValue() : stringValue != null ? new BigDecimal(stringValue).longValue() : valueOf(numberValue).longValue(); } /** * Gets the float value of the {@link SdkNumber}. * If we do a floatValue() for {@link SdkNumber} constructed from * double, BigDecimal, BigInteger number type then it * may result in loss of magnitude and a loss of precision. * Precision is not lost while getting a {@link SdkNumber} which was constructed from * precision type like short, byte, integer, long. * * @return long value of {@link SdkNumber}. */ @Override public float floatValue() { return numberValue instanceof Float ? numberValue.floatValue() : numberValue != null ? valueOf(numberValue).floatValue() : new BigDecimal(stringValue).floatValue(); } /** * Gets the double value of the {@link SdkNumber}. * If we do a doubleValue() for {@link SdkNumber} constructed from BigDecimal, BigInteger number type then it * may result in loss of magnitude and a loss of precision. * Precision is not lost while getting a {@link SdkNumber} which was constructed from * precision type like short, byte, integer, long, float. * * @return long value of {@link SdkNumber}. */ @Override public double doubleValue() { return numberValue instanceof Double ? numberValue.doubleValue() : numberValue != null ? valueOf(numberValue).doubleValue() : new BigDecimal(stringValue).doubleValue(); } /** * Gets the bigDecimalValue of the {@link SdkNumber}. * Precision is not lost in this case. * However bigDecimalValue cannot be performed on * a {{@link SdkNumber}} constructed from Float/Double Nan/Infinity. * * @return BigDecimal value of {@link SdkNumber} * @throws NumberFormatException Exception in thrown if a {@link SdkNumber} was constructed asNan/Infinte number * of Double/FLoat type.Since we cannot convert NaN/Infinite numbers to BigDecimal. */ public BigDecimal bigDecimalValue() { if (stringValue != null) { return new BigDecimal(stringValue); } if (numberValue instanceof BigDecimal) { return (BigDecimal) numberValue; } if (isNumberValueNaN(numberValue) || isNumberValueInfinite(numberValue)) { throw new NumberFormatException("Nan or Infinite Number can not be converted to BigDecimal."); } else { return valueInBigDecimal(numberValue); } } /** * Gets the String value of the {@link SdkNumber}. * * @return the stringValue */ public String stringValue() { return stringValue != null ? stringValue : numberValue.toString(); } @Override public String toString() { return stringValue != null ? stringValue : numberValue.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof SdkNumber)) { return false; } SdkNumber sdkNumber = (SdkNumber) o; return Objects.equals(stringValue(), sdkNumber.stringValue()); } @Override public int hashCode() { return Objects.hashCode(stringValue()); } }
1,775
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ResponseBytes.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * An in-memory representation of the service's response from a streaming operation. This usually obtained by calling the "bytes" * form of a streaming operation, like S3's {@code getObjectBytes}. Can also be retrieved by passing * {@link ResponseTransformer#toBytes()} or {@link AsyncResponseTransformer#toBytes()} to a streaming output operation. */ @SdkPublicApi public final class ResponseBytes<ResponseT> extends BytesWrapper { private final ResponseT response; private ResponseBytes(ResponseT response, byte[] bytes) { super(bytes); this.response = Validate.paramNotNull(response, "response"); } /** * Create {@link ResponseBytes} from a Byte array. This will copy the contents of the byte array. */ public static <ResponseT> ResponseBytes<ResponseT> fromInputStream(ResponseT response, InputStream stream) throws UncheckedIOException { return new ResponseBytes<>(response, invokeSafely(() -> IoUtils.toByteArray(stream))); } /** * Create {@link ResponseBytes} from a Byte array. This will copy the contents of the byte array. */ public static <ResponseT> ResponseBytes<ResponseT> fromByteArray(ResponseT response, byte[] bytes) { return new ResponseBytes<>(response, Arrays.copyOf(bytes, bytes.length)); } /** * Create {@link ResponseBytes} from a Byte array <b>without</b> copying the contents of the byte array. This introduces * concurrency risks, allowing: (1) the caller to modify the byte array stored in this {@code SdkBytes} implementation AND * (2) any users of {@link #asByteArrayUnsafe()} to modify the byte array passed into this {@code SdkBytes} implementation. * * <p>As the method name implies, this is unsafe. Use {@link #fromByteArray(Object, byte[])} unless you're sure you know the * risks. */ public static <ResponseT> ResponseBytes<ResponseT> fromByteArrayUnsafe(ResponseT response, byte[] bytes) { return new ResponseBytes<>(response, bytes); } /** * @return the unmarshalled response object from the service. */ public ResponseT response() { return response; } @Override public String toString() { return ToString.builder("ResponseBytes") .add("response", response) .add("bytes", asByteArrayUnsafe()) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ResponseBytes<?> that = (ResponseBytes<?>) o; return response != null ? response.equals(that.response) : that.response == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (response != null ? response.hashCode() : 0); return result; } }
1,776
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; /** * The base class for all SDK requests. * <p> * Implementations must ensure the class is immutable. * </p> * @see SdkResponse */ @Immutable @SdkPublicApi public abstract class SdkRequest implements SdkPojo { /** * @return The optional client configuration overrides for this request. */ public abstract Optional<? extends RequestOverrideConfiguration> overrideConfiguration(); /** * Used to retrieve the value of a field from any class that extends {@link SdkRequest}. The field name * specified should match the member name from the corresponding service-2.json model specified in the * codegen-resources folder for a given service. The class specifies what class to cast the returned value to. * If the returned value is also a modeled class, the {@link #getValueForField(String, Class)} method will * again be available. * * @param fieldName The name of the member to be retrieved. * @param clazz The class to cast the returned object to. * @return Optional containing the casted return value */ public <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { return Optional.empty(); } public abstract Builder toBuilder(); public interface Builder { RequestOverrideConfiguration overrideConfiguration(); SdkRequest build(); } }
1,777
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.SdkHttpResponse; /** * The base class for all SDK responses. * * @see SdkRequest */ @Immutable @SdkPublicApi public abstract class SdkResponse implements SdkPojo { private final SdkHttpResponse sdkHttpResponse; protected SdkResponse(Builder builder) { this.sdkHttpResponse = builder.sdkHttpResponse(); } /** * @return HTTP response data returned from the service. * * @see SdkHttpResponse */ public SdkHttpResponse sdkHttpResponse() { return sdkHttpResponse; } /** * Used to retrieve the value of a field from any class that extends {@link SdkResponse}. The field name * specified should match the member name from the corresponding service-2.json model specified in the * codegen-resources folder for a given service. The class specifies what class to cast the returned value to. * If the returned value is also a modeled class, the {@link #getValueForField(String, Class)} method will * again be available. * * @param fieldName The name of the member to be retrieved. * @param clazz The class to cast the returned object to. * @return Optional containing the casted return value */ public <T> Optional<T> getValueForField(String fieldName, Class<T> clazz) { return Optional.empty(); } public abstract Builder toBuilder(); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SdkResponse that = (SdkResponse) o; return Objects.equals(sdkHttpResponse, that.sdkHttpResponse); } @Override public int hashCode() { return Objects.hashCode(sdkHttpResponse); } public interface Builder { Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse); SdkHttpResponse sdkHttpResponse(); SdkResponse build(); } protected abstract static class BuilderImpl implements Builder { private SdkHttpResponse sdkHttpResponse; protected BuilderImpl() { } protected BuilderImpl(SdkResponse response) { this.sdkHttpResponse = response.sdkHttpResponse(); } @Override public Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse) { this.sdkHttpResponse = sdkHttpResponse; return this; } @Override public SdkHttpResponse sdkHttpResponse() { return sdkHttpResponse; } } }
1,778
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/RequestOverrideConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPreviewApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Validate; /** * Base per-request override configuration for all SDK requests. */ @Immutable @SdkPublicApi public abstract class RequestOverrideConfiguration { private final Map<String, List<String>> headers; private final Map<String, List<String>> rawQueryParameters; private final List<ApiName> apiNames; private final Duration apiCallTimeout; private final Duration apiCallAttemptTimeout; private final Signer signer; private final List<MetricPublisher> metricPublishers; private final ExecutionAttributes executionAttributes; private final EndpointProvider endpointProvider; private final CompressionConfiguration compressionConfiguration; private final List<SdkPlugin> plugins; protected RequestOverrideConfiguration(Builder<?> builder) { this.headers = CollectionUtils.deepUnmodifiableMap(builder.headers(), () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); this.rawQueryParameters = CollectionUtils.deepUnmodifiableMap(builder.rawQueryParameters()); this.apiNames = Collections.unmodifiableList(new ArrayList<>(builder.apiNames())); this.apiCallTimeout = Validate.isPositiveOrNull(builder.apiCallTimeout(), "apiCallTimeout"); this.apiCallAttemptTimeout = Validate.isPositiveOrNull(builder.apiCallAttemptTimeout(), "apiCallAttemptTimeout"); this.signer = builder.signer(); this.metricPublishers = Collections.unmodifiableList(new ArrayList<>(builder.metricPublishers())); this.executionAttributes = ExecutionAttributes.unmodifiableExecutionAttributes(builder.executionAttributes()); this.endpointProvider = builder.endpointProvider(); this.compressionConfiguration = builder.compressionConfiguration(); this.plugins = Collections.unmodifiableList(new ArrayList<>(builder.plugins())); } /** * Optional additional headers to be added to the HTTP request. * * @return The optional additional headers. */ public Map<String, List<String>> headers() { return headers; } /** * Optional additional query parameters to be added to the HTTP request. * * @return The optional additional query parameters. */ public Map<String, List<String>> rawQueryParameters() { return rawQueryParameters; } /** * The optional names of the higher level libraries that constructed the request. * * @return The names of the libraries. */ public List<ApiName> apiNames() { return apiNames; } /** * The amount of time to allow the client to complete the execution of an API call. This timeout covers the entire client * execution except for marshalling. This includes request handler execution, all HTTP requests including retries, * unmarshalling, etc. This value should always be positive, if present. * * <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the * timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be * requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client * execution timeout feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * @see Builder#apiCallTimeout(Duration) */ public Optional<Duration> apiCallTimeout() { return Optional.ofNullable(apiCallTimeout); } /** * The amount of time to wait for the http request to complete before giving up and timing out. This value should always be * positive, if present. * * <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is * breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that * don't get aborted until several seconds after the timer has been breached. Because of this, the request timeout * feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP * request * (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * @see Builder#apiCallAttemptTimeout(Duration) */ public Optional<Duration> apiCallAttemptTimeout() { return Optional.ofNullable(apiCallAttemptTimeout); } /** * @return the signer for signing the request. This signer get priority over the signer set on the client while * signing the requests. If this value is not set, then the client level signer is used for signing the request. */ public Optional<Signer> signer() { return Optional.ofNullable(signer); } /** * Return the metric publishers for publishing the metrics collected for this request. This list supersedes the * metric publishers set on the client. */ public List<MetricPublisher> metricPublishers() { return metricPublishers; } /** * Return the plugins that will be used to update the configuration used by the request. */ @SdkPreviewApi public List<SdkPlugin> plugins() { return plugins; } /** * Returns the additional execution attributes to be added to this request. * This collection of attributes is added in addition to the attributes set on the client. * An attribute value added on the client within the collection of attributes is superseded by an * attribute value added on the request. */ public ExecutionAttributes executionAttributes() { return executionAttributes; } /** * Returns the endpoint provider for resolving the endpoint for this request. This supersedes the * endpoint provider set on the client. */ public Optional<EndpointProvider> endpointProvider() { return Optional.ofNullable(endpointProvider); } /** * Returns the compression configuration object, if present, which includes options to enable/disable compression and set * the minimum compression threshold. This compression config object supersedes the compression config object set on the * client. */ public Optional<CompressionConfiguration> compressionConfiguration() { return Optional.ofNullable(compressionConfiguration); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RequestOverrideConfiguration that = (RequestOverrideConfiguration) o; return Objects.equals(headers, that.headers) && Objects.equals(rawQueryParameters, that.rawQueryParameters) && Objects.equals(apiNames, that.apiNames) && Objects.equals(apiCallTimeout, that.apiCallTimeout) && Objects.equals(apiCallAttemptTimeout, that.apiCallAttemptTimeout) && Objects.equals(signer, that.signer) && Objects.equals(metricPublishers, that.metricPublishers) && Objects.equals(executionAttributes, that.executionAttributes) && Objects.equals(endpointProvider, that.endpointProvider) && Objects.equals(compressionConfiguration, that.compressionConfiguration) && Objects.equals(plugins, that.plugins); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + Objects.hashCode(headers); hashCode = 31 * hashCode + Objects.hashCode(rawQueryParameters); hashCode = 31 * hashCode + Objects.hashCode(apiNames); hashCode = 31 * hashCode + Objects.hashCode(apiCallTimeout); hashCode = 31 * hashCode + Objects.hashCode(apiCallAttemptTimeout); hashCode = 31 * hashCode + Objects.hashCode(signer); hashCode = 31 * hashCode + Objects.hashCode(metricPublishers); hashCode = 31 * hashCode + Objects.hashCode(executionAttributes); hashCode = 31 * hashCode + Objects.hashCode(endpointProvider); hashCode = 31 * hashCode + Objects.hashCode(compressionConfiguration); hashCode = 31 * hashCode + Objects.hashCode(plugins); return hashCode; } /** * Create a {@link Builder} initialized with the properties of this {@code SdkRequestOverrideConfiguration}. * * @return A new builder intialized with this config's properties. */ public abstract Builder<? extends Builder> toBuilder(); public interface Builder<B extends Builder> { /** * Optional additional headers to be added to the HTTP request. * * @return The optional additional headers. */ Map<String, List<String>> headers(); /** * Add a single header to be set on the HTTP request. * <p> * This overrides any values for the given header set on the request by default by the SDK, as well as header * overrides set at the client level using * {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}. * * <p> * This overrides any values already configured with this header name in the builder. * * @param name The name of the header. * @param value The value of the header. * @return This object for method chaining. */ default B putHeader(String name, String value) { putHeader(name, Collections.singletonList(value)); return (B) this; } /** * Add a single header with multiple values to be set on the HTTP request. * <p> * This overrides any values for the given header set on the request by default by the SDK, as well as header * overrides set at the client level using * {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}. * * <p> * This overrides any values already configured with this header name in the builder. * * @param name The name of the header. * @param values The values of the header. * @return This object for method chaining. */ B putHeader(String name, List<String> values); /** * Add additional headers to be set on the HTTP request. * <p> * This overrides any values for the given headers set on the request by default by the SDK, as well as header * overrides set at the client level using * {@link software.amazon.awssdk.core.client.config.ClientOverrideConfiguration}. * * <p> * This completely overrides any values currently configured in the builder. * * @param headers The set of additional headers. * @return This object for method chaining. */ B headers(Map<String, List<String>> headers); /** * Optional additional query parameters to be added to the HTTP request. * * @return The optional additional query parameters. */ Map<String, List<String>> rawQueryParameters(); /** * Add a single query parameter to be set on the HTTP request. * * <p> * This overrides any values already configured with this query name in the builder. * * @param name The query parameter name. * @param value The query parameter value. * @return This object for method chaining. */ default B putRawQueryParameter(String name, String value) { putRawQueryParameter(name, Collections.singletonList(value)); return (B) this; } /** * Add a single query parameter with multiple values to be set on the HTTP request. * * <p> * This overrides any values already configured with this query name in the builder. * * @param name The query parameter name. * @param values The query parameter values. * @return This object for method chaining. */ B putRawQueryParameter(String name, List<String> values); /** * Configure query parameters to be set on the HTTP request. * * <p> * This completely overrides any query parameters currently configured in the builder. * * @param rawQueryParameters The set of additional query parameters. * @return This object for method chaining. */ B rawQueryParameters(Map<String, List<String>> rawQueryParameters); /** * The optional names of the higher level libraries that constructed the request. * * @return The names of the libraries. */ List<ApiName> apiNames(); /** * Set the optional name of the higher level library that constructed the request. * * @param apiName The name of the library. * * @return This object for method chaining. */ B addApiName(ApiName apiName); /** * Set the optional name of the higher level library that constructed the request. * * @param apiNameConsumer A {@link Consumer} that accepts a {@link ApiName.Builder}. * * @return This object for method chaining. */ B addApiName(Consumer<ApiName.Builder> apiNameConsumer); /** * Configure the amount of time to allow the client to complete the execution of an API call. This timeout covers the * entire client execution except for marshalling. This includes request handler execution, all HTTP requests including * retries, unmarshalling, etc. This value should always be positive, if present. * * <p>The api call timeout feature doesn't have strict guarantees on how quickly a request is aborted when the * timeout is breached. The typical case aborts the request within a few milliseconds but there may occasionally be * requests that don't get aborted until several seconds after the timer has been breached. Because of this, the client * execution timeout feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallAttemptTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * <p> * Note that this timeout takes precedence over the value configured at client level via * {@link ClientOverrideConfiguration.Builder#apiCallTimeout(Duration)}. * * @see RequestOverrideConfiguration#apiCallTimeout() */ B apiCallTimeout(Duration apiCallTimeout); Duration apiCallTimeout(); /** * Configure the amount of time to wait for the http request to complete before giving up and timing out. This value * should always be positive, if present. * * <p>The request timeout feature doesn't have strict guarantees on how quickly a request is aborted when the timeout is * breached. The typical case aborts the request within a few milliseconds but there may occasionally be requests that * don't get aborted until several seconds after the timer has been breached. Because of this, the request timeout * feature should not be used when absolute precision is needed. * * <p>This may be used together with {@link #apiCallTimeout()} to enforce both a timeout on each individual HTTP * request (i.e. each retry) and the total time spent on all requests across retries (i.e. the 'api call' time). * * <p> * Note that this timeout takes precedence over the value configured at client level via * {@link ClientOverrideConfiguration.Builder#apiCallAttemptTimeout(Duration)}. * * @see RequestOverrideConfiguration#apiCallAttemptTimeout() */ B apiCallAttemptTimeout(Duration apiCallAttemptTimeout); Duration apiCallAttemptTimeout(); /** * Sets the signer to use for signing the request. This signer get priority over the signer set on the client while * signing the requests. If this value is null, then the client level signer is used for signing the request. * * @param signer Signer for signing the request * @return This object for method chaining */ B signer(Signer signer); Signer signer(); /** * Sets the metric publishers for publishing the metrics collected for this request. This list supersedes * the metric publisher set on the client. * * @param metricPublisher The list metric publisher for this request. * @return This object for method chaining. */ B metricPublishers(List<MetricPublisher> metricPublisher); /** * Add a metric publisher to the existing list of previously set publishers to be used for publishing metrics * for this request. * * @param metricPublisher The metric publisher to add. */ B addMetricPublisher(MetricPublisher metricPublisher); List<MetricPublisher> metricPublishers(); /** * Sets the additional execution attributes collection for this request. * @param executionAttributes Execution attributes for this request * @return This object for method chaining. */ B executionAttributes(ExecutionAttributes executionAttributes); /** * Add an execution attribute to the existing collection of execution attributes. * @param attribute The execution attribute object * @param value The value of the execution attribute. */ <T> B putExecutionAttribute(ExecutionAttribute<T> attribute, T value); ExecutionAttributes executionAttributes(); /** * Sets the endpointProvider to use for resolving the endpoint of the request. This endpointProvider gets priority * over the endpointProvider set on the client while resolving the endpoint for the requests. * If this value is null, then the client level endpointProvider is used for resolving the endpoint. * * @param endpointProvider Endpoint Provider that will override the resolving the endpoint for the request. * @return This object for method chaining */ B endpointProvider(EndpointProvider endpointProvider); EndpointProvider endpointProvider(); /** * Sets the {@link CompressionConfiguration} for this request. The order of precedence, from highest to lowest, * for this setting is: 1) Per request configuration 2) Client configuration 3) Environment variables 4) Profile setting. * * @param compressionConfiguration Request compression configuration object for this request. */ B compressionConfiguration(CompressionConfiguration compressionConfiguration); /** * Sets the {@link CompressionConfiguration} for this request. The order of precedence, from highest to lowest, * for this setting is: 1) Per request configuration 2) Client configuration 3) Environment variables 4) Profile setting. * * @param compressionConfigurationConsumer A {@link Consumer} that accepts a {@link CompressionConfiguration.Builder} * * @return This object for method chaining */ B compressionConfiguration(Consumer<CompressionConfiguration.Builder> compressionConfigurationConsumer); CompressionConfiguration compressionConfiguration(); /** * Sets the plugins used to update the configuration used by this request. * * @param plugins The list of plugins for this request. * @return This object for method chaining. */ @SdkPreviewApi B plugins(List<SdkPlugin> plugins); /** * Add a plugin used to update the configuration used by this request. * * @param plugin The plugin to add. */ @SdkPreviewApi B addPlugin(SdkPlugin plugin); /** * Returns the list of registered plugins */ @SdkPreviewApi List<SdkPlugin> plugins(); /** * Create a new {@code SdkRequestOverrideConfiguration} with the properties set on this builder. * * @return The new {@code SdkRequestOverrideConfiguration}. */ RequestOverrideConfiguration build(); } protected abstract static class BuilderImpl<B extends Builder> implements Builder<B> { private Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); private Map<String, List<String>> rawQueryParameters = new HashMap<>(); private List<ApiName> apiNames = new ArrayList<>(); private Duration apiCallTimeout; private Duration apiCallAttemptTimeout; private Signer signer; private List<MetricPublisher> metricPublishers = new ArrayList<>(); private ExecutionAttributes.Builder executionAttributesBuilder = ExecutionAttributes.builder(); private EndpointProvider endpointProvider; private CompressionConfiguration compressionConfiguration; private List<SdkPlugin> plugins = new ArrayList<>(); protected BuilderImpl() { } protected BuilderImpl(RequestOverrideConfiguration sdkRequestOverrideConfig) { headers(sdkRequestOverrideConfig.headers); rawQueryParameters(sdkRequestOverrideConfig.rawQueryParameters); sdkRequestOverrideConfig.apiNames.forEach(this::addApiName); apiCallTimeout(sdkRequestOverrideConfig.apiCallTimeout); apiCallAttemptTimeout(sdkRequestOverrideConfig.apiCallAttemptTimeout); signer(sdkRequestOverrideConfig.signer().orElse(null)); metricPublishers(sdkRequestOverrideConfig.metricPublishers()); executionAttributes(sdkRequestOverrideConfig.executionAttributes()); endpointProvider(sdkRequestOverrideConfig.endpointProvider); compressionConfiguration(sdkRequestOverrideConfig.compressionConfiguration); plugins(sdkRequestOverrideConfig.plugins); } @Override public Map<String, List<String>> headers() { return CollectionUtils.unmodifiableMapOfLists(headers); } @Override public B putHeader(String name, List<String> values) { Validate.paramNotNull(values, "values"); headers.put(name, new ArrayList<>(values)); return (B) this; } @Override @SuppressWarnings("unchecked") public B headers(Map<String, List<String>> headers) { Validate.paramNotNull(headers, "headers"); this.headers = CollectionUtils.deepCopyMap(headers); return (B) this; } @Override public Map<String, List<String>> rawQueryParameters() { return CollectionUtils.unmodifiableMapOfLists(rawQueryParameters); } @Override public B putRawQueryParameter(String name, List<String> values) { Validate.paramNotNull(name, "name"); Validate.paramNotNull(values, "values"); rawQueryParameters.put(name, new ArrayList<>(values)); return (B) this; } @Override @SuppressWarnings("unchecked") public B rawQueryParameters(Map<String, List<String>> rawQueryParameters) { Validate.paramNotNull(rawQueryParameters, "rawQueryParameters"); this.rawQueryParameters = CollectionUtils.deepCopyMap(rawQueryParameters); return (B) this; } @Override public List<ApiName> apiNames() { return Collections.unmodifiableList(apiNames); } @Override @SuppressWarnings("unchecked") public B addApiName(ApiName apiName) { this.apiNames.add(apiName); return (B) this; } @Override @SuppressWarnings("unchecked") public B addApiName(Consumer<ApiName.Builder> apiNameConsumer) { ApiName.Builder b = ApiName.builder(); apiNameConsumer.accept(b); addApiName(b.build()); return (B) this; } @Override public B apiCallTimeout(Duration apiCallTimeout) { this.apiCallTimeout = apiCallTimeout; return (B) this; } public void setApiCallTimeout(Duration apiCallTimeout) { apiCallTimeout(apiCallTimeout); } @Override public Duration apiCallTimeout() { return apiCallTimeout; } @Override public B apiCallAttemptTimeout(Duration apiCallAttemptTimeout) { this.apiCallAttemptTimeout = apiCallAttemptTimeout; return (B) this; } public void setApiCallAttemptTimeout(Duration apiCallAttemptTimeout) { apiCallAttemptTimeout(apiCallAttemptTimeout); } @Override public Duration apiCallAttemptTimeout() { return apiCallAttemptTimeout; } @Override public B signer(Signer signer) { this.signer = signer; return (B) this; } public void setSigner(Signer signer) { signer(signer); } @Override public Signer signer() { return signer; } @Override public B metricPublishers(List<MetricPublisher> metricPublishers) { Validate.paramNotNull(metricPublishers, "metricPublishers"); this.metricPublishers = new ArrayList<>(metricPublishers); return (B) this; } @Override public B addMetricPublisher(MetricPublisher metricPublisher) { Validate.paramNotNull(metricPublisher, "metricPublisher"); this.metricPublishers.add(metricPublisher); return (B) this; } public void setMetricPublishers(List<MetricPublisher> metricPublishers) { metricPublishers(metricPublishers); } @Override public List<MetricPublisher> metricPublishers() { return metricPublishers; } @Override public B executionAttributes(ExecutionAttributes executionAttributes) { Validate.paramNotNull(executionAttributes, "executionAttributes"); this.executionAttributesBuilder = executionAttributes.toBuilder(); return (B) this; } @Override public <T> B putExecutionAttribute(ExecutionAttribute<T> executionAttribute, T value) { this.executionAttributesBuilder.put(executionAttribute, value); return (B) this; } @Override public ExecutionAttributes executionAttributes() { return executionAttributesBuilder.build(); } public void setExecutionAttributes(ExecutionAttributes executionAttributes) { executionAttributes(executionAttributes); } @Override public B endpointProvider(EndpointProvider endpointProvider) { this.endpointProvider = endpointProvider; return (B) this; } public void setEndpointProvider(EndpointProvider endpointProvider) { endpointProvider(endpointProvider); } @Override public EndpointProvider endpointProvider() { return endpointProvider; } @Override public B compressionConfiguration(CompressionConfiguration compressionConfiguration) { this.compressionConfiguration = compressionConfiguration; return (B) this; } @Override public B compressionConfiguration(Consumer<CompressionConfiguration.Builder> compressionConfigurationConsumer) { CompressionConfiguration.Builder b = CompressionConfiguration.builder(); compressionConfigurationConsumer.accept(b); compressionConfiguration(b.build()); return (B) this; } @Override public CompressionConfiguration compressionConfiguration() { return compressionConfiguration; } @Override public B plugins(List<SdkPlugin> plugins) { this.plugins = new ArrayList<>(plugins); return (B) this; } @Override public B addPlugin(SdkPlugin plugin) { this.plugins.add(plugin); return (B) this; } @Override public List<SdkPlugin> plugins() { return Collections.unmodifiableList(plugins); } } }
1,779
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkGlobalTime.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Used for clock skew adjustment between the client JVM where the SDK is run, * and the server side. */ @SdkProtectedApi public final class SdkGlobalTime { /** * globalTimeOffset is a time difference in seconds between the running JVM * and AWS. Used to globally adjust the client clock skew. Java SDK already * provides timeOffset and accessor methods in <code>Request</code> class but * those are used per request, whereas this variable will adjust clock skew * globally. Java SDK detects clock skew errors and adjusts global clock * skew automatically. */ private static volatile int globalTimeOffset; private SdkGlobalTime() { } /** * Gets the global time difference in seconds between the running JVM and * AWS. See <code>Request#getTimeOffset()</code> if global time offset is * not set. */ public static int getGlobalTimeOffset() { return globalTimeOffset; } /** * Sets the global time difference in seconds between the running JVM and * AWS. If this value is set then all the subsequent instantiation of an * <code>AmazonHttpClient</code> will start using this * value to generate timestamps. * * @param timeOffset * the time difference in seconds between the running JVM and AWS */ public static void setGlobalTimeOffset(int timeOffset) { globalTimeOffset = timeOffset; } }
1,780
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/RequestOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Client option defaults for individual {@link SdkRequest}s. */ @SdkProtectedApi public final class RequestOption { private RequestOption() { } }
1,781
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPojo.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.List; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Interface to provide the list of {@link SdkField}s in a POJO. {@link SdkField} contains * metadata about how a field should be marshalled/unmarshalled and allows for generic * accessing/setting/creating of that field on an object. */ @SdkProtectedApi public interface SdkPojo { /** * @return List of {@link SdkField} in this POJO. May be empty list but should never be null. */ List<SdkField<?>> sdkFields(); /** * Indicates whether some other object is "equal to" this one by SDK fields. * An SDK field is a modeled, non-inherited field in an {@link SdkPojo} class, * and is generated based on a service model. * * <p> * If an {@link SdkPojo} class does not have any inherited fields, {@code equalsBySdkFields} * and {@code equals} are essentially the same. * * @param other the object to be compared with * @return true if the other object equals to this object by sdk fields, false otherwise. */ default boolean equalsBySdkFields(Object other) { throw new UnsupportedOperationException(); } }
1,782
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ApiName.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static software.amazon.awssdk.utils.Validate.notNull; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Encapsulates the API name and version of a library built using the AWS SDK. * * See {@link RequestOverrideConfiguration.Builder#addApiName(ApiName)}. */ @SdkPublicApi public final class ApiName { private final String name; private final String version; private ApiName(BuilderImpl b) { this.name = notNull(b.name, "name must not be null"); this.version = notNull(b.version, "version must not be null"); } public String name() { return name; } public String version() { return version; } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * Set the name of the API. * * @param name The name. * * @return This object for method chaining. */ Builder name(String name); /** * Set the version of the API. * * @param version The version. * * @return This object for method chaining. */ Builder version(String version); ApiName build(); } private static final class BuilderImpl implements Builder { private String name; private String version; @Override public Builder name(String name) { this.name = name; return this; } public void setName(String name) { name(name); } @Override public Builder version(String version) { this.version = version; return this; } public void setVersion(String version) { version(version); } @Override public ApiName build() { return new ApiName(this); } } }
1,783
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkRequestOverrideConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Base per-request override configuration for all SDK requests. */ @Immutable @SdkPublicApi public final class SdkRequestOverrideConfiguration extends RequestOverrideConfiguration { private SdkRequestOverrideConfiguration(Builder builder) { super(builder); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends RequestOverrideConfiguration.Builder<Builder> { @Override SdkRequestOverrideConfiguration build(); } private static final class BuilderImpl extends RequestOverrideConfiguration.BuilderImpl<Builder> implements Builder { private BuilderImpl() { } private BuilderImpl(SdkRequestOverrideConfiguration sdkRequestOverrideConfig) { super(sdkRequestOverrideConfig); } @Override public SdkRequestOverrideConfiguration build() { return new SdkRequestOverrideConfiguration(this); } } }
1,784
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkField.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.protocol.MarshallLocation; import software.amazon.awssdk.core.protocol.MarshallingType; import software.amazon.awssdk.core.traits.DefaultValueTrait; import software.amazon.awssdk.core.traits.LocationTrait; import software.amazon.awssdk.core.traits.Trait; /** * Metadata about a member in an {@link SdkPojo}. Contains information about how to marshall/unmarshall. * * @param <TypeT> Java Type of member. */ @SdkProtectedApi public final class SdkField<TypeT> { private final String memberName; private final MarshallingType<? super TypeT> marshallingType; private final MarshallLocation location; private final String locationName; private final String unmarshallLocationName; private final Supplier<SdkPojo> constructor; private final BiConsumer<Object, TypeT> setter; private final Function<Object, TypeT> getter; private final Map<Class<? extends Trait>, Trait> traits; private SdkField(Builder<TypeT> builder) { this.memberName = builder.memberName; this.marshallingType = builder.marshallingType; this.traits = new HashMap<>(builder.traits); this.constructor = builder.constructor; this.setter = builder.setter; this.getter = builder.getter; // Eagerly dereference location trait since it's so commonly used. LocationTrait locationTrait = getTrait(LocationTrait.class); this.location = locationTrait.location(); this.locationName = locationTrait.locationName(); this.unmarshallLocationName = locationTrait.unmarshallLocationName(); } public String memberName() { return memberName; } /** * @return MarshallingType of member. Used primarily for marshaller/unmarshaller lookups. */ public MarshallingType<? super TypeT> marshallingType() { return marshallingType; } /** * @return Location the member should be marshalled into (i.e. headers/query/path/payload). */ public MarshallLocation location() { return location; } /** * @return The location name to use when marshalling. I.E. the field name of the JSON document, or the header name, etc. */ public String locationName() { return locationName; } /** * @return The location name to use when unmarshalling. This is only needed for AWS/Query or EC2 services. All * other services should use {@link #locationName} for both marshalling and unmarshalling. */ public String unmarshallLocationName() { return unmarshallLocationName; } public Supplier<SdkPojo> constructor() { return constructor; } /** * Gets the trait of the specified class if available. * * @param clzz Trait class to get. * @param <T> Type of trait. * @return Trait instance or null if trait is not present. */ @SuppressWarnings("unchecked") public <T extends Trait> T getTrait(Class<T> clzz) { return (T) traits.get(clzz); } /** * Gets the trait of the specified class if available. * * @param clzz Trait class to get. * @param <T> Type of trait. * @return Optional of trait instance. */ @SuppressWarnings("unchecked") public <T extends Trait> Optional<T> getOptionalTrait(Class<T> clzz) { return Optional.ofNullable((T) traits.get(clzz)); } /** * Gets the trait of the specified class, or throw {@link IllegalStateException} if not available. * * @param clzz Trait class to get. * @param <T> Type of trait. * @return Trait instance. * @throws IllegalStateException if trait is not present. */ @SuppressWarnings("unchecked") public <T extends Trait> T getRequiredTrait(Class<T> clzz) throws IllegalStateException { T trait = (T) traits.get(clzz); if (trait == null) { throw new IllegalStateException(memberName + " member is missing " + clzz.getSimpleName()); } return trait; } /** * Checks if a given {@link Trait} is present on the field. * * @param clzz Trait class to check. * @return True if trait is present, false if not. */ public boolean containsTrait(Class<? extends Trait> clzz) { return traits.containsKey(clzz); } /** * Retrieves the current value of 'this' field from the given POJO. Uses the getter passed into the {@link Builder}. * * @param pojo POJO to retrieve value from. * @return Current value of 'this' field in the POJO. */ private TypeT get(Object pojo) { return getter.apply(pojo); } /** * Retrieves the current value of 'this' field from the given POJO. Uses the getter passed into the {@link Builder}. If the * current value is null this method will look for the {@link DefaultValueTrait} on the field and attempt to resolve a default * value. If the {@link DefaultValueTrait} is not present this just returns null. * * @param pojo POJO to retrieve value from. * @return Current value of 'this' field in the POJO or default value if current value is null. */ public TypeT getValueOrDefault(Object pojo) { TypeT val = this.get(pojo); DefaultValueTrait trait = getTrait(DefaultValueTrait.class); return (trait == null ? val : (TypeT) trait.resolveValue(val)); } /** * Sets the given value on the POJO via the setter passed into the {@link Builder}. * * @param pojo POJO containing field to set. * @param val Value of field. */ @SuppressWarnings("unchecked") public void set(Object pojo, Object val) { setter.accept(pojo, (TypeT) val); } /** * Creates a new instance of {@link Builder} bound to the specified type. * * @param marshallingType Type of field. * @param <TypeT> Type of field. Must be a subtype of the {@link MarshallingType} type param. * @return New builder instance. */ public static <TypeT> Builder<TypeT> builder(MarshallingType<? super TypeT> marshallingType) { return new Builder<>(marshallingType); } /** * Builder for {@link SdkField}. * * @param <TypeT> Java type of field. */ public static final class Builder<TypeT> { private final MarshallingType<? super TypeT> marshallingType; private String memberName; private Supplier<SdkPojo> constructor; private BiConsumer<Object, TypeT> setter; private Function<Object, TypeT> getter; private final Map<Class<? extends Trait>, Trait> traits = new HashMap<>(); private Builder(MarshallingType<? super TypeT> marshallingType) { this.marshallingType = marshallingType; } public Builder<TypeT> memberName(String memberName) { this.memberName = memberName; return this; } /** * Sets a {@link Supplier} which will create a new <b>MUTABLE</b> instance of the POJO. I.E. this will * create the Builder for a given POJO and not the immutable POJO itself. * * @param constructor Supplier method to create the mutable POJO. * @return This object for method chaining. */ public Builder<TypeT> constructor(Supplier<SdkPojo> constructor) { this.constructor = constructor; return this; } /** * Sets the {@link BiConsumer} which will accept an object and a value and set that value on the appropriate * member of the object. This requires a <b>MUTABLE</b> pojo so thus this setter will be on the Builder * for the given POJO. * * @param setter Setter method. * @return This object for method chaining. */ public Builder<TypeT> setter(BiConsumer<Object, TypeT> setter) { this.setter = setter; return this; } /** * Sets the {@link Function} that will accept an object and return the current value of 'this' field on that object. * This will typically be a getter on the immutable representation of the POJO and is used mostly during marshalling. * * @param getter Getter method. * @return This object for method chaining. */ public Builder<TypeT> getter(Function<Object, TypeT> getter) { this.getter = getter; return this; } /** * Attaches one or more traits to the {@link SdkField}. Traits can have additional metadata and behavior that * influence how a field is marshalled/unmarshalled. * * @param traits Traits to attach. * @return This object for method chaining. */ public Builder<TypeT> traits(Trait... traits) { Arrays.stream(traits).forEach(t -> this.traits.put(t.getClass(), t)); return this; } /** * @return An immutable {@link SdkField}. */ public SdkField<TypeT> build() { return new SdkField<>(this); } } }
1,785
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/ClientType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Enum that represents the type of client being used. */ @SdkPublicApi public enum ClientType { ASYNC("Async"), SYNC("Sync"), UNKNOWN("Unknown"); private final String clientType; ClientType(String clientType) { this.clientType = clientType; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return clientType; } }
1,786
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkServiceClientConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.net.URI; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; /** * Class to expose SDK service client settings to the user, e.g., ClientOverrideConfiguration */ @SdkPublicApi public abstract class SdkServiceClientConfiguration { private final ClientOverrideConfiguration overrideConfiguration; private final URI endpointOverride; private final EndpointProvider endpointProvider; private final Map<String, AuthScheme<?>> authSchemes; protected SdkServiceClientConfiguration(Builder builder) { this.overrideConfiguration = builder.overrideConfiguration(); this.endpointOverride = builder.endpointOverride(); this.endpointProvider = builder.endpointProvider(); this.authSchemes = builder.authSchemes(); } /** * * @return The ClientOverrideConfiguration of the SdkClient. If this is not set, an ClientOverrideConfiguration object will * still be returned, with empty fields */ public ClientOverrideConfiguration overrideConfiguration() { return this.overrideConfiguration; } /** * * @return The configured endpoint override of the SdkClient. If the endpoint was not overridden, an empty Optional will be * returned */ public Optional<URI> endpointOverride() { return Optional.ofNullable(this.endpointOverride); } /** * * @return The configured endpoint provider of the SdkClient. If the endpoint provider was not configured, the default * endpoint provider will be returned. */ public Optional<EndpointProvider> endpointProvider() { return Optional.ofNullable(this.endpointProvider); } /** * @return The configured map of auth schemes. */ public Map<String, AuthScheme<?>> authSchemes() { return authSchemes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SdkServiceClientConfiguration serviceClientConfiguration = (SdkServiceClientConfiguration) o; return Objects.equals(overrideConfiguration, serviceClientConfiguration.overrideConfiguration()) && Objects.equals(endpointOverride, serviceClientConfiguration.endpointOverride().orElse(null)) && Objects.equals(endpointProvider, serviceClientConfiguration.endpointProvider().orElse(null)) && Objects.equals(authSchemes, serviceClientConfiguration.authSchemes); } @Override public int hashCode() { int result = overrideConfiguration != null ? overrideConfiguration.hashCode() : 0; result = 31 * result + (endpointOverride != null ? endpointOverride.hashCode() : 0); result = 31 * result + (endpointProvider != null ? endpointProvider.hashCode() : 0); result = 31 * result + (authSchemes != null ? authSchemes.hashCode() : 0); return result; } /** * The base interface for all SDK service client configuration builders */ public interface Builder { /** * Return the client override configuration */ default ClientOverrideConfiguration overrideConfiguration() { throw new UnsupportedOperationException(); } /** * Return the endpoint override */ default URI endpointOverride() { throw new UnsupportedOperationException(); } default EndpointProvider endpointProvider() { throw new UnsupportedOperationException(); } /** * Configure the client override configuration */ default Builder overrideConfiguration(ClientOverrideConfiguration clientOverrideConfiguration) { throw new UnsupportedOperationException(); } default Builder overrideConfiguration(Consumer<ClientOverrideConfiguration.Builder> consumer) { ClientOverrideConfiguration overrideConfiguration = overrideConfiguration(); ClientOverrideConfiguration.Builder builder; if (overrideConfiguration != null) { builder = overrideConfiguration.toBuilder(); } else { builder = ClientOverrideConfiguration.builder(); } consumer.accept(builder); return overrideConfiguration(builder.build()); } /** * Configure the endpoint override */ default Builder endpointOverride(URI endpointOverride) { throw new UnsupportedOperationException(); } default Builder endpointProvider(EndpointProvider endpointProvider) { throw new UnsupportedOperationException(); } /** * Adds the given auth scheme. Replaces an existing auth scheme with the same id. */ default Builder putAuthScheme(AuthScheme<?> authScheme) { throw new UnsupportedOperationException(); } /** * Returns the configured map of auth schemes. */ default Map<String, AuthScheme<?>> authSchemes() { throw new UnsupportedOperationException(); } /** * Build the service client configuration using the configuration on this builder */ SdkServiceClientConfiguration build(); } }
1,787
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/BytesWrapper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * A base class for {@link SdkBytes} and {@link ResponseBytes} that enables retrieving an underlying byte array as multiple * different types, like a byte buffer (via {@link #asByteBuffer()}, or a string (via {@link #asUtf8String()}. */ @SdkPublicApi public abstract class BytesWrapper { private final byte[] bytes; // Needed for serialization @SdkInternalApi BytesWrapper() { this(new byte[0]); } @SdkInternalApi BytesWrapper(byte[] bytes) { this.bytes = Validate.paramNotNull(bytes, "bytes"); } /** * @return The output as a read-only byte buffer. */ public final ByteBuffer asByteBuffer() { return ByteBuffer.wrap(bytes).asReadOnlyBuffer(); } /** * @return A copy of the output as a byte array. * @see #asByteBuffer() to prevent creating an additional array copy. */ public final byte[] asByteArray() { return Arrays.copyOf(bytes, bytes.length); } /** * @return The output as a byte array. This <b>does not</b> create a copy of the underlying byte array. This introduces * concurrency risks, allowing: (1) the caller to modify the byte array stored in this object implementation AND * (2) the original creator of this object, if they created it using the unsafe method. * * <p>Consider using {@link #asByteBuffer()}, which is a safer method to avoid an additional array copy because it does not * provide a way to modify the underlying buffer. As the method name implies, this is unsafe. If you're not sure, don't use * this. The only guarantees given to the user of this method is that the SDK itself won't modify the underlying byte * array.</p> * * @see #asByteBuffer() to prevent creating an additional array copy safely. */ public final byte[] asByteArrayUnsafe() { return bytes; } /** * Retrieve the output as a string. * * @param charset The charset of the string. * @return The output as a string. * @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded using the * provided charset */ public final String asString(Charset charset) throws UncheckedIOException { return StringUtils.fromBytes(bytes, charset); } /** * @return The output as a utf-8 encoded string. * @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded as UTF-8. */ public final String asUtf8String() throws UncheckedIOException { return asString(UTF_8); } /** * @return The output as an input stream. This stream will not need to be closed. */ public final InputStream asInputStream() { return new ByteArrayInputStream(bytes); } /** * @return The output as a {@link ContentStreamProvider}. */ public final ContentStreamProvider asContentStreamProvider() { return this::asInputStream; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BytesWrapper sdkBytes = (BytesWrapper) o; return Arrays.equals(bytes, sdkBytes.bytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } }
1,788
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkPojoBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.Buildable; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A builder for an immutable {@link SdkPojo} with no fields. * * <p> * This is useful for {@code SdkPojo} implementations that don't have their own builders, but need to be passed to something * that assumes they already have a builder. For example, marshallers expect all {@code SdkPojo} implementations to have a * builder. In the cases that they do not, this can be used as their builder. * * <p> * This currently only supports {@code SdkPojo}s without any fields (because it has no way to set them). It also does not support * {@code SdkPojo}s that already have or are a builder (that builder should be used instead). */ @SdkProtectedApi public final class SdkPojoBuilder<T extends SdkPojo> implements SdkPojo, Buildable { private final T delegate; public SdkPojoBuilder(T delegate) { Validate.isTrue(delegate.sdkFields().isEmpty(), "Delegate must be empty."); Validate.isTrue(!(delegate instanceof ToCopyableBuilder), "Delegate already has a builder."); Validate.isTrue(!(delegate instanceof Buildable), "Delegate is already a builder."); this.delegate = delegate; } @Override public List<SdkField<?>> sdkFields() { return Collections.emptyList(); } @Override public boolean equalsBySdkFields(Object other) { return delegate.equalsBySdkFields(other); } @Override public T build() { return delegate; } }
1,789
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/HttpChecksumConstant.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.internal.signer.SigningMethod; /** * Defines all the constants that are used while adding and validating Http checksum for an operation. */ @SdkInternalApi public final class HttpChecksumConstant { public static final String HTTP_CHECKSUM_HEADER_PREFIX = "x-amz-checksum"; public static final String X_AMZ_TRAILER = "x-amz-trailer"; public static final String CONTENT_SHA_256_FOR_UNSIGNED_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER"; public static final String AWS_CHUNKED_HEADER = "aws-chunked"; public static final ExecutionAttribute<String> HTTP_CHECKSUM_VALUE = new ExecutionAttribute<>("HttpChecksumValue"); public static final ExecutionAttribute<SigningMethod> SIGNING_METHOD = new ExecutionAttribute<>("SigningMethod"); public static final String HEADER_FOR_TRAILER_REFERENCE = "x-amz-trailer"; /** * Default chunk size for Async trailer based checksum data transfer* */ public static final int DEFAULT_ASYNC_CHUNK_SIZE = 16 * 1024; private HttpChecksumConstant() { } }
1,790
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkProtocolMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Interface to hold protocol-specific information. */ @SdkProtectedApi public interface SdkProtocolMetadata { String serviceProtocol(); }
1,791
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/SdkClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * All SDK service client interfaces should extend this interface. */ @SdkPublicApi @ThreadSafe public interface SdkClient extends SdkAutoCloseable { /** * The name of the service. * * @return name for this service. */ String serviceName(); /** * The SDK service client configuration exposes client settings to the user, e.g., ClientOverrideConfiguration * * @return SdkServiceClientConfiguration */ default SdkServiceClientConfiguration serviceClientConfiguration() { throw new UnsupportedOperationException(); } }
1,792
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/metrics/CoreMetric.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.metrics; import java.net.URI; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.metrics.MetricCategory; import software.amazon.awssdk.metrics.MetricLevel; import software.amazon.awssdk.metrics.SdkMetric; @SdkPublicApi public final class CoreMetric { /** * The unique ID for the service. This is present for all API call metrics. */ public static final SdkMetric<String> SERVICE_ID = metric("ServiceId", String.class, MetricLevel.ERROR); /** * The name of the service operation being invoked. This is present for all * API call metrics. */ public static final SdkMetric<String> OPERATION_NAME = metric("OperationName", String.class, MetricLevel.ERROR); /** * True if the API call succeeded, false otherwise. */ public static final SdkMetric<Boolean> API_CALL_SUCCESSFUL = metric("ApiCallSuccessful", Boolean.class, MetricLevel.ERROR); /** * The number of retries that the SDK performed in the execution of the request. 0 implies that the request worked the first * time, and no retries were attempted. */ public static final SdkMetric<Integer> RETRY_COUNT = metric("RetryCount", Integer.class, MetricLevel.ERROR); /** * The endpoint for the service. */ public static final SdkMetric<URI> SERVICE_ENDPOINT = metric("ServiceEndpoint", URI.class, MetricLevel.ERROR); /** * The duration of the API call. This includes all call attempts made. * * <p>{@code API_CALL_DURATION ~= CREDENTIALS_FETCH_DURATION + MARSHALLING_DURATION + SUM_ALL(BACKOFF_DELAY_DURATION) + * SUM_ALL(SIGNING_DURATION) + SUM_ALL(SERVICE_CALL_DURATION) + SUM_ALL(UNMARSHALLING_DURATION)} */ public static final SdkMetric<Duration> API_CALL_DURATION = metric("ApiCallDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to fetch signing credentials for the API call. */ public static final SdkMetric<Duration> CREDENTIALS_FETCH_DURATION = metric("CredentialsFetchDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to fetch signing credentials for the API call. */ public static final SdkMetric<Duration> TOKEN_FETCH_DURATION = metric("TokenFetchDuration", Duration.class, MetricLevel.INFO); /** * The duration of time that the SDK has waited before this API call attempt, based on the * {@link RetryPolicy#backoffStrategy()}. */ public static final SdkMetric<Duration> BACKOFF_DELAY_DURATION = metric("BackoffDelayDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to marshall the SDK request to an HTTP request. */ public static final SdkMetric<Duration> MARSHALLING_DURATION = metric("MarshallingDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to sign the HTTP request. */ public static final SdkMetric<Duration> SIGNING_DURATION = metric("SigningDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to connect to the service (or acquire a connection from the connection pool), send the * serialized request and receive the initial response (e.g. HTTP status code and headers). This DOES NOT include the time * taken to read the entire response from the service. */ public static final SdkMetric<Duration> SERVICE_CALL_DURATION = metric("ServiceCallDuration", Duration.class, MetricLevel.INFO); /** * The duration of time taken to unmarshall the HTTP response to an SDK response. * * <p>Note: For streaming operations, this does not include the time to read the response payload. */ public static final SdkMetric<Duration> UNMARSHALLING_DURATION = metric("UnmarshallingDuration", Duration.class, MetricLevel.INFO); /** * The request ID of the service request. */ public static final SdkMetric<String> AWS_REQUEST_ID = metric("AwsRequestId", String.class, MetricLevel.INFO); /** * The extended request ID of the service request. */ public static final SdkMetric<String> AWS_EXTENDED_REQUEST_ID = metric("AwsExtendedRequestId", String.class, MetricLevel.INFO); /** * The type of error that occurred for a call attempt. * <p> * The following are possible values: * <ul> * <li>Throttling - The service responded with a throttling error.</li> * <li>ServerError - The service responded with an error other than throttling.</li> * <li>ClientTimeout - A client timeout occurred, either at the API call level, or API call attempt level.</li> * <li>IO - An I/O error occurred.</li> * <li>Other - Catch-all for other errors that don't fall into the above categories.</li> * </ul> * <p> */ public static final SdkMetric<String> ERROR_TYPE = metric("ErrorType", String.class, MetricLevel.INFO); private CoreMetric() { } private static <T> SdkMetric<T> metric(String name, Class<T> clzz, MetricLevel level) { return SdkMetric.create(name, clzz, level, MetricCategory.CORE); } }
1,793
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/AsyncRequestBodySigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * Interface for the signer used for signing the async requests. */ @SdkPublicApi @FunctionalInterface public interface AsyncRequestBodySigner { /** * Method that takes in an signed request and async request body provider, * and returns a transformed version the request body provider. * * @param request The signed request (with Authentication header) * @param asyncRequestBody Data publisher of the request body * @param executionAttributes Contains the attributes required for signing the request * @return The transformed request body provider (with singing operator) */ AsyncRequestBody signAsyncRequestBody(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody, ExecutionAttributes executionAttributes); }
1,794
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/AsyncSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * A signer capable of including the contents of the asynchronous body into the request calculation. */ @SdkPublicApi public interface AsyncSigner { /** * Sign the request, including the contents of the body into the signature calculation. * * @param request The HTTP request. * @param requestBody The body of the request. * @param executionAttributes The execution attributes that contains information information used to sign the * request. * @return A future containing the signed request. */ CompletableFuture<SdkHttpFullRequest> sign(SdkHttpFullRequest request, AsyncRequestBody requestBody, ExecutionAttributes executionAttributes); }
1,795
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/Presigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * Interface for the signer used for pre-signing the requests. All SDK signer implementations that support pre-signing * will implement this interface. */ @SdkPublicApi @FunctionalInterface public interface Presigner { /** * Method that takes in an request and returns a pre signed version of the request. * * @param request The request to presign * @param executionAttributes Contains the attributes required for pre signing the request * @return A pre signed version of the input request */ SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); }
1,796
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/NoOpSigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * A No op implementation of Signer and Presigner interfaces that returns the * input {@link SdkHttpFullRequest} without modifications. */ @SdkPublicApi public final class NoOpSigner implements Signer, Presigner { @Override public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { return request; } @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { return request; } }
1,797
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/signer/Signer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * Interface for the signer used for signing the requests. All SDK signer implementations will implement this interface. */ @SdkPublicApi @FunctionalInterface public interface Signer { /** * Method that takes in an request and returns a signed version of the request. * * @param request The request to sign * @param executionAttributes Contains the attributes required for signing the request * @return A signed version of the input request */ SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes); /** * Method that retrieves {@link CredentialType} i.e. the type of Credentials used by the Signer while authorizing a request. * * @return null by default else return {@link CredentialType} as defined by the signer implementation. */ default CredentialType credentialType() { return null; } }
1,798
0
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination
Create_ds/aws-sdk-java-v2/core/sdk-core/src/main/java/software/amazon/awssdk/core/pagination/async/PaginationSubscription.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.pagination.async; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public abstract class PaginationSubscription<ResponseT> implements Subscription { protected AtomicLong outstandingRequests = new AtomicLong(0); protected final Subscriber subscriber; protected final AsyncPageFetcher<ResponseT> nextPageFetcher; protected volatile ResponseT currentPage; // boolean indicating whether subscription is terminated private AtomicBoolean isTerminated = new AtomicBoolean(false); // boolean indicating whether task to handle requests is running private AtomicBoolean isTaskRunning = new AtomicBoolean(false); protected PaginationSubscription(BuilderImpl builder) { this.subscriber = builder.subscriber; this.nextPageFetcher = builder.nextPageFetcher; } @Override public void request(long n) { if (isTerminated()) { return; } if (n <= 0) { subscriber.onError(new IllegalArgumentException("Non-positive request signals are illegal")); } AtomicBoolean startTask = new AtomicBoolean(false); synchronized (this) { outstandingRequests.addAndGet(n); startTask.set(startTask()); } if (startTask.get()) { handleRequests(); } } /** * Recursive method to deal with requests until there are no outstandingRequests or * no more pages. */ protected abstract void handleRequests(); @Override public void cancel() { cleanup(); } protected boolean hasNextPage() { return currentPage == null || nextPageFetcher.hasNextPage(currentPage); } protected void completeSubscription() { if (!isTerminated()) { subscriber.onComplete(); cleanup(); } } private void terminate() { isTerminated.compareAndSet(false, true); } protected boolean isTerminated() { return isTerminated.get(); } protected void stopTask() { isTaskRunning.set(false); } private synchronized boolean startTask() { return !isTerminated() && isTaskRunning.compareAndSet(false, true); } protected synchronized void cleanup() { terminate(); stopTask(); } public interface Builder<TypeToBuildT extends PaginationSubscription, BuilderT extends Builder> { BuilderT subscriber(Subscriber subscriber); BuilderT nextPageFetcher(AsyncPageFetcher nextPageFetcher); TypeToBuildT build(); } protected abstract static class BuilderImpl<TypeToBuildT extends PaginationSubscription, BuilderT extends Builder> implements Builder<TypeToBuildT, BuilderT> { private Subscriber subscriber; private AsyncPageFetcher nextPageFetcher; @Override public BuilderT subscriber(Subscriber subscriber) { this.subscriber = subscriber; return (BuilderT) this; } @Override public BuilderT nextPageFetcher(AsyncPageFetcher nextPageFetcher) { this.nextPageFetcher = nextPageFetcher; return (BuilderT) this; } } }
1,799