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/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/eventstream/EventStreamInitialRequestInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.when; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT; import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import io.reactivex.Flowable; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.Context.ModifyHttpRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class EventStreamInitialRequestInterceptorTest { static final String RPC_CONTENT_TYPE = "rpc-format"; Message eventMessage = getEventMessage(); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()); byte[] payload = "initial request payload".getBytes(StandardCharsets.UTF_8); ExecutionAttributes attr = new ExecutionAttributes().putAttribute(HAS_INITIAL_REQUEST_EVENT, true); EventStreamInitialRequestInterceptor interceptor = new EventStreamInitialRequestInterceptor(); @Test public void testHttpHeaderModification() { ModifyHttpRequest context = buildContext(bytePublisher, payload); SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(context, attr); List<String> contentType = modifiedRequest.headers().get(CONTENT_TYPE); assertEquals(1, contentType.size()); assertEquals(MIMETYPE_EVENT_STREAM, contentType.get(0)); } @Test public void testInitialRequestEvent() { ModifyHttpRequest context = buildContext(bytePublisher, payload); Optional<AsyncRequestBody> modifiedBody = interceptor.modifyAsyncHttpContent(context, attr); List<Message> messages = Flowable.fromPublisher(modifiedBody.get()).map(Message::decode).toList().blockingGet(); Message initialRequestEvent = messages.get(0); assertArrayEquals(payload, initialRequestEvent.getPayload()); assertEquals(RPC_CONTENT_TYPE, initialRequestEvent.getHeaders().get(":content-type").getString()); } @Test public void testPrepending() { ModifyHttpRequest context = buildContext(bytePublisher, payload); Optional<AsyncRequestBody> modifiedBody = interceptor.modifyAsyncHttpContent(context, attr); List<Message> messages = Flowable.fromPublisher(modifiedBody.get()).map(Message::decode).toList().blockingGet(); assertEquals(3, messages.size()); assertEquals(eventMessage, messages.get(1)); assertEquals(eventMessage, messages.get(2)); } @Test public void testDisabled() { ModifyHttpRequest context = buildContext(bytePublisher, payload); attr.putAttribute(HAS_INITIAL_REQUEST_EVENT, false); assertSame(context.httpRequest(), interceptor.modifyHttpRequest(context, attr)); assertSame(context.asyncRequestBody(), interceptor.modifyAsyncHttpContent(context, attr)); } private ModifyHttpRequest buildContext(Flowable<ByteBuffer> bytePublisher, byte[] payload) { SdkHttpFullRequest request = buildRequest(); ModifyHttpRequest context = Mockito.mock(ModifyHttpRequest.class); when(context.httpRequest()).thenReturn(request); when(context.asyncRequestBody()).thenReturn(Optional.of(AsyncRequestBody.fromPublisher(bytePublisher))); when(context.requestBody()).thenReturn(Optional.of(RequestBody.fromByteBuffer(ByteBuffer.wrap(payload)))); return context; } private SdkHttpFullRequest buildRequest() { return SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .uri(URI.create("https://example.com/")) .putHeader(CONTENT_TYPE, RPC_CONTENT_TYPE) .build(); } private Message getEventMessage() { Map<String, HeaderValue> headers = ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")); return new Message(headers, new byte[0]); } }
1,200
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/eventstream/EventStreamAsyncResponseTransformerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class EventStreamAsyncResponseTransformerTest { @Test public void multipleEventsInChunk_OnlyDeliversOneEvent() throws InterruptedException { Message eventMessage = new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")), new byte[0]); CountDownLatch latch = new CountDownLatch(1); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()) .doOnCancel(latch::countDown); AtomicInteger numEvents = new AtomicInteger(0); // Request one event then cancel Subscriber<Object> requestOneSubscriber = new Subscriber<Object>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(Object o) { numEvents.incrementAndGet(); subscription.cancel(); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }; AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> p.subscribe(requestOneSubscriber))) .eventResponseHandler((r, e) -> new Object()) .executor(Executors.newSingleThreadExecutor()) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); assertThat(numEvents) .as("Expected only one event to be delivered") .hasValue(1); } @Test public void devilSubscriber_requestDataAfterComplete() throws InterruptedException { Message eventMessage = new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("foo")), "helloworld".getBytes()); CountDownLatch latch = new CountDownLatch(1); Flowable<ByteBuffer> bytePublisher = Flowable.just(eventMessage.toByteBuffer(), eventMessage.toByteBuffer()); AtomicInteger numEvents = new AtomicInteger(0); Subscriber<Object> requestAfterCompleteSubscriber = new Subscriber<Object>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(Object o) { subscription.request(1); } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { // Should never ever do this in production! subscription.request(1); latch.countDown(); } }; AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> p.subscribe(requestAfterCompleteSubscriber))) .eventResponseHandler((r, e) -> numEvents.incrementAndGet()) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); assertThat(numEvents) .as("Expected only one event to be delivered") .hasValue(2); } @Test public void unknownExceptionEventsThrowException() { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":message-type", HeaderValue.fromString("exception")); headers.put(":exception-type", HeaderValue.fromString("modeledException")); headers.put(":content-type", HeaderValue.fromString("application/json")); verifyExceptionThrown(headers); } @Test public void errorEventsThrowException() { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":message-type", HeaderValue.fromString("error")); verifyExceptionThrown(headers); } @Test public void prepareReturnsNewFuture() { AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> {})) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); CompletableFuture<?> cf1 = transformer.prepare(); transformer.exceptionOccurred(new RuntimeException("Boom!")); assertThat(cf1.isCompletedExceptionally()).isTrue(); assertThat(transformer.prepare()).isNotEqualTo(cf1); } @Test(timeout = 2000) public void prepareResetsSubscriberRef() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); AtomicBoolean exceptionThrown = new AtomicBoolean(false); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler( onEventStream(p -> { try { p.subscribe(e -> {}); } catch (Throwable t) { exceptionThrown.set(true); } finally { latch.countDown(); } })) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); Flowable<ByteBuffer> bytePublisher = Flowable.empty(); CompletableFuture<Void> transformFuture = transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); transformFuture.join(); transformFuture = transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); transformFuture.join(); latch.await(); assertThat(exceptionThrown).isFalse(); } @Test public void erroneousExtraExceptionOccurredDoesNotSurfaceException() { AtomicLong numExceptions = new AtomicLong(0); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { } @Override public void exceptionOccurred(Throwable throwable) { numExceptions.incrementAndGet(); } @Override public void complete() { } }) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); transformer.prepare(); transformer.exceptionOccurred(new RuntimeException("Boom!")); transformer.exceptionOccurred(new RuntimeException("Boom again!")); assertThat(numExceptions).hasValue(1); } // Test that the class guards against signalling exceptionOccurred if the stream is already complete. @Test public void erroneousExceptionOccurredAfterCompleteDoesNotSurfaceException() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Subscriber<Object> subscriber = new Subscriber<Object>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(1); } @Override public void onNext(Object o) { } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { latch.countDown(); } }; AtomicLong numExceptionOccurredCalls = new AtomicLong(0); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { publisher.subscribe(subscriber); } @Override public void exceptionOccurred(Throwable throwable) { numExceptionOccurredCalls.incrementAndGet(); } @Override public void complete() { latch.countDown(); } }) .eventResponseHandler((r, e) -> null) .executor(Executors.newFixedThreadPool(2)) .future(new CompletableFuture<>()) .build(); Flowable<ByteBuffer> bytePublisher = Flowable.empty(); transformer.prepare(); transformer.onStream(SdkPublisher.adapt(bytePublisher)); latch.await(); transformer.exceptionOccurred(new RuntimeException("Uh-oh")); assertThat(numExceptionOccurredCalls) .as("Expected only one event to be delivered") .hasValue(0); } private void verifyExceptionThrown(Map<String, HeaderValue> headers) { SdkServiceException exception = SdkServiceException.builder().build(); Message exceptionMessage = new Message(headers, new byte[0]); Flowable<ByteBuffer> bytePublisher = Flowable.just(exceptionMessage.toByteBuffer()); SubscribingResponseHandler handler = new SubscribingResponseHandler(); AsyncResponseTransformer<SdkResponse, Void> transformer = EventStreamAsyncResponseTransformer.builder() .eventStreamResponseHandler(handler) .exceptionResponseHandler((response, executionAttributes) -> exception) .executor(Executors.newSingleThreadExecutor()) .future(new CompletableFuture<>()) .build(); CompletableFuture<Void> cf = transformer.prepare(); transformer.onResponse(null); transformer.onStream(SdkPublisher.adapt(bytePublisher)); assertThatThrownBy(() -> { try { cf.join(); } catch (CompletionException e) { if (e.getCause() instanceof SdkServiceException) { throw e.getCause(); } } }).isSameAs(exception); assertThat(handler.exceptionOccurredCalled).isTrue(); } private static class SubscribingResponseHandler implements EventStreamResponseHandler<Object, Object> { private volatile boolean exceptionOccurredCalled = false; @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { publisher.subscribe(e -> { }); } @Override public void exceptionOccurred(Throwable throwable) { exceptionOccurredCalled = true; } @Override public void complete() { } } public EventStreamResponseHandler<Object, Object> onEventStream(Consumer<SdkPublisher<Object>> onEventStream) { return new EventStreamResponseHandler<Object, Object>() { @Override public void responseReceived(Object response) { } @Override public void onEventStream(SdkPublisher<Object> publisher) { onEventStream.accept(publisher); } @Override public void exceptionOccurred(Throwable throwable) { } @Override public void complete() { } }; } }
1,201
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/retry/RetryOnErrorCodeConditionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Sets; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.awscore.retry.conditions.RetryOnErrorCodeCondition; import software.amazon.awssdk.core.retry.RetryPolicyContext; public class RetryOnErrorCodeConditionTest { private RetryOnErrorCodeCondition condition = RetryOnErrorCodeCondition.create(Sets.newHashSet("Foo", "Bar")); @Test public void noExceptionInContext_ReturnsFalse() { assertFalse(shouldRetry(builder -> builder.exception(null))); } @Test public void retryableErrorCodes_ReturnsTrue() { assertTrue(shouldRetry(applyErrorCode("Foo"))); assertTrue(shouldRetry(applyErrorCode("Bar"))); } @Test public void nonRetryableErrorCode_ReturnsFalse() { assertFalse(shouldRetry(applyErrorCode("HelloWorld"))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return condition.shouldRetry(RetryPolicyContext.builder().applyMutation(builder).build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) { AwsServiceException.Builder exception = AwsServiceException.builder(); exception.statusCode(404); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build()); return b -> b.exception(exception.build()); } }
1,202
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/retry/AwsRetryPolicyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry; import static java.time.temporal.ChronoUnit.HOURS; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static software.amazon.awssdk.awscore.retry.AwsRetryPolicy.defaultRetryCondition; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.NonRetryableException; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.DateUtils; public class AwsRetryPolicyTest { @Test public void retriesOnRetryableErrorCodes() { assertTrue(shouldRetry(applyErrorCode("PriorRequestNotComplete"))); } @Test public void retriesOnThrottlingExceptions() { assertTrue(shouldRetry(applyErrorCode("ThrottlingException"))); assertTrue(shouldRetry(applyErrorCode("ThrottledException"))); assertTrue(shouldRetry(applyStatusCode(429))); } @Test public void retriesOnClockSkewErrors() { assertTrue(shouldRetry(applyErrorCode("RequestTimeTooSkewed"))); assertTrue(shouldRetry(applyErrorCode("AuthFailure", Duration.ZERO, Instant.now().minus(1, HOURS)))); } @Test public void retriesOnInternalError() { assertTrue(shouldRetry(applyStatusCode(500))); } @Test public void retriesOnBadGateway() { assertTrue(shouldRetry(applyStatusCode(502))); } @Test public void retriesOnServiceUnavailable() { assertTrue(shouldRetry(applyStatusCode(503))); } @Test public void retriesOnGatewayTimeout() { assertTrue(shouldRetry(applyStatusCode(504))); } @Test public void retriesOnIOException() { assertTrue(shouldRetry(b -> b.exception(SdkClientException.builder() .message("IO") .cause(new IOException()) .build()))); } @Test public void retriesOnRetryableException() { assertTrue(shouldRetry(b -> b.exception(RetryableException.builder().build()))); } @Test public void doesNotRetryOnNonRetryableException() { assertFalse(shouldRetry(b -> b.exception(NonRetryableException.builder().build()))); } @Test public void doesNotRetryOnNonRetryableStatusCode() { assertFalse(shouldRetry(applyStatusCode(404))); } @Test public void doesNotRetryOnNonRetryableErrorCode() { assertFalse(shouldRetry(applyErrorCode("ValidationError"))); } @Test public void retriesOnEC2ThrottledException() { AwsServiceException ex = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorCode("EC2ThrottledException") .build()) .build(); assertTrue(shouldRetry(b -> b.exception(ex))); } private boolean shouldRetry(Consumer<RetryPolicyContext.Builder> builder) { return defaultRetryCondition().shouldRetry(RetryPolicyContext.builder().applyMutation(builder).build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode) { AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(404); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode(errorCode).build()); return b -> b.exception(exception.build()); } private Consumer<RetryPolicyContext.Builder> applyErrorCode(String errorCode, Duration clockSkew, Instant dateHeader) { SdkHttpFullResponse response = SdkHttpFullResponse.builder() .putHeader("Date", DateUtils.formatRfc822Date(dateHeader)) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode(errorCode) .sdkHttpResponse(response) .build(); AwsServiceException.Builder exception = AwsServiceException.builder() .statusCode(404) .awsErrorDetails(errorDetails) .clockSkew(clockSkew); return b -> b.exception(exception.build()); } private Consumer<RetryPolicyContext.Builder> applyStatusCode(Integer statusCode) { AwsServiceException.Builder exception = AwsServiceException.builder().statusCode(statusCode); exception.awsErrorDetails(AwsErrorDetails.builder().errorCode("Foo").build()); return b -> b.exception(exception.build()) .httpStatusCode(statusCode); } }
1,203
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/TestWrapperSchedulerService.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import software.amazon.awssdk.utils.ThreadFactoryBuilder; /** * Test Scheduler class to Spy on default implementation of ScheduledExecutorService. */ public class TestWrapperSchedulerService implements ScheduledExecutorService { ScheduledExecutorService scheduledExecutorService; public TestWrapperSchedulerService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return scheduledExecutorService.schedule(command,delay,unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return scheduledExecutorService.schedule(callable,delay,unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return scheduledExecutorService.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return scheduledExecutorService.scheduleAtFixedRate(command,initialDelay,delay,unit); } @Override public void shutdown() { scheduledExecutorService.shutdown(); } @Override public List<Runnable> shutdownNow() { return scheduledExecutorService.shutdownNow(); } @Override public boolean isShutdown() { return scheduledExecutorService.isShutdown(); } @Override public boolean isTerminated() { return scheduledExecutorService.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return scheduledExecutorService.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { return scheduledExecutorService.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return scheduledExecutorService.submit(task,result); } @Override public Future<?> submit(Runnable task) { return scheduledExecutorService.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return scheduledExecutorService.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return scheduledExecutorService.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return scheduledExecutorService.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return scheduledExecutorService.invokeAny(tasks,timeout,unit); } @Override public void execute(Runnable command) { scheduledExecutorService.execute(command); } }
1,204
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/SignerOverrideUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.http.NoopTestAwsRequest; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.Pair; class SignerOverrideUtilsTest { @Test @DisplayName("If signer is already overridden, assert that it is not modified") void overrideSignerIfNotOverridden() { Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(new FooSigner()); SdkRequest request = stubs.left(); ExecutionAttributes executionAttributes = stubs.right(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, BarSigner::new); assertThat(result.overrideConfiguration()).isPresent(); assertThat(result.overrideConfiguration().get().signer().get()).isInstanceOf(FooSigner.class); } @Test @DisplayName("If signer is not already overridden, assert that it is overridden with the new signer") void overrideSignerIfNotOverridden2() { Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(null); SdkRequest request = stubs.left(); ExecutionAttributes executionAttributes = stubs.right(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, BarSigner::new); assertThat(result.overrideConfiguration()).isPresent(); assertThat(result.overrideConfiguration().get().signer().get()).isInstanceOf(BarSigner.class); } @Test @DisplayName("If signer will be overridden, assert that the other existing override configuration properties are preserved") public void overrideSignerOriginalConfigPreserved() { AwsRequestOverrideConfiguration originalOverride = AwsRequestOverrideConfiguration.builder() .putHeader("Header1", "HeaderValue1") .putRawQueryParameter("QueryParam1", "QueryValue1") .addApiName(ApiName.builder().name("foo").version("bar").build()) .build(); Pair<SdkRequest, ExecutionAttributes> stubs = stubInitialSigner(null); SdkRequest request = ((AwsRequest) stubs.left()).toBuilder() .overrideConfiguration(originalOverride) .build(); ExecutionAttributes executionAttributes = stubs.right(); BarSigner overrideSigner = new BarSigner(); SdkRequest result = SignerOverrideUtils.overrideSignerIfNotOverridden(request, executionAttributes, () -> overrideSigner); AwsRequestOverrideConfiguration originalOverrideWithNewSigner = originalOverride.toBuilder() .signer(overrideSigner) .build(); assertThat(result.overrideConfiguration().get()).isEqualTo(originalOverrideWithNewSigner); } private static Pair<SdkRequest, ExecutionAttributes> stubInitialSigner(Signer signer) { AwsRequest request; if (signer != null) { AwsRequestOverrideConfiguration config = AwsRequestOverrideConfiguration.builder() .signer(signer) .build(); request = NoopTestAwsRequest.builder() .overrideConfiguration(config) .build(); } else { request = NoopTestAwsRequest.builder().build(); } ExecutionAttributes executionAttributes = new ExecutionAttributes(); if (signer != null) { executionAttributes.putAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN, true); } return Pair.of(request, executionAttributes); } private static class FooSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { throw new UnsupportedOperationException(); } } private static class BarSigner implements Signer { @Override public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) { throw new UnsupportedOperationException(); } } }
1,205
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/util/AwsHostNameUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.awscore.util.AwsHostNameUtils.parseSigningRegion; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; /** Unit tests for the utility methods that parse information from AWS URLs. */ public class AwsHostNameUtilsTest { @Test public void testStandardNoHint() { // Verify that standard endpoints parse correctly without a service hint assertThat(parseSigningRegion("iam.amazonaws.com", null)).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", null)).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", null)).hasValue(Region.US_WEST_2); } @Test public void testStandard() { // Verify that standard endpoints parse correctly with a service hint assertThat(parseSigningRegion("iam.amazonaws.com", "iam")).hasValue(Region.US_EAST_1); assertThat(parseSigningRegion("iam.us-west-2.amazonaws.com", "iam")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("ec2.us-west-2.amazonaws.com", "ec2")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("cloudsearch.us-west-2.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); assertThat(parseSigningRegion("domain.us-west-2.cloudsearch.amazonaws.com", "cloudsearch")).hasValue(Region.US_WEST_2); } @Test public void testBjs() { // Verify that BJS endpoints parse correctly even though they're non-standard. assertThat(parseSigningRegion("iam.cn-north-1.amazonaws.com.cn", "iam")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("ec2.cn-north-1.amazonaws.com.cn", "ec2")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("bucket.name.with.periods.s3.cn-north-1.amazonaws.com.cn", "s3")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("cloudsearch.cn-north-1.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); assertThat(parseSigningRegion("domain.cn-north-1.cloudsearch.amazonaws.com.cn", "cloudsearch")).hasValue(Region.CN_NORTH_1); } @Test public void testParseRegionWithIpv4() { assertThat(parseSigningRegion("54.231.16.200", null)).isNotPresent(); } }
1,206
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/AwsExecutionContextBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import static org.assertj.core.api.Assertions.assertThat; 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 java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; 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.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.checksums.ChecksumSpecs; 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.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.core.internal.util.HttpChecksumUtils; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.profiles.ProfileFile; @RunWith(MockitoJUnitRunner.class) public class AwsExecutionContextBuilderTest { @Mock SdkRequest sdkRequest; @Mock ExecutionInterceptor interceptor; @Mock IdentityProvider<AwsCredentialsIdentity> defaultCredentialsProvider; @Mock Signer defaultSigner; @Mock Signer clientOverrideSigner; @Mock Map<String, AuthScheme<?>> defaultAuthSchemes; @Before public void setUp() throws Exception { when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); when(interceptor.modifyRequest(any(), any())).thenReturn(sdkRequest); when(defaultCredentialsProvider.resolveIdentity()).thenAnswer( invocationOnMock -> CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk"))); } @Test public void verifyInterceptors() { AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); verify(interceptor, times(1)).beforeExecution(any(), any()); verify(interceptor, times(1)).modifyRequest(any(), any()); } @Test public void verifyCoreExecutionAttributesTakePrecedence() { ExecutionAttributes requestOverrides = ExecutionAttributes.builder() .put(SdkExecutionAttribute.SERVICE_NAME, "RequestOverrideServiceName") .build(); Optional requestOverrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .executionAttributes(requestOverrides) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(requestOverrideConfiguration); ExecutionAttributes clientConfigOverrides = ExecutionAttributes.builder() .put(SdkExecutionAttribute.SERVICE_NAME, "ClientConfigServiceName") .build(); SdkClientConfiguration testClientConfiguration = testClientConfiguration() .option(SdkClientOption.SERVICE_NAME, "DoNotOverrideService") .option(SdkClientOption.EXECUTION_ATTRIBUTES, clientConfigOverrides) .build(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration); assertThat(executionContext.executionAttributes().getAttribute(SdkExecutionAttribute.SERVICE_NAME)).isEqualTo("DoNotOverrideService"); } // pre SRA, AuthorizationStrategy would setup the signer and resolve identity. @Test public void preSra_signing_ifNoOverrides_assignDefaultSigner_resolveIdentity() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), preSraClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(defaultSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } // This is post SRA case. This is asserting that AuthorizationStrategy is not used. @Test public void postSra_ifNoOverrides_doesNotResolveIdentity_doesNotAssignSigner() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_signing_ifClientOverride_assignClientOverrideSigner_resolveIdentity() { Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), preSraClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(clientOverrideSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } @Test public void postSra_signing_ifClientOverride_assignClientOverrideSigner_resolveIdentity() { Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); assertThat(executionContext.signer()).isEqualTo(clientOverrideSigner); verify(defaultCredentialsProvider, times(1)).resolveIdentity(); } @Test public void preSra_authTypeNone_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_authTypeNone_signerClientOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); clientConfig.option(SdkAdvancedClientOption.SIGNER, this.clientOverrideSigner) .option(SdkClientOption.SIGNER_OVERRIDDEN, true); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_signerClientOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); clientConfig.option(SdkAdvancedClientOption.SIGNER, this.clientOverrideSigner) .option(SdkClientOption.SIGNER_OVERRIDDEN, true); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void preSra_authTypeNone_signerRequestOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = preSraClientConfiguration(); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) // yes, our code would put false instead of true .putAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST, false); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void postSra_authTypeNone_signerRequestOverride_doesNotAssignSigner_doesNotResolveIdentity() { SdkClientConfiguration.Builder clientConfig = noAuthAuthSchemeClientConfiguration(); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder() .signer(clientOverrideSigner) .build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), clientConfig.build()); assertThat(executionContext.signer()).isNull(); verify(defaultCredentialsProvider, times(0)).resolveIdentity(); } @Test public void invokeInterceptorsAndCreateExecutionContext_noHttpChecksumTrait_resolvesChecksumSpecs() { ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(clientExecutionParams(), testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); Optional<ChecksumSpecs> checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes); Optional<ChecksumSpecs> checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes); assertThat(checksumSpecs1).isNotPresent(); assertThat(checksumSpecs2).isNotPresent(); assertThat(checksumSpecs1).isSameAs(checksumSpecs2); } @Test public void invokeInterceptorsAndCreateExecutionContext_singleExecutionContext_resolvesEqualChecksumSpecs() { HttpChecksum httpCrc32Checksum = HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build(); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams() .putExecutionAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, httpCrc32Checksum); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); ChecksumSpecs checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).get(); ChecksumSpecs checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).get(); assertThat(checksumSpecs1).isEqualTo(checksumSpecs2); } @Test public void invokeInterceptorsAndCreateExecutionContext_multipleExecutionContexts_resolvesEqualChecksumSpecs() { HttpChecksum httpCrc32Checksum = HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build(); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams() .putExecutionAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, httpCrc32Checksum); SdkClientConfiguration clientConfig = testClientConfiguration().build(); ExecutionContext executionContext1 = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes1 = executionContext1.executionAttributes(); ChecksumSpecs checksumSpecs1 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes1).get(); ExecutionContext executionContext2 = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes2 = executionContext2.executionAttributes(); ChecksumSpecs checksumSpecs2 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes2).get(); ChecksumSpecs checksumSpecs3 = HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes2).get(); assertThat(checksumSpecs1).isEqualTo(checksumSpecs2); assertThat(checksumSpecs2).isEqualTo(checksumSpecs3); } @Test public void invokeInterceptorsAndCreateExecutionContext_profileFileSupplier_storesValueInExecutionAttributes() { ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); Supplier<ProfileFile> profileFileSupplier = () -> null; SdkClientConfiguration clientConfig = testClientConfiguration() .option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFileSupplier) .build(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); assertThat(profileFileSupplier).isSameAs(executionAttributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER)); } @Test public void invokeInterceptorsAndCreateExecutionContext_withoutIdentityProviders_assignsNull() { ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, testClientConfiguration().build()); ExecutionAttributes executionAttributes = executionContext.executionAttributes(); assertThat(executionAttributes.getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS)).isNull(); } @Test public void invokeInterceptorsAndCreateExecutionContext_requestOverrideForIdentityProvider_updatesIdentityProviders() { IdentityProvider<? extends AwsCredentialsIdentity> clientCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("foo", "bar")); IdentityProviders identityProviders = IdentityProviders.builder().putIdentityProvider(clientCredentialsProvider).build(); SdkClientConfiguration clientConfig = testClientConfiguration() .option(SdkClientOption.IDENTITY_PROVIDERS, identityProviders) .build(); IdentityProvider<? extends AwsCredentialsIdentity> requestCredentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); Optional overrideConfiguration = Optional.of(AwsRequestOverrideConfiguration.builder().credentialsProvider(requestCredentialsProvider).build()); when(sdkRequest.overrideConfiguration()).thenReturn(overrideConfiguration); ClientExecutionParams<SdkRequest, SdkResponse> executionParams = clientExecutionParams(); ExecutionContext executionContext = AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfig); IdentityProviders actualIdentityProviders = executionContext.executionAttributes().getAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS); IdentityProvider<AwsCredentialsIdentity> actualIdentityProvider = actualIdentityProviders.identityProvider(AwsCredentialsIdentity.class); assertThat(actualIdentityProvider).isSameAs(requestCredentialsProvider); } private ClientExecutionParams<SdkRequest, SdkResponse> clientExecutionParams() { return new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(sdkRequest) .withFullDuplex(false) .withOperationName("TestOperation"); } private SdkClientConfiguration.Builder testClientConfiguration() { // In real SRA case, SelectedAuthScheme is setup as an executionAttribute by {Service}AuthSchemeInterceptor that is setup // in EXECUTION_INTERCEPTORS. But, faking it here for unit test, by already setting SELECTED_AUTH_SCHEME into the // executionAttributes. SelectedAuthScheme<?> selectedAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk")), mock(HttpSigner.class), AuthSchemeOption.builder().schemeId(AwsV4AuthScheme.SCHEME_ID).build() ); ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, selectedAuthScheme) .build(); List<ExecutionInterceptor> interceptorList = Collections.singletonList(interceptor); return SdkClientConfiguration.builder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, interceptorList) .option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, defaultCredentialsProvider) .option(SdkClientOption.AUTH_SCHEMES, defaultAuthSchemes) .option(SdkClientOption.EXECUTION_ATTRIBUTES, executionAttributes); } private SdkClientConfiguration.Builder noAuthAuthSchemeClientConfiguration() { SdkClientConfiguration.Builder clientConfig = testClientConfiguration(); SelectedAuthScheme<?> selectedNoAuthScheme = new SelectedAuthScheme<>( CompletableFuture.completedFuture(AwsCredentialsIdentity.create("ak", "sk")), mock(HttpSigner.class), AuthSchemeOption.builder().schemeId(NoAuthAuthScheme.SCHEME_ID).build() ); clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES) .putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, selectedNoAuthScheme); return clientConfig; } private SdkClientConfiguration.Builder preSraClientConfiguration() { SdkClientConfiguration.Builder clientConfiguration = testClientConfiguration(); clientConfiguration.option(SdkClientOption.EXECUTION_ATTRIBUTES) .putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); return clientConfiguration.option(SdkClientOption.AUTH_SCHEMES, null) .option(SdkAdvancedClientOption.SIGNER, this.defaultSigner); } }
1,207
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/CachedTokenRefresherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.atMost; 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.time.Duration; import java.time.Instant; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; public class CachedTokenRefresherTest { @Test public void doNotRefresh_when_valueIsNotStale() { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().plus(Duration.ofMillis(10000))).build(); TestToken token2 = TestToken.builder().token("token2").expirationDate(Instant.now().plus(Duration.ofMillis(900))).build(); when(supplier.get()).thenReturn(token1) .thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(99)) .tokenRetriever(supplier) .build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token1); } @Test public void refresh_when_valueIsStale() { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().minus(Duration.ofMillis(1))).build(); TestToken token2 = TestToken.builder().token("token2").expirationDate(Instant.now().plus(Duration.ofMillis(900))).build(); when(supplier.get()).thenReturn(token1) .thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(99)) .tokenRetriever(supplier) .build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token2); } @Test public void refreshTokenFails_when_exceptionHandlerThrowsBackException() { Function<RuntimeException, TestToken> fun = e -> { throw e; }; CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(fun) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); assertThatExceptionOfType(SdkException.class) .isThrownBy(() -> tokenRefresher.refreshIfStaleAndFetch()).withMessage("Auth Failure"); } @Test public void refreshTokenPasses_when_exceptionHandlerSkipsException() throws ExecutionException, InterruptedException { TestToken initialToken = getTestTokenBuilder().token("OldToken").expirationDate(Instant.now()).build(); CachedTokenRefresher<TestToken> tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(e -> initialToken) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); TestToken testToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(testToken).isEqualTo(initialToken); assertThat(testToken.token()).isEqualTo("OldToken"); assertThat(initialToken).isEqualTo(testToken); } @Test public void refreshTokenFails_when_baseTokenIsNotInTokenManagerWhileTokenFailedToObtainFromService() { Function<RuntimeException, TestToken> handleException = e -> { // handle Exception throws back another exception while handling the exception. throw new IllegalStateException("Unable to load token from Disc"); }; CachedTokenRefresher tokenRefresher = tokenRefresherBuilder() .staleDuration(Duration.ofMillis(101)) .exceptionHandler(handleException) .tokenRetriever(() -> { throw SdkException.create("Auth Failure", SdkClientException.create("Error")); }) .build(); assertThatExceptionOfType(IllegalStateException.class) .isThrownBy(() -> tokenRefresher.refreshIfStaleAndFetch()).withMessage("Unable to load token from Disc"); } @Test public void autoRefresheToken_when_tokensExpire() throws InterruptedException { Supplier<TestToken> testTokenSupplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").expirationDate(Instant.now().minus(Duration.ofMillis(10000))).build(); TestToken token3 = TestToken.builder().token("token3").expirationDate(Instant.now().plus(Duration.ofDays(1))).build(); when(testTokenSupplier.get()).thenReturn(token1).thenReturn(token1).thenReturn(token3); CachedTokenRefresher tokenRefresher = CachedTokenRefresher.builder() .tokenRetriever(testTokenSupplier). staleDuration(Duration.ofMillis(100)) .prefetchTime(Duration.ofMillis(110)) .build(); Thread.sleep(400); verify(testTokenSupplier, atMost(3)).get(); } @Test public void prefetchToken_whenTokenNotStale_and_withinPrefetchTime() throws InterruptedException { Supplier<TestToken> mockCache = mock(Supplier.class); Instant startInstance = Instant.now(); TestToken firstToken = TestToken.builder().token("firstToken").expirationDate(startInstance.plusSeconds(1)).build(); TestToken secondToken = TestToken.builder().token("secondTokenWithinStaleTime").expirationDate(startInstance.plusSeconds(1)).build(); TestToken thirdToken = TestToken.builder().token("thirdTokenOutsidePrefetchTime").expirationDate(startInstance.plusMillis(1500)).build(); TestToken fourthToken = TestToken.builder().token("thirdTokenOutsidePrefetchTime").expirationDate(Instant.now().plusSeconds(6000)).build(); when(mockCache.get()).thenReturn(firstToken) .thenReturn(secondToken) .thenReturn(thirdToken) .thenReturn(fourthToken); CachedTokenRefresher cachedTokenRefresher = CachedTokenRefresher.builder() .asyncRefreshEnabled(true) .staleDuration(Duration.ofMillis(1000)) .tokenRetriever(mockCache) .prefetchTime(Duration.ofMillis(1500)) .build(); // Sleep is invoked to make sure executor executes refresh in initializeCachedSupplier() in NonBlocking CachedSupplier.PrefetchStrategy Thread.sleep(1000); verify(mockCache, times(0)).get(); SdkToken firstRetrieved = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRetrieved).isEqualTo(firstToken); Thread.sleep(1000); // Sleep to make sure the Async prefetch thread is picked up verify(mockCache, times(1)).get(); SdkToken secondRetrieved = cachedTokenRefresher.refreshIfStaleAndFetch(); // Note that since the token has already been prefetched mockCache.get() is not called again thus it is secondToken. assertThat(secondRetrieved).isEqualTo(secondToken); Thread.sleep(1000); // Sleep to make sure the Async prefetch thread is picked up verify(mockCache, times(2)).get(); SdkToken thirdRetrievedToken = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(thirdRetrievedToken).isEqualTo(thirdToken); // Sleep to make sure the Async prefetch thread is picked up Thread.sleep(1000); verify(mockCache, times(3)).get(); SdkToken fourthRetrievedToken = cachedTokenRefresher.refreshIfStaleAndFetch(); assertThat(fourthRetrievedToken).isEqualTo(fourthToken); // Sleep to make sure the Async prefetch thread is picked up Thread.sleep(1000); verify(mockCache, times(4)).get(); SdkToken fifthToken = cachedTokenRefresher.refreshIfStaleAndFetch(); // Note that since Fourth token's expiry date is too high the prefetch is no longer done and the last fetch token is used. verify(mockCache, times(4)).get(); assertThat(fifthToken).isEqualTo(fourthToken); } @Test public void refreshEveryTime_when_ExpirationDateDoesNotExist() throws InterruptedException { Supplier<TestToken> supplier = mock(Supplier.class); TestToken token1 = TestToken.builder().token("token1").build(); TestToken token2 = TestToken.builder().token("token2").build(); when(supplier.get()).thenReturn(token1).thenReturn(token2); CachedTokenRefresher tokenRefresher = tokenRefresherBuilder().tokenRetriever(supplier).build(); SdkToken firstRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(firstRefreshToken).isEqualTo(token1); Thread.sleep(1000); SdkToken secondRefreshToken = tokenRefresher.refreshIfStaleAndFetch(); assertThat(secondRefreshToken).isEqualTo(token2); } private TestAwsResponse.Builder getDefaultTestAwsResponseBuilder() { return TestAwsResponse.builder().accessToken("serviceToken") .expiryTime(Instant.ofEpochMilli(1743680000000L)).startUrl("new_start_url"); } private CachedTokenRefresher.Builder tokenRefresherBuilder() { return CachedTokenRefresher.builder(); } private TestToken.Builder getTestTokenBuilder() { return TestToken.builder().token("sampleToken") .start_url("start_url"); } }
1,208
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/TestToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.time.Instant; import java.util.Optional; import software.amazon.awssdk.auth.token.credentials.SdkToken; public class TestToken implements SdkToken { private final String token; private final Instant expirationDate; private final String start_url; public static Builder builder() { return new Builder(); } public TestToken(Builder builder) { this.token = builder.token; this.start_url = builder.start_url; this.expirationDate = builder.expirationDate; } @Override public String token() { return token; } @Override public Optional<Instant> expirationTime() { return Optional.ofNullable(expirationDate); } public static class Builder { private String token; private Instant expirationDate; private String start_url; public Builder token(String token) { this.token = token; return this; } public Builder expirationDate(Instant expirationDate) { this.expirationDate = expirationDate; return this; } public Builder start_url(String start_url) { this.start_url = start_url; return this; } public TestToken build() { return new TestToken(this); } } }
1,209
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/token/TestAwsResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.time.Instant; import java.util.List; import software.amazon.awssdk.awscore.AwsResponse; import software.amazon.awssdk.core.SdkField; public class TestAwsResponse extends AwsResponse { private final String accessToken; private final Instant expiryTime; private final String startUrl; protected TestAwsResponse(Builder builder) { super(builder); this.accessToken = builder.accessToken; this.expiryTime = builder.expiryTime; this.startUrl = builder.startUrl; } public String getAccessToken() { return accessToken; } public Instant getExpiryTime() { return expiryTime; } public String getStartUrl() { return startUrl; } public static Builder builder(){ return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } @Override public List<SdkField<?>> sdkFields() { return null; } public static class Builder extends BuilderImpl{ public Builder() { } private String accessToken; private Instant expiryTime; private String startUrl; public Builder(TestAwsResponse testAwsResponse) { this.accessToken = testAwsResponse.accessToken; this.expiryTime = testAwsResponse.expiryTime; this.startUrl = testAwsResponse.startUrl; } public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } public Builder expiryTime(Instant expiryTime) { this.expiryTime = expiryTime; return this; } public Builder startUrl(String startUrl) { this.startUrl = startUrl; return this; } @Override public TestAwsResponse build() { return new TestAwsResponse(this); } } }
1,210
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/AutoDefaultsModeDiscoveryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.JavaSystemSetting; @RunWith(Parameterized.class) public class AutoDefaultsModeDiscoveryTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Mobile new TestData().clientRegion(Region.US_EAST_1) .javaVendorProperty("The Android Project") .awsExecutionEnvVar("AWS_Lambda_java8") .awsRegionEnvVar("us-east-1") .expectedResolvedMode(DefaultsMode.MOBILE), // Region available from AWS execution environment new TestData().clientRegion(Region.US_EAST_1) .awsExecutionEnvVar("AWS_Lambda_java8") .awsRegionEnvVar("us-east-1") .expectedResolvedMode(DefaultsMode.IN_REGION), // Region available from AWS execution environment new TestData().clientRegion(Region.US_EAST_1) .awsExecutionEnvVar("AWS_Lambda_java8") .awsDefaultRegionEnvVar("us-west-2") .expectedResolvedMode(DefaultsMode.CROSS_REGION), // ImdsV2 available, in-region new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-east-1") .imdsAvailable(true)) .expectedResolvedMode(DefaultsMode.IN_REGION), // ImdsV2 available, cross-region new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-west-2") .imdsAvailable(true) .ec2MetadataDisabledEnvVar("false")) .expectedResolvedMode(DefaultsMode.CROSS_REGION), // Imdsv2 disabled, should not query ImdsV2 and use fallback mode new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().region("us-west-2") .imdsAvailable(true) .ec2MetadataDisabledEnvVar("true")) .expectedResolvedMode(DefaultsMode.STANDARD), // Imdsv2 not available, should use fallback mode. new TestData().clientRegion(Region.US_EAST_1) .awsDefaultRegionEnvVar("us-west-2") .ec2MetadataConfig(new Ec2MetadataConfig().imdsAvailable(false)) .expectedResolvedMode(DefaultsMode.STANDARD), }); } @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void methodSetup() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + wireMock.port()); } @After public void cleanUp() { EC2MetadataUtils.clearCache(); wireMock.resetAll(); ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(JavaSystemSetting.JAVA_VENDOR.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.javaVendorProperty != null) { System.setProperty(JavaSystemSetting.JAVA_VENDOR.property(), testData.javaVendorProperty); } if (testData.awsExecutionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EXECUTION_ENV.environmentVariable(), testData.awsExecutionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove(SdkSystemSetting.AWS_EXECUTION_ENV.environmentVariable()); } if (testData.awsRegionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_REGION.environmentVariable(), testData.awsRegionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove(SdkSystemSetting.AWS_REGION.environmentVariable()); } if (testData.awsDefaultRegionEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set("AWS_DEFAULT_REGION", testData.awsDefaultRegionEnvVar); } else { ENVIRONMENT_VARIABLE_HELPER.remove("AWS_DEFAULT_REGION"); } if (testData.ec2MetadataConfig != null) { if (testData.ec2MetadataConfig.ec2MetadataDisabledEnvVar != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.environmentVariable(), testData.ec2MetadataConfig.ec2MetadataDisabledEnvVar); } if (testData.ec2MetadataConfig.imdsAvailable) { stubSuccessfulResponse(testData.ec2MetadataConfig.region); } } Callable<DefaultsMode> result = () -> new AutoDefaultsModeDiscovery().discover(testData.clientRegion); assertThat(result.call()).isEqualTo(testData.expectedResolvedMode); } public void stubSuccessfulResponse(String region) { stubFor(put("/latest/api/token") .willReturn(aResponse().withStatus(200).withBody("token"))); stubFor(get("/latest/meta-data/placement/region") .willReturn(aResponse().withStatus(200).withBody(region))); } private static final class TestData { private Region clientRegion; private String javaVendorProperty; private String awsExecutionEnvVar; private String awsRegionEnvVar; private String awsDefaultRegionEnvVar; private Ec2MetadataConfig ec2MetadataConfig; private DefaultsMode expectedResolvedMode; public TestData clientRegion(Region clientRegion) { this.clientRegion = clientRegion; return this; } public TestData javaVendorProperty(String javaVendorProperty) { this.javaVendorProperty = javaVendorProperty; return this; } public TestData awsExecutionEnvVar(String awsExecutionEnvVar) { this.awsExecutionEnvVar = awsExecutionEnvVar; return this; } public TestData awsRegionEnvVar(String awsRegionEnvVar) { this.awsRegionEnvVar = awsRegionEnvVar; return this; } public TestData awsDefaultRegionEnvVar(String awsDefaultRegionEnvVar) { this.awsDefaultRegionEnvVar = awsDefaultRegionEnvVar; return this; } public TestData ec2MetadataConfig(Ec2MetadataConfig ec2MetadataConfig) { this.ec2MetadataConfig = ec2MetadataConfig; return this; } public TestData expectedResolvedMode(DefaultsMode expectedResolvedMode) { this.expectedResolvedMode = expectedResolvedMode; return this; } } private static final class Ec2MetadataConfig { private boolean imdsAvailable; private String region; private String ec2MetadataDisabledEnvVar; public Ec2MetadataConfig imdsAvailable(boolean imdsAvailable) { this.imdsAvailable = imdsAvailable; return this; } public Ec2MetadataConfig region(String region) { this.region = region; return this; } public Ec2MetadataConfig ec2MetadataDisabledEnvVar(String ec2MetadataDisabledEnvVar) { this.ec2MetadataDisabledEnvVar = ec2MetadataDisabledEnvVar; return this; } } }
1,211
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.utils.AttributeMap; public class DefaultsModeConfigurationTest { @Test public void defaultConfig_shouldPresentExceptLegacyAndAuto() { Arrays.stream(DefaultsMode.values()).forEach(m -> { if (m == DefaultsMode.LEGACY || m == DefaultsMode.AUTO) { assertThat(DefaultsModeConfiguration.defaultConfig(m)).isEqualTo(AttributeMap.empty()); assertThat(DefaultsModeConfiguration.defaultHttpConfig(m)).isEqualTo(AttributeMap.empty()); } else { assertThat(DefaultsModeConfiguration.defaultConfig(m)).isNotEqualTo(AttributeMap.empty()); assertThat(DefaultsModeConfiguration.defaultHttpConfig(m)).isNotEqualTo(AttributeMap.empty()); } }); } }
1,212
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeResolverTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.Callable; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class DefaultsModeResolverTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, DefaultsMode.LEGACY), new TestData(null, null, "PropertyNotSet", null, DefaultsMode.LEGACY), // Test resolution new TestData("legacy", null, null, null, DefaultsMode.LEGACY), new TestData("standard", null, null, null, DefaultsMode.STANDARD), new TestData("auto", null, null, null, DefaultsMode.AUTO), new TestData("lEgAcY", null, null, null, DefaultsMode.LEGACY), new TestData("sTanDaRd", null, null, null, DefaultsMode.STANDARD), new TestData("AUtO", null, null, null, DefaultsMode.AUTO), // Test precedence new TestData("standard", "legacy", "PropertySetToLegacy", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData("standard", null, null, DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, "standard", "PropertySetToLegacy", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, "standard", null, DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, null, "PropertySetToStandard", DefaultsMode.LEGACY, DefaultsMode.STANDARD), new TestData(null, null, "PropertySetToAuto", DefaultsMode.LEGACY, DefaultsMode.AUTO), new TestData(null, null, null, DefaultsMode.STANDARD, DefaultsMode.STANDARD), // Test invalid values new TestData("wrongValue", null, null, null, IllegalArgumentException.class), new TestData(null, "wrongValue", null, null, IllegalArgumentException.class), new TestData(null, null, "PropertySetToUnsupportedValue", null, IllegalArgumentException.class), // Test capitalization standardization new TestData("sTaNdArD", null, null, null, DefaultsMode.STANDARD), new TestData(null, "sTaNdArD", null, null, DefaultsMode.STANDARD), new TestData(null, null, "PropertyMixedCase", null, DefaultsMode.STANDARD), }); } @Before @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_DEFAULTS_MODE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_PROFILE.property()); System.clearProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() throws Exception { if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_DEFAULTS_MODE.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_DEFAULTS_MODE.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); System.setProperty(ProfileFileSystemSetting.AWS_PROFILE.property(), "default"); System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), diskLocationForFile); } Callable<DefaultsMode> result = DefaultsModeResolver.create().defaultMode(testData.defaultMode)::resolve; if (testData.expected instanceof Class<?>) { Class<?> expectedClassType = (Class<?>) testData.expected; assertThatThrownBy(result::call).isInstanceOf(expectedClassType); } else { assertThat(result.call()).isEqualTo(testData.expected); } } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String envVarValue; private final String systemProperty; private final String configFile; private final DefaultsMode defaultMode; private final Object expected; TestData(String systemProperty, String envVarValue, String configFile, DefaultsMode defaultMode, Object expected) { this.envVarValue = envVarValue; this.systemProperty = systemProperty; this.configFile = configFile; this.defaultMode = defaultMode; this.expected = expected; } } }
1,213
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/AwsCredentialsAuthorizationStrategyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.metrics.MetricCollector; @RunWith(MockitoJUnitRunner.class) public class AwsCredentialsAuthorizationStrategyTest { @Mock SdkRequest sdkRequest; @Mock Signer defaultSigner; @Mock Signer requestOverrideSigner; AwsCredentialsProvider credentialsProvider; AwsCredentials credentials; @Mock MetricCollector metricCollector; @Before public void setUp() throws Exception { when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); credentials = AwsBasicCredentials.create("foo", "bar"); credentialsProvider = StaticCredentialsProvider.create(credentials); } @Test public void noOverrideSigner_returnsDefaultSigner() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(defaultSigner); } @Test public void overrideSigner_returnsOverrideSigner() { Optional cfg = Optional.of(requestOverrideConfiguration()); when(sdkRequest.overrideConfiguration()).thenReturn(cfg); AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(requestOverrideSigner); } @Test public void noDefaultSignerNoOverride_returnsNull() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(null) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isNull(); } @Test public void providerExists_credentialsAddedToExecutionAttributes() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(credentialsProvider) .metricCollector(metricCollector) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); authorizationContext.addCredentialsToExecutionAttributes(executionAttributes); assertThat(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isEqualTo(credentials); } @Test public void noProvider_throwsError() { AwsCredentialsAuthorizationStrategy authorizationContext = AwsCredentialsAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultCredentialsProvider(null) .metricCollector(metricCollector) .build(); assertThatThrownBy(() -> authorizationContext.addCredentialsToExecutionAttributes(new ExecutionAttributes())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("No credentials provider exists to resolve credentials from."); } private AwsRequestOverrideConfiguration requestOverrideConfiguration() { return AwsRequestOverrideConfiguration.builder() .signer(requestOverrideSigner) .build(); } }
1,214
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/TokenAuthorizationStrategyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.credentials.StaticTokenProvider; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.internal.token.TestToken; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.metrics.MetricCollector; @RunWith(MockitoJUnitRunner.class) public class TokenAuthorizationStrategyTest { private static final String TOKEN_VALUE = "token_value"; private SdkToken token; private SdkTokenProvider tokenProvider; @Mock SdkRequest sdkRequest; @Mock Signer defaultSigner; @Mock Signer requestOverrideSigner; @Mock MetricCollector metricCollector; @Before public void setUp() throws Exception { token = TestToken.builder().token(TOKEN_VALUE).build(); tokenProvider = StaticTokenProvider.create(token); when(sdkRequest.overrideConfiguration()).thenReturn(Optional.empty()); } @Test public void noOverrideSigner_returnsDefaultSigner() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(defaultSigner); } @Test public void overrideSigner_returnsOverrideSigner() { Optional cfg = Optional.of(requestOverrideConfiguration()); when(sdkRequest.overrideConfiguration()).thenReturn(cfg); TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isEqualTo(requestOverrideSigner); } @Test public void noDefaultSignerNoOverride_returnsNull() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(null) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); Signer signer = authorizationContext.resolveSigner(); assertThat(signer).isNull(); } @Test public void providerExists_credentialsAddedToExecutionAttributes() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(tokenProvider) .metricCollector(metricCollector) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes(); authorizationContext.addCredentialsToExecutionAttributes(executionAttributes); assertThat(executionAttributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isEqualTo(token); } @Test public void noProvider_throwsError() { TokenAuthorizationStrategy authorizationContext = TokenAuthorizationStrategy.builder() .request(sdkRequest) .defaultSigner(defaultSigner) .defaultTokenProvider(null) .metricCollector(metricCollector) .build(); assertThatThrownBy(() -> authorizationContext.addCredentialsToExecutionAttributes(new ExecutionAttributes())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("No token provider exists to resolve a token from."); } private AwsRequestOverrideConfiguration requestOverrideConfiguration() { return AwsRequestOverrideConfiguration.builder() .signer(requestOverrideSigner) .build(); } }
1,215
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategyFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.mockito.Mock; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.metrics.MetricCollector; public class AuthorizationStrategyFactoryTest { @Mock SdkRequest sdkRequest; @Mock MetricCollector metricCollector; @Test public void credentialTypeBearerToken_returnsTokenStrategy() { AuthorizationStrategyFactory factory = new AuthorizationStrategyFactory(sdkRequest, metricCollector, SdkClientConfiguration.builder().build()); AuthorizationStrategy authorizationStrategy = factory.strategyFor(CredentialType.TOKEN); assertThat(authorizationStrategy).isExactlyInstanceOf(TokenAuthorizationStrategy.class); } @Test public void credentialTypeAwsCredentials_returnsCredentialsStrategy() { AuthorizationStrategyFactory factory = new AuthorizationStrategyFactory(sdkRequest, metricCollector, SdkClientConfiguration.builder().build()); AuthorizationStrategy authorizationStrategy = factory.strategyFor(CredentialType.of("AWS")); assertThat(authorizationStrategy).isExactlyInstanceOf(AwsCredentialsAuthorizationStrategy.class); } }
1,216
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/checksum/AwsSignerWithChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.checksum; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.Optional; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import static org.assertj.core.api.Assertions.assertThat; public class AwsSignerWithChecksumTest { final String headerName = "x-amz-checksum-sha256"; final ChecksumSpecs SHA_256_HEADER = getCheckSum(Algorithm.SHA256, false, headerName); private final Aws4Signer signer = Aws4Signer.create(); private final AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); @Test public void signingWithChecksumWithSha256ShouldHaveChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(SHA_256_HEADER); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); final Optional<String> checksumHeader = signed.firstMatchingHeader(headerName); assertThat(checksumHeader).hasValue("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="); } @Test public void signingWithNoChecksumHeaderAlgorithmShouldNotAddChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(null); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); assertThat(signed.firstMatchingHeader(headerName)).isNotPresent(); } @Test public void signingWithNoChecksumShouldNotHaveChecksumInHeaders() throws Exception { SdkHttpFullRequest.Builder request = generateBasicRequest("abc"); ExecutionAttributes executionAttributes = getExecutionAttributes(null); SdkHttpFullRequest signed = signer.sign(request.build(), executionAttributes); assertThat(signed.firstMatchingHeader(headerName)).isNotPresent(); } private ExecutionAttributes getExecutionAttributes(ChecksumSpecs checksumSpecs) { ExecutionAttributes executionAttributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "demo") .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of("us-east-1")) .put(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, checksumSpecs) .build(); return executionAttributes; } private SdkHttpFullRequest.Builder generateBasicRequest(String stringInput) { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> { return new ByteArrayInputStream(stringInput.getBytes()); }) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } private ChecksumSpecs getCheckSum(Algorithm algorithm, boolean isStreamingRequest, String headerName) { return ChecksumSpecs.builder().algorithm(algorithm) .isRequestStreaming(isStreamingRequest).headerName(headerName).build(); } }
1,217
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsServiceExceptionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.DateUtils; public class AwsServiceExceptionTest { private static final int SKEWED_SECONDS = 60 * 60; private Instant unskewedDate = Instant.now(); private Instant futureSkewedDate = unskewedDate.plusSeconds(SKEWED_SECONDS); private Instant pastSkewedDate = unskewedDate.minusSeconds(SKEWED_SECONDS); @Test public void nonSkewErrorsAreIdentifiedCorrectly() { assertNotSkewed(0, "", 401, unskewedDate); assertNotSkewed(0, "", 403, unskewedDate); assertNotSkewed(0, "SignatureDoesNotMatch", 404, unskewedDate); assertNotSkewed(-SKEWED_SECONDS, "", 403, futureSkewedDate); assertNotSkewed(SKEWED_SECONDS, "", 403, pastSkewedDate); assertNotSkewed(0, "", 404, futureSkewedDate); assertNotSkewed(0, "", 404, pastSkewedDate); } @Test public void skewErrorsAreIdentifiedCorrectly() { assertSkewed(0, "RequestTimeTooSkewed", 404, unskewedDate); assertSkewed(0, "", 403, futureSkewedDate); assertSkewed(0, "", 401, futureSkewedDate); assertSkewed(0, "", 403, pastSkewedDate); assertSkewed(-SKEWED_SECONDS, "", 403, unskewedDate); assertSkewed(SKEWED_SECONDS, "", 403, unskewedDate); } @Test public void exceptionMessage_withExtendedRequestId() { AwsServiceException e = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorMessage("errorMessage") .serviceName("serviceName") .errorCode("errorCode") .build()) .statusCode(500) .requestId("requestId") .extendedRequestId("extendedRequestId") .build(); assertThat(e.getMessage()).isEqualTo("errorMessage (Service: serviceName, Status Code: 500, Request ID: requestId, " + "Extended Request ID: extendedRequestId)"); } @Test public void exceptionMessage_withoutExtendedRequestId() { AwsServiceException e = AwsServiceException.builder() .awsErrorDetails(AwsErrorDetails.builder() .errorMessage("errorMessage") .serviceName("serviceName") .errorCode("errorCode") .build()) .statusCode(500) .requestId("requestId") .build(); assertThat(e.getMessage()).isEqualTo("errorMessage (Service: serviceName, Status Code: 500, Request ID: requestId)"); } public void assertSkewed(int clientSideTimeOffset, String errorCode, int statusCode, Instant serverDate) { AwsServiceException exception = exception(clientSideTimeOffset, errorCode, statusCode, DateUtils.formatRfc822Date(serverDate)); assertThat(exception.isClockSkewException()).isTrue(); } public void assertNotSkewed(int clientSideTimeOffset, String errorCode, int statusCode, Instant serverDate) { AwsServiceException exception = exception(clientSideTimeOffset, errorCode, statusCode, DateUtils.formatRfc822Date(serverDate)); assertThat(exception.isClockSkewException()).isFalse(); } private AwsServiceException exception(int clientSideTimeOffset, String errorCode, int statusCode, String serverDate) { SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(statusCode) .applyMutation(r -> { if (serverDate != null) { r.putHeader("Date", serverDate); } }) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode(errorCode) .sdkHttpResponse(httpResponse) .build(); return AwsServiceException.builder() .clockSkew(Duration.ofSeconds(clientSideTimeOffset)) .awsErrorDetails(errorDetails) .statusCode(statusCode) .build(); } }
1,218
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsServiceExceptionSerializationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.StringInputStream; public class AwsServiceExceptionSerializationTest { @Test public void serializeServiceException() throws Exception { AwsServiceException expectedException = createException(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(expectedException); objectOutputStream.flush(); objectOutputStream.close(); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); AwsServiceException resultException = (AwsServiceException) ois.readObject(); assertSameValues(resultException, expectedException); } private void assertSameValues(AwsServiceException resultException, AwsServiceException expectedException) { assertThat(resultException.getMessage()).isEqualTo(expectedException.getMessage()); assertThat(resultException.requestId()).isEqualTo(expectedException.requestId()); assertThat(resultException.extendedRequestId()).isEqualTo(expectedException.extendedRequestId()); assertThat(resultException.toBuilder().clockSkew()).isEqualTo(expectedException.toBuilder().clockSkew()); assertThat(resultException.toBuilder().cause().getMessage()).isEqualTo(expectedException.toBuilder().cause().getMessage()); assertThat(resultException.awsErrorDetails()).isEqualTo(expectedException.awsErrorDetails()); } private AwsServiceException createException() { AbortableInputStream contentStream = AbortableInputStream.create(new StringInputStream("some content")); SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(403) .statusText("SomeText") .content(contentStream) .build(); AwsErrorDetails errorDetails = AwsErrorDetails.builder() .errorCode("someCode") .errorMessage("message") .serviceName("someService") .sdkHttpResponse(httpResponse) .build(); return AwsServiceException.builder() .awsErrorDetails(errorDetails) .statusCode(403) .cause(new RuntimeException("someThrowable")) .clockSkew(Duration.ofSeconds(2)) .requestId("requestId") .extendedRequestId("extendedRequestId") .message("message") .build(); } }
1,219
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/exception/AwsErrorDetailsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class AwsErrorDetailsTest { @Test public void equals_hashcode() throws Exception { EqualsVerifier.forClass(AwsErrorDetails.class) .usingGetClass() .verify(); } }
1,220
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/utils/ValidSdkObjects.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.utils; import java.net.URI; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpMethod; /** * A collection of objects (or object builder) pre-populated with all required fields. This allows tests to focus on what data * they care about, not necessarily what data is required. */ public final class ValidSdkObjects { private ValidSdkObjects() {} public static SdkHttpFullRequest.Builder sdkHttpFullRequest() { return SdkHttpFullRequest.builder() .uri(URI.create("http://test.com:80")) .method(SdkHttpMethod.GET); } public static SdkHttpFullResponse.Builder sdkHttpFullResponse() { return SdkHttpFullResponse.builder() .statusCode(200); } }
1,221
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/utils/HttpTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.utils; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Executors; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.client.config.AwsClientOption; 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.internal.http.AmazonSyncHttpClient; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; public class HttpTestUtils { public static SdkHttpClient testSdkHttpClient() { return new DefaultSdkHttpClientBuilder().buildWithDefaults( AttributeMap.empty().merge(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS)); } public static AmazonSyncHttpClient testAmazonHttpClient() { return testClientBuilder().httpClient(testSdkHttpClient()).build(); } public static TestClientBuilder testClientBuilder() { return new TestClientBuilder(); } public static SdkClientConfiguration testClientConfiguration() { return SdkClientConfiguration.builder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, new ArrayList<>()) .option(SdkClientOption.ENDPOINT, URI.create("http://localhost:8080")) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.defaultRetryPolicy()) .option(SdkClientOption.ADDITIONAL_HTTP_HEADERS, new HashMap<>()) .option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED, false) .option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, DefaultCredentialsProvider.create()) .option(SdkAdvancedClientOption.SIGNER, new NoOpSigner()) .option(SdkAdvancedClientOption.USER_AGENT_PREFIX, "") .option(SdkAdvancedClientOption.USER_AGENT_SUFFIX, "") .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .option(SdkClientOption.SCHEDULED_EXECUTOR_SERVICE, Executors.newScheduledThreadPool(1)) .build(); } public static class TestClientBuilder { private RetryPolicy retryPolicy; private SdkHttpClient httpClient; public TestClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } public TestClientBuilder httpClient(SdkHttpClient sdkHttpClient) { this.httpClient = sdkHttpClient; return this; } public AmazonSyncHttpClient build() { SdkHttpClient sdkHttpClient = this.httpClient != null ? this.httpClient : testSdkHttpClient(); return new AmazonSyncHttpClient(testClientConfiguration().toBuilder() .option(SdkClientOption.SYNC_HTTP_CLIENT, sdkHttpClient) .applyMutation(this::configureRetryPolicy) .build()); } private void configureRetryPolicy(SdkClientConfiguration.Builder builder) { if (retryPolicy != null) { builder.option(SdkClientOption.RETRY_POLICY, retryPolicy); } } } }
1,222
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/http/NoopTestAwsRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.http; import java.util.Collections; import java.util.List; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; public class NoopTestAwsRequest extends AwsRequest { private NoopTestAwsRequest(Builder builder) { super(builder); } @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 AwsRequest.Builder { @Override NoopTestAwsRequest build(); @Override Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig); } private static class BuilderImpl extends AwsRequest.BuilderImpl implements Builder { @Override public NoopTestAwsRequest build() { return new NoopTestAwsRequest(this); } @Override public Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig) { super.overrideConfiguration(awsRequestOverrideConfig); return this; } } }
1,223
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/endpoint/DefaultServiceEndpointBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.endpoint; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; public class DefaultServiceEndpointBuilderTest { @Test public void getServiceEndpoint_S3StandardRegion_HttpsProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "https") .withRegion(Region.US_EAST_1); assertEquals("https://s3.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_S3StandardRegion_HttpProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.US_EAST_1); assertEquals("http://s3.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_S3NonStandardRegion_HttpProtocol() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.EU_CENTRAL_1); assertEquals("http://s3.eu-central-1.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } @Test public void getServiceEndpoint_regionalOption_shouldUseRegionalEndpoint() throws Exception { DefaultServiceEndpointBuilder endpointBuilder = new DefaultServiceEndpointBuilder("s3", "http") .withRegion(Region.US_EAST_1).putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional"); assertEquals("http://s3.us-east-1.amazonaws.com", endpointBuilder.getServiceEndpoint().toString()); } }
1,224
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/FipsPseudoRegionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; public class FipsPseudoRegionTest { private static final AttributeMap MOCK_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "s3"; private static final String SIGNING_NAME = "demo"; private static final String SERVICE_NAME = "Demo"; private SdkHttpClient.Builder defaultHttpClientBuilder; @BeforeEach public void setup() { defaultHttpClientBuilder = mock(SdkHttpClient.Builder.class); when(defaultHttpClientBuilder.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class)); } @ParameterizedTest @MethodSource("testCases") public void verifyRegion(TestCase tc) { TestClient client = testClientBuilder().region(tc.inputRegion).build(); assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(tc.expectedClientRegion); assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue(); } public static List<TestCase> testCases() { List<TestCase> testCases = new ArrayList<>(); testCases.add(new TestCase(Region.of("fips-us-west-2"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("us-west-2-fips"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("rekognition-fips.us-west-2"), Region.of("rekognition.us-west-2"))); testCases.add(new TestCase(Region.of("rekognition.fips-us-west-2"), Region.of("rekognition.us-west-2"))); testCases.add(new TestCase(Region.of("query-fips-us-west-2"), Region.of("query-us-west-2"))); testCases.add(new TestCase(Region.of("fips-fips-us-west-2"), Region.of("us-west-2"))); testCases.add(new TestCase(Region.of("fips-us-west-2-fips"), Region.of("us-west-2"))); return testCases; } private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, mock(Signer.class)) .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private static class TestCase { private Region inputRegion; private Region expectedClientRegion; public TestCase(Region inputRegion, Region expectedClientRegion) { this.inputRegion = inputRegion; this.expectedClientRegion = expectedClientRegion; } } private static class TestClient { private final SdkClientConfiguration clientConfiguration; public TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient> implements AwsClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientBuilder, null, null); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return MOCK_DEFAULTS; } } }
1,225
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/DefaultsModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION; import static software.amazon.awssdk.awscore.client.config.AwsClientOption.DEFAULTS_MODE; import static software.amazon.awssdk.core.client.config.SdkClientOption.DEFAULT_RETRY_MODE; import static software.amazon.awssdk.core.client.config.SdkClientOption.RETRY_POLICY; import static software.amazon.awssdk.regions.ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT; import java.time.Duration; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; @RunWith(MockitoJUnitRunner.class) public class DefaultsModeTest { private static final AttributeMap SERVICE_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "test"; private static final String SIGNING_NAME = "test"; private static final String SERVICE_NAME = "test"; @Mock private SdkHttpClient.Builder defaultHttpClientBuilder; @Mock private SdkAsyncHttpClient.Builder defaultAsyncHttpClientBuilder; @Mock private AutoDefaultsModeDiscovery autoModeDiscovery; @Test public void defaultClient_shouldUseLegacyModeWithExistingDefaults() { TestClient client = testClientBuilder() .region(Region.US_WEST_2) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { assertThat(serviceDefaults).isEqualTo(SERVICE_DEFAULTS); return mock(SdkHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(DefaultsMode.LEGACY); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(RetryMode.defaultRetryMode()); assertThat(client.clientConfiguration.option(DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)).isNull(); } @Test public void nonLegacyDefaultsMode_shouldApplySdkDefaultsAndHttpDefaults() { DefaultsMode targetMode = DefaultsMode.IN_REGION; TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(targetMode) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { AttributeMap defaultHttpConfig = DefaultsModeConfiguration.defaultHttpConfig(targetMode); AttributeMap mergedDefaults = SERVICE_DEFAULTS.merge(defaultHttpConfig); assertThat(serviceDefaults).isEqualTo(mergedDefaults); return mock(SdkHttpClient.class); }).build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(targetMode); AttributeMap attributes = DefaultsModeConfiguration.defaultConfig(targetMode); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(attributes.get(DEFAULT_RETRY_MODE)); assertThat(client.clientConfiguration.option(DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)).isEqualTo("regional"); } @Test public void nonLegacyDefaultsModeAsyncClient_shouldApplySdkDefaultsAndHttpDefaults() { DefaultsMode targetMode = DefaultsMode.IN_REGION; TestAsyncClient client = testAsyncClientBuilder().region(Region.US_WEST_1) .defaultsMode(targetMode) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { AttributeMap defaultHttpConfig = DefaultsModeConfiguration.defaultHttpConfig(targetMode); AttributeMap mergedDefaults = SERVICE_DEFAULTS.merge(defaultHttpConfig); assertThat(serviceDefaults).isEqualTo(mergedDefaults); return mock(SdkHttpClient.class); }).build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(targetMode); AttributeMap attributes = DefaultsModeConfiguration.defaultConfig(targetMode); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(attributes.get(DEFAULT_RETRY_MODE)); } @Test public void clientOverrideRetryMode_shouldTakePrecedence() { TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(DefaultsMode.IN_REGION) .overrideConfiguration(o -> o.retryPolicy(RetryMode.LEGACY)) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(DefaultsMode.IN_REGION); assertThat(client.clientConfiguration.option(RETRY_POLICY).retryMode()).isEqualTo(RetryMode.LEGACY); } @Test public void autoMode_shouldResolveDefaultsMode() { DefaultsMode expectedMode = DefaultsMode.IN_REGION; when(autoModeDiscovery.discover(any(Region.class))).thenReturn(expectedMode); TestClient client = testClientBuilder().region(Region.US_WEST_1) .defaultsMode(DefaultsMode.AUTO) .build(); assertThat(client.clientConfiguration.option(DEFAULTS_MODE)).isEqualTo(expectedMode); } private static class TestClient { private final SdkClientConfiguration clientConfiguration; public TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestAsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient> implements AwsClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientBuilder, defaultAsyncHttpClientBuilder, autoModeDiscovery); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return SERVICE_DEFAULTS; } } private class TestAsyncClientBuilder extends AwsDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> implements AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> { public TestAsyncClientBuilder() { super(defaultHttpClientBuilder, defaultAsyncHttpClientBuilder, autoModeDiscovery); } @Override protected TestAsyncClient buildClient() { return new TestAsyncClient(super.asyncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return SERVICE_DEFAULTS; } } private static class TestAsyncClient { private final SdkClientConfiguration clientConfiguration; private TestAsyncClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } }
1,226
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/DefaultAwsClientBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import static org.assertj.core.api.Assertions.assertThat; 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.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION; import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SERVICE_SIGNING_NAME; import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SIGNING_REGION; import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER; 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.Arrays; 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.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; 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.regions.Region; import software.amazon.awssdk.utils.AttributeMap; /** * Validate the functionality of the {@link AwsDefaultClientBuilder}. */ @RunWith(MockitoJUnitRunner.class) public class DefaultAwsClientBuilderTest { private static final AttributeMap MOCK_DEFAULTS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .build(); private static final String ENDPOINT_PREFIX = "s3"; private static final String SIGNING_NAME = "demo"; private static final String SERVICE_NAME = "Demo"; private static final Signer TEST_SIGNER = Aws4Signer.create(); private static final URI ENDPOINT = URI.create("https://example.com"); @Mock private SdkHttpClient.Builder defaultHttpClientBuilder; @Mock private SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory; @Mock private AutoDefaultsModeDiscovery autoModeDiscovery; @Before public void setup() { when(defaultHttpClientBuilder.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class)); when(defaultAsyncHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkAsyncHttpClient.class)); } @Test public void buildIncludesServiceDefaults() { TestClient client = testClientBuilder().region(Region.US_WEST_1).build(); assertThat(client.clientConfiguration.option(SIGNER)).isEqualTo(TEST_SIGNER); assertThat(client.clientConfiguration.option(SIGNING_REGION)).isNotNull(); assertThat(client.clientConfiguration.option(SdkClientOption.SERVICE_NAME)).isEqualTo(SERVICE_NAME); } @Test public void buildWithRegionShouldHaveCorrectEndpointAndSigningRegion() { TestClient client = testClientBuilder().region(Region.US_WEST_1).build(); assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)) .hasToString("https://" + ENDPOINT_PREFIX + ".us-west-1.amazonaws.com"); assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1); assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME); } @Test public void buildWithFipsRegionThenNonFipsFipsEnabledRemainsSet() { TestClient client = testClientBuilder() .region(Region.of("us-west-2-fips")) // first call to setter sets the flag .region(Region.of("us-west-2"))// second call should clear .build(); assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2); assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue(); } @Test public void buildWithSetFipsTrueAndNonFipsRegionFipsEnabledRemainsSet() { TestClient client = testClientBuilder() .fipsEnabled(true) .region(Region.of("us-west-2")) .build(); assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2); assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue(); } @Test public void buildWithEndpointShouldHaveCorrectEndpointAndSigningRegion() { TestClient client = testClientBuilder().region(Region.US_WEST_1).endpointOverride(ENDPOINT).build(); assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)).isEqualTo(ENDPOINT); assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1); assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME); } @Test public void noClientProvided_DefaultHttpClientIsManagedBySdk() { TestClient client = testClientBuilder().region(Region.US_WEST_2).build(); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class); verify(defaultHttpClientBuilder, times(1)).buildWithDefaults(any()); } @Test public void noAsyncClientProvided_DefaultAsyncHttpClientIsManagedBySdk() { TestAsyncClient client = testAsyncClientBuilder().region(Region.US_WEST_2).build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); verify(defaultAsyncHttpClientFactory, times(1)).buildWithDefaults(any()); } @Test public void clientFactoryProvided_ClientIsManagedBySdk() { TestClient client = testClientBuilder() .region(Region.US_WEST_2) .httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> { assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS); return mock(SdkHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class); verify(defaultHttpClientBuilder, never()).buildWithDefaults(any()); } @Test public void asyncHttpClientFactoryProvided_ClientIsManagedBySdk() { TestAsyncClient client = testAsyncClientBuilder() .region(Region.US_WEST_2) .httpClientBuilder((SdkAsyncHttpClient.Builder) serviceDefaults -> { assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS); return mock(SdkAsyncHttpClient.class); }) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void explicitClientProvided_ClientIsNotManagedBySdk() { String clientName = "foobarsync"; SdkHttpClient sdkHttpClient = mock(SdkHttpClient.class); TestClient client = testClientBuilder() .region(Region.US_WEST_2) .httpClient(sdkHttpClient) .build(); when(sdkHttpClient.clientName()).thenReturn(clientName); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT)) .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class); assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT).clientName()) .isEqualTo(clientName); verify(defaultHttpClientBuilder, never()).buildWithDefaults(any()); } @Test public void explicitAsyncHttpClientProvided_ClientIsNotManagedBySdk() { String clientName = "foobarasync"; SdkAsyncHttpClient sdkAsyncHttpClient = mock(SdkAsyncHttpClient.class); TestAsyncClient client = testAsyncClientBuilder() .region(Region.US_WEST_2) .httpClient(sdkAsyncHttpClient) .build(); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); when(sdkAsyncHttpClient.clientName()).thenReturn(clientName); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT)) .isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class); assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT).clientName()) .isEqualTo(clientName); verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any()); } @Test public void clientBuilderFieldsHaveBeanEquivalents() throws Exception { AwsClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder(); BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass()); Method[] clientBuilderMethods = AwsClientBuilder.class.getDeclaredMethods(); Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> { String propertyName = builderMethod.getName(); 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(); }); }); } private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, TEST_SIGNER) .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() { ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .putAdvancedOption(SIGNER, TEST_SIGNER) .putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false) .build(); return new TestAsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(overrideConfig); } private static class TestClient { private final SdkClientConfiguration clientConfiguration; public TestClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient> implements AwsClientBuilder<TestClientBuilder, TestClient> { public TestClientBuilder() { super(defaultHttpClientBuilder, null, autoModeDiscovery); } @Override protected TestClient buildClient() { return new TestClient(super.syncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return MOCK_DEFAULTS; } } private static class TestAsyncClient { private final SdkClientConfiguration clientConfiguration; private TestAsyncClient(SdkClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; } } private class TestAsyncClientBuilder extends AwsDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient> implements AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> { public TestAsyncClientBuilder() { super(defaultHttpClientBuilder, defaultAsyncHttpClientFactory, autoModeDiscovery); } @Override protected TestAsyncClient buildClient() { return new TestAsyncClient(super.asyncClientConfiguration()); } @Override protected String serviceEndpointPrefix() { return ENDPOINT_PREFIX; } @Override protected String signingName() { return SIGNING_NAME; } @Override protected String serviceName() { return SERVICE_NAME; } @Override protected AttributeMap serviceHttpConfig() { return MOCK_DEFAULTS; } } }
1,227
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/interceptor/TraceIdExecutionInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.interceptor; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.util.Properties; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; public class TraceIdExecutionInterceptorTest { @Test public void nothingDoneWithoutEnvSettings() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest()); }); } @Test public void headerAddedWithEnvSettings() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("AWS_LAMBDA_FUNCTION_NAME", "foo"); env.set("_X_AMZN_TRACE_ID", "bar"); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("bar"); }); } @Test public void headerAddedWithSysPropWhenNoEnvSettings() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("AWS_LAMBDA_FUNCTION_NAME", "foo"); Properties props = System.getProperties(); props.setProperty("com.amazonaws.xray.traceHeader", "sys-prop"); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("sys-prop"); }); } @Test public void headerAddedWithEnvVariableValueWhenBothEnvAndSysPropAreSet() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("AWS_LAMBDA_FUNCTION_NAME", "foo"); env.set("_X_AMZN_TRACE_ID", "bar"); Properties props = System.getProperties(); props.setProperty("com.amazonaws.xray.traceHeader", "sys-prop"); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("sys-prop"); }); } @Test public void headerNotAddedIfHeaderAlreadyExists() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("AWS_LAMBDA_FUNCTION_NAME", "foo"); env.set("_X_AMZN_TRACE_ID", "bar"); Context.ModifyHttpRequest context = context(SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .putHeader("X-Amzn-Trace-Id", "existing") .build()); assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest()); }); } @Test public void headerNotAddedIfNotInLambda() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("_X_AMZN_TRACE_ID", "bar"); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest()); }); } @Test public void headerNotAddedIfNoTraceIdEnvVar() { EnvironmentVariableHelper.run(env -> { resetRelevantEnvVars(env); env.set("_X_AMZN_TRACE_ID", "bar"); Context.ModifyHttpRequest context = context(); assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest()); }); } private Context.ModifyHttpRequest context() { return context(SdkHttpRequest.builder() .uri(URI.create("https://localhost")) .method(SdkHttpMethod.GET) .build()); } private Context.ModifyHttpRequest context(SdkHttpRequest request) { return InterceptorContext.builder() .request(Mockito.mock(SdkRequest.class)) .httpRequest(request) .build(); } private SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context) { return new TraceIdExecutionInterceptor().modifyHttpRequest(context, new ExecutionAttributes()); } private void resetRelevantEnvVars(EnvironmentVariableHelper env) { env.remove("AWS_LAMBDA_FUNCTION_NAME"); env.remove("_X_AMZN_TRACE_ID"); } }
1,228
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/interceptor/HelpfulUnknownHostExceptionInterceptorTest.java
package software.amazon.awssdk.awscore.interceptor; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.UnknownHostException; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.internal.interceptor.DefaultFailedExecutionContext; import software.amazon.awssdk.regions.Region; public class HelpfulUnknownHostExceptionInterceptorTest { private static final ExecutionInterceptor INTERCEPTOR = new HelpfulUnknownHostExceptionInterceptor(); @Test public void modifyException_skipsNonUnknownHostExceptions() { IOException exception = new IOException(); assertThat(modifyException(exception)).isEqualTo(exception); } @Test public void modifyException_supportsNestedUnknownHostExceptions() { Exception exception = new UnknownHostException(); exception.initCause(new IOException()); exception = new IllegalArgumentException(exception); exception = new UnsupportedOperationException(exception); assertThat(modifyException(exception, Region.AWS_GLOBAL)).isInstanceOf(SdkClientException.class); } @Test public void modifyException_returnsGenericHelp_forGlobalRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.AWS_GLOBAL)) .isInstanceOf(SdkClientException.class) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forUnknownServices() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forUnknownServicesInUnknownRegions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "millems-hotdog-stand")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericHelp_forServicesRegionalizedInAllPartitions() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.US_EAST_1, "dynamodb")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "global")) .hasMessageContaining("network"); } @Test public void modifyException_returnsGenericGlobalRegionHelp_forServicesGlobalInSomePartitionOtherThanTheClientPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-99"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "network")) .hasMessageContaining("aws-global") .hasMessageContaining("aws-cn-global"); } @Test public void modifyException_returnsSpecificGlobalRegionHelp_forServicesGlobalInTheClientRegionPartition() { UnknownHostException exception = new UnknownHostException(); assertThat(modifyException(exception, Region.of("cn-north-1"), "iam")) .isInstanceOf(SdkClientException.class) .satisfies(t -> doesNotHaveMessageContaining(t, "aws-global")) .hasMessageContaining("aws-cn-global"); } private void doesNotHaveMessageContaining(Throwable throwable, String value) { assertThat(throwable.getMessage()).doesNotContain(value); } private Throwable modifyException(Throwable throwable) { return modifyException(throwable, null); } private Throwable modifyException(Throwable throwable, Region clientRegion) { return modifyException(throwable, clientRegion, null); } private Throwable modifyException(Throwable throwable, Region clientRegion, String serviceEndpointPrefix) { SdkRequest sdkRequest = Mockito.mock(SdkRequest.class); DefaultFailedExecutionContext context = DefaultFailedExecutionContext.builder() .interceptorContext(InterceptorContext.builder().request(sdkRequest).build()) .exception(throwable) .build(); ExecutionAttributes executionAttributes = new ExecutionAttributes().putAttribute(AwsExecutionAttribute.AWS_REGION, clientRegion) .putAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX, serviceEndpointPrefix); return INTERCEPTOR.modifyException(context, executionAttributes); } }
1,229
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsRequestOverrideConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Request-specific configuration overrides for AWS service clients. */ @SdkPublicApi public final class AwsRequestOverrideConfiguration extends RequestOverrideConfiguration { private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private AwsRequestOverrideConfiguration(BuilderImpl builder) { super(builder); this.credentialsProvider = builder.awsCredentialsProvider; } /** * Create a {@link AwsRequestOverrideConfiguration} from the provided {@link RequestOverrideConfiguration}. * * Given null, this will return null. Given a {@code AwsRequestOverrideConfiguration} this will return the input. Given * any other {@code RequestOverrideConfiguration} this will return a new {@code AwsRequestOverrideConfiguration} with all * the common attributes from the input copied into the result. */ public static AwsRequestOverrideConfiguration from(RequestOverrideConfiguration configuration) { if (configuration == null) { return null; } if (configuration instanceof AwsRequestOverrideConfiguration) { return (AwsRequestOverrideConfiguration) configuration; } return new AwsRequestOverrideConfiguration.BuilderImpl(configuration).build(); } /** * The optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this request. * * @return The optional {@link AwsCredentialsProvider}. */ public Optional<AwsCredentialsProvider> credentialsProvider() { return Optional.ofNullable(CredentialUtils.toCredentialsProvider(credentialsProvider)); } /** * The optional {@link IdentityProvider<? extends AwsCredentialsIdentity>} that will provide credentials to be used to * authenticate this request. * * @return The optional {@link IdentityProvider<? extends AwsCredentialsIdentity>}. */ public Optional<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsIdentityProvider() { return Optional.ofNullable(credentialsProvider); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } @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; } AwsRequestOverrideConfiguration that = (AwsRequestOverrideConfiguration) o; return Objects.equals(credentialsProvider, that.credentialsProvider); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + super.hashCode(); hashCode = 31 * hashCode + Objects.hashCode(credentialsProvider); return hashCode; } public interface Builder extends RequestOverrideConfiguration.Builder<Builder>, SdkBuilder<Builder, AwsRequestOverrideConfiguration> { /** * Set the optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this request. * * @param credentialsProvider The {@link AwsCredentialsProvider}. * @return This object for chaining. */ default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider); } /** * Set the optional {@link IdentityProvider<? extends AwsCredentialsIdentity>} that will provide credentials to be used * to authenticate this request. * * @param credentialsProvider The {@link IdentityProvider<? extends AwsCredentialsIdentity>}. * @return This object for chaining. */ default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } /** * Return the optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this * request. * * @return The optional {@link AwsCredentialsProvider}. */ AwsCredentialsProvider credentialsProvider(); @Override AwsRequestOverrideConfiguration build(); } private static final class BuilderImpl extends RequestOverrideConfiguration.BuilderImpl<Builder> implements Builder { private IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider; private BuilderImpl() { } private BuilderImpl(RequestOverrideConfiguration requestOverrideConfiguration) { super(requestOverrideConfiguration); } private BuilderImpl(AwsRequestOverrideConfiguration awsRequestOverrideConfig) { super(awsRequestOverrideConfig); this.awsCredentialsProvider = awsRequestOverrideConfig.credentialsProvider; } @Override public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.awsCredentialsProvider = credentialsProvider; return this; } @Override public AwsCredentialsProvider credentialsProvider() { return CredentialUtils.toCredentialsProvider(awsCredentialsProvider); } @Override public AwsRequestOverrideConfiguration build() { return new AwsRequestOverrideConfiguration(this); } } }
1,230
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.regions.Region; /** * AWS-specific attributes attached to the execution. This information is available to {@link ExecutionInterceptor}s. */ @SdkPublicApi public final class AwsExecutionAttribute extends SdkExecutionAttribute { /** * The AWS {@link Region} the client was configured with. This is not always same as the * {@link AwsSignerExecutionAttribute#SIGNING_REGION} for global services like IAM. */ public static final ExecutionAttribute<Region> AWS_REGION = new ExecutionAttribute<>("AwsRegion"); /** * The {@link AwsClientOption#ENDPOINT_PREFIX} for the client. */ public static final ExecutionAttribute<String> ENDPOINT_PREFIX = new ExecutionAttribute<>("AwsEndpointPrefix"); /** * Whether dualstack endpoints were enabled for this request. */ public static final ExecutionAttribute<Boolean> DUALSTACK_ENDPOINT_ENABLED = new ExecutionAttribute<>("DualstackEndpointsEnabled"); /** * Whether fips endpoints were enabled for this request. */ public static final ExecutionAttribute<Boolean> FIPS_ENDPOINT_ENABLED = new ExecutionAttribute<>("FipsEndpointsEnabled"); /** * Whether the client was configured to use the service's global endpoint. This is used as part of endpoint computation by * the endpoint providers. */ public static final ExecutionAttribute<Boolean> USE_GLOBAL_ENDPOINT = new ExecutionAttribute<>("UseGlobalEndpoint"); private AwsExecutionAttribute() { } }
1,231
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkRequest; /** * Base class for all AWS Service requests. */ @SdkPublicApi public abstract class AwsRequest extends SdkRequest { private final AwsRequestOverrideConfiguration requestOverrideConfig; protected AwsRequest(Builder builder) { this.requestOverrideConfig = builder.overrideConfiguration(); } @Override public final Optional<AwsRequestOverrideConfiguration> overrideConfiguration() { return Optional.ofNullable(requestOverrideConfig); } @Override public abstract Builder toBuilder(); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsRequest that = (AwsRequest) o; return Objects.equals(requestOverrideConfig, that.requestOverrideConfig); } @Override public int hashCode() { return Objects.hashCode(requestOverrideConfig); } public interface Builder extends SdkRequest.Builder { @Override AwsRequestOverrideConfiguration overrideConfiguration(); /** * Add an optional request override configuration. * * @param awsRequestOverrideConfig The override configuration. * @return This object for method chaining. */ Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig); /** * Add an optional request override configuration. * * @param builderConsumer A {@link Consumer} to which an empty {@link AwsRequestOverrideConfiguration.Builder} will be * given. * @return This object for method chaining. */ Builder overrideConfiguration(Consumer<AwsRequestOverrideConfiguration.Builder> builderConsumer); @Override AwsRequest build(); } protected abstract static class BuilderImpl implements Builder { private AwsRequestOverrideConfiguration awsRequestOverrideConfig; protected BuilderImpl() { } protected BuilderImpl(AwsRequest request) { request.overrideConfiguration().ifPresent(this::overrideConfiguration); } @Override public Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig) { this.awsRequestOverrideConfig = awsRequestOverrideConfig; return this; } @Override public Builder overrideConfiguration(Consumer<AwsRequestOverrideConfiguration.Builder> builderConsumer) { AwsRequestOverrideConfiguration.Builder b = AwsRequestOverrideConfiguration.builder(); builderConsumer.accept(b); awsRequestOverrideConfig = b.build(); return this; } @Override public final AwsRequestOverrideConfiguration overrideConfiguration() { return awsRequestOverrideConfig; } } }
1,232
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsResponseMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.ToString; /** * Represents additional metadata included with a response from a service. Response * metadata varies by service, but all services return an AWS request ID that * can be used in the event a service call isn't working as expected and you * need to work with AWS support to debug an issue. */ @SdkProtectedApi public abstract class AwsResponseMetadata { private static final String UNKNOWN = "UNKNOWN"; private final Map<String, String> metadata; /** * Creates a new ResponseMetadata object from a specified map of raw * metadata information. * * @param metadata * The raw metadata for the new ResponseMetadata object. */ protected AwsResponseMetadata(Map<String, String> metadata) { this.metadata = Collections.unmodifiableMap(metadata); } protected AwsResponseMetadata(AwsResponseMetadata responseMetadata) { this(responseMetadata == null ? new HashMap<>() : responseMetadata.metadata); } /** * Returns the AWS request ID contained in this response metadata object. * AWS request IDs can be used in the event a service call isn't working as * expected and you need to work with AWS support to debug an issue. * * <p> * Can be overriden by subclasses to provide service specific requestId * * @return The AWS request ID contained in this response metadata object. */ public String requestId() { return getValue(AWS_REQUEST_ID); } @Override public final String toString() { return ToString.builder("AwsResponseMetadata") .add("metadata", metadata.keySet()) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsResponseMetadata that = (AwsResponseMetadata) o; return Objects.equals(metadata, that.metadata); } @Override public int hashCode() { return Objects.hashCode(metadata); } /** * Get the value based on the key, returning {@link #UNKNOWN} if the value is null. * * @param key the key of the value * @return the value or {@link #UNKNOWN} if not present. */ protected final String getValue(String key) { return Optional.ofNullable(metadata.get(key)).orElse(UNKNOWN); } }
1,233
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/DefaultAwsResponseMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkStandardLogger; /** * Represents additional metadata included with a response from a service. Response * metadata varies by service, but all services return an AWS request ID that * can be used in the event a service call isn't working as expected and you * need to work with AWS support to debug an issue. * <p> * Access to AWS request IDs is also available through the {@link SdkStandardLogger#REQUEST_ID_LOGGER} * logger. */ @SdkProtectedApi public final class DefaultAwsResponseMetadata extends AwsResponseMetadata { /** * Creates a new ResponseMetadata object from a specified map of raw * metadata information. * * @param metadata * The raw metadata for the new ResponseMetadata object. */ private DefaultAwsResponseMetadata(Map<String, String> metadata) { super(metadata); } public static DefaultAwsResponseMetadata create(Map<String, String> metadata) { return new DefaultAwsResponseMetadata(metadata); } }
1,234
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkClient; /** * Interface for an AWS Client that extends SdkClient. All AWS service client interfaces should extend this interface. */ @SdkPublicApi @ThreadSafe public interface AwsClient extends SdkClient { @Override default AwsServiceClientConfiguration serviceClientConfiguration() { throw new UnsupportedOperationException(); } }
1,235
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkResponse; /** * Base class for all AWS Service responses. */ @SdkPublicApi public abstract class AwsResponse extends SdkResponse { private AwsResponseMetadata responseMetadata; protected AwsResponse(Builder builder) { super(builder); this.responseMetadata = builder.responseMetadata(); } public AwsResponseMetadata responseMetadata() { return responseMetadata; } @Override public abstract Builder toBuilder(); @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; } AwsResponse that = (AwsResponse) o; return Objects.equals(responseMetadata, that.responseMetadata); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + super.hashCode(); hashCode = 31 * hashCode + Objects.hashCode(responseMetadata); return hashCode; } public interface Builder extends SdkResponse.Builder { AwsResponseMetadata responseMetadata(); Builder responseMetadata(AwsResponseMetadata metadata); @Override AwsResponse build(); } protected abstract static class BuilderImpl extends SdkResponse.BuilderImpl implements Builder { private AwsResponseMetadata responseMetadata; protected BuilderImpl() { } protected BuilderImpl(AwsResponse response) { super(response); this.responseMetadata = response.responseMetadata(); } @Override public Builder responseMetadata(AwsResponseMetadata responseMetadata) { this.responseMetadata = responseMetadata; return this; } @Override public AwsResponseMetadata responseMetadata() { return responseMetadata; } } }
1,236
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsServiceClientConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore; import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkServiceClientConfiguration; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; /** * Class to expose AWS service client settings to the user, e.g., region */ @SdkPublicApi public abstract class AwsServiceClientConfiguration extends SdkServiceClientConfiguration { private final Region region; private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; protected AwsServiceClientConfiguration(Builder builder) { super(builder); this.region = builder.region(); this.credentialsProvider = builder.credentialsProvider(); } /** * * @return The configured region of the AwsClient */ public Region region() { return this.region; } /** * @return The configured identity provider */ public IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() { return credentialsProvider; } @Override public int hashCode() { int result = 1; result = 31 * result + super.hashCode(); result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (credentialsProvider != null ? credentialsProvider.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (!super.equals(o)) { return false; } AwsServiceClientConfiguration that = (AwsServiceClientConfiguration) o; return Objects.equals(region, that.region) && Objects.equals(credentialsProvider, that.credentialsProvider); } /** * The base interface for all AWS service client configuration builders */ public interface Builder extends SdkServiceClientConfiguration.Builder { /** * Return the region */ default Region region() { throw new UnsupportedOperationException(); } /** * Configure the region */ default Builder region(Region region) { throw new UnsupportedOperationException(); } @Override default Builder overrideConfiguration(ClientOverrideConfiguration clientOverrideConfiguration) { throw new UnsupportedOperationException(); } @Override default Builder endpointOverride(URI endpointOverride) { throw new UnsupportedOperationException(); } @Override default Builder endpointProvider(EndpointProvider endpointProvider) { throw new UnsupportedOperationException(); } @Override default Builder putAuthScheme(AuthScheme<?> authScheme) { throw new UnsupportedOperationException(); } /** * Configure the credentials provider */ default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } default IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() { throw new UnsupportedOperationException(); } @Override AwsServiceClientConfiguration build(); } protected abstract static class BuilderImpl implements Builder { protected ClientOverrideConfiguration overrideConfiguration; protected Region region; protected URI endpointOverride; protected EndpointProvider endpointProvider; protected IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; protected Map<String, AuthScheme<?>> authSchemes; protected BuilderImpl() { } protected BuilderImpl(AwsServiceClientConfiguration awsServiceClientConfiguration) { this.overrideConfiguration = awsServiceClientConfiguration.overrideConfiguration(); this.region = awsServiceClientConfiguration.region(); this.endpointOverride = awsServiceClientConfiguration.endpointOverride().orElse(null); this.endpointProvider = awsServiceClientConfiguration.endpointProvider().orElse(null); } @Override public final ClientOverrideConfiguration overrideConfiguration() { return overrideConfiguration; } @Override public final Region region() { return region; } @Override public final URI endpointOverride() { return endpointOverride; } @Override public final EndpointProvider endpointProvider() { return endpointProvider; } @Override public final Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } @Override public final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() { return credentialsProvider; } @Override public final Builder putAuthScheme(AuthScheme<?> authScheme) { if (authSchemes == null) { authSchemes = new HashMap<>(); } authSchemes.put(authScheme.schemeId(), authScheme); return this; } @Override public final Map<String, AuthScheme<?>> authSchemes() { if (authSchemes == null) { return Collections.emptyMap(); } return Collections.unmodifiableMap(new HashMap<>(authSchemes)); } } }
1,237
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamAsyncResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER; 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.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; /** * Unmarshalling layer on top of the {@link AsyncResponseTransformer} to decode event stream messages and deliver them to the * subscriber. * * @param <ResponseT> Initial response type of event stream operation. * @param <EventT> Base type of event stream message frames. */ @SdkProtectedApi public final class EventStreamAsyncResponseTransformer<ResponseT, EventT> implements AsyncResponseTransformer<SdkResponse, Void> { private static final Logger log = Logger.loggerFor(EventStreamAsyncResponseTransformer.class); /** * {@link EventStreamResponseHandler} provided by customer. */ private final EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler; /** * Unmarshalls the initial response. */ private final HttpResponseHandler<? extends ResponseT> initialResponseHandler; /** * Unmarshalls the event POJO. */ private final HttpResponseHandler<? extends EventT> eventResponseHandler; /** * Unmarshalls exception events. */ private final HttpResponseHandler<? extends Throwable> exceptionResponseHandler; private final Supplier<ExecutionAttributes> attributesFactory; /** * Future to notify on completion. Note that we do not notify this future in the event of an error, that * is handled separately by the generated client. Ultimately we need this due to a disconnect between * completion of the request (i.e. finish reading all the data from the wire) and the completion of the event * stream (i.e. deliver the last event to the subscriber). */ private final CompletableFuture<Void> future; /** * Whether exceptions may be sent to the downstream event stream response handler. This prevents multiple exception * deliveries from being performed. */ private final AtomicBoolean exceptionsMayBeSent = new AtomicBoolean(true); /** * The future generated via {@link #prepare()}. */ private volatile CompletableFuture<Void> transformFuture; /** * Request Id for the streaming request. The value is populated when the initial response is received from the service. * As request id is not sent in event messages (including exceptions), this can be returned by the SDK along with * received exception details. */ private volatile String requestId = null; /** * Extended Request Id for the streaming request. The value is populated when the initial response is received from the * service. As request id is not sent in event messages (including exceptions), this can be returned by the SDK along with * received exception details. */ private volatile String extendedRequestId = null; private EventStreamAsyncResponseTransformer( EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler, HttpResponseHandler<? extends ResponseT> initialResponseHandler, HttpResponseHandler<? extends EventT> eventResponseHandler, HttpResponseHandler<? extends Throwable> exceptionResponseHandler, CompletableFuture<Void> future, String serviceName) { this.eventStreamResponseHandler = eventStreamResponseHandler; this.initialResponseHandler = initialResponseHandler; this.eventResponseHandler = eventResponseHandler; this.exceptionResponseHandler = exceptionResponseHandler; this.future = future; this.attributesFactory = () -> new ExecutionAttributes().putAttribute(SdkExecutionAttribute.SERVICE_NAME, serviceName); } /** * Creates a {@link Builder} used to create {@link EventStreamAsyncResponseTransformer}. * * @param <ResponseT> Initial response type. * @param <EventT> Event type being delivered. * @return New {@link Builder} instance. */ public static <ResponseT, EventT> Builder<ResponseT, EventT> builder() { return new Builder<>(); } @Override public CompletableFuture<Void> prepare() { transformFuture = new CompletableFuture<>(); return transformFuture; } @Override public void onResponse(SdkResponse response) { // Capture the request IDs from the initial response, so that we can include them in each event. if (response != null && response.sdkHttpResponse() != null) { this.requestId = response.sdkHttpResponse() .firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS) .orElse(null); this.extendedRequestId = response.sdkHttpResponse() .firstMatchingHeader(X_AMZ_ID_2_HEADER) .orElse(null); log.debug(() -> getLogPrefix() + "Received HTTP response headers: " + response); } } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { Validate.isTrue(transformFuture != null, "onStream() invoked without prepare()."); exceptionsMayBeSent.set(true); SynchronousMessageDecoder decoder = new SynchronousMessageDecoder(); eventStreamResponseHandler.onEventStream(publisher.flatMapIterable(decoder::decode) .flatMapIterable(this::transformMessage) .doAfterOnComplete(this::handleOnStreamComplete) .doAfterOnError(this::handleOnStreamError) .doAfterOnCancel(this::handleOnStreamCancel)); } @Override public void exceptionOccurred(Throwable throwable) { if (exceptionsMayBeSent.compareAndSet(true, false)) { try { eventStreamResponseHandler.exceptionOccurred(throwable); } catch (RuntimeException e) { log.warn(() -> "Exception raised by exceptionOccurred. Ignoring.", e); } transformFuture.completeExceptionally(throwable); } } private void handleOnStreamComplete() { log.trace(() -> getLogPrefix() + "Event stream completed successfully."); exceptionsMayBeSent.set(false); eventStreamResponseHandler.complete(); transformFuture.complete(null); future.complete(null); } private void handleOnStreamError(Throwable throwable) { log.trace(() -> getLogPrefix() + "Event stream failed.", throwable); exceptionOccurred(throwable); } private void handleOnStreamCancel() { log.trace(() -> getLogPrefix() + "Event stream cancelled."); exceptionsMayBeSent.set(false); transformFuture.complete(null); future.complete(null); } private static final class SynchronousMessageDecoder { private final MessageDecoder decoder = new MessageDecoder(); private Iterable<Message> decode(ByteBuffer bytes) { decoder.feed(bytes); return decoder.getDecodedMessages(); } } private Iterable<EventT> transformMessage(Message message) { try { if (isEvent(message)) { return transformEventMessage(message); } else if (isError(message) || isException(message)) { throw transformErrorMessage(message); } else { log.debug(() -> getLogPrefix() + "Decoded a message of an unknown type, it will be dropped: " + message); return emptyList(); } } catch (Error | SdkException e) { throw e; } catch (Throwable e) { throw SdkClientException.builder().cause(e).build(); } } private Iterable<EventT> transformEventMessage(Message message) throws Exception { SdkHttpFullResponse response = adaptMessageToResponse(message, false); if (message.getHeaders().get(":event-type").getString().equals("initial-response")) { ResponseT initialResponse = initialResponseHandler.handle(response, attributesFactory.get()); eventStreamResponseHandler.responseReceived(initialResponse); log.debug(() -> getLogPrefix() + "Decoded initial response: " + initialResponse); return emptyList(); } EventT event = eventResponseHandler.handle(response, attributesFactory.get()); log.debug(() -> getLogPrefix() + "Decoded event: " + event); return singleton(event); } private Throwable transformErrorMessage(Message message) throws Exception { SdkHttpFullResponse errorResponse = adaptMessageToResponse(message, true); Throwable exception = exceptionResponseHandler.handle(errorResponse, attributesFactory.get()); log.debug(() -> getLogPrefix() + "Decoded error or exception: " + exception, exception); return exception; } private String getLogPrefix() { if (requestId == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("("); stringBuilder.append("RequestId: ").append(requestId); if (extendedRequestId != null) { stringBuilder.append(", ExtendedRequestId: ").append(extendedRequestId); } stringBuilder.append(") "); return stringBuilder.toString(); } /** * Transforms an event stream message into a {@link SdkHttpFullResponse} so we can reuse our existing generated unmarshallers. * * @param message Message to transform. */ private SdkHttpFullResponse adaptMessageToResponse(Message message, boolean isException) { Map<String, List<String>> headers = message.getHeaders() .entrySet() .stream() .collect(HashMap::new, (m, e) -> m.put(e.getKey(), singletonList(e.getValue().getString())), Map::putAll); if (requestId != null) { headers.put(X_AMZN_REQUEST_ID_HEADER, singletonList(requestId)); } if (extendedRequestId != null) { headers.put(X_AMZ_ID_2_HEADER, singletonList(extendedRequestId)); } SdkHttpFullResponse.Builder builder = SdkHttpFullResponse.builder() .content(AbortableInputStream.create(new ByteArrayInputStream(message.getPayload()))) .headers(headers); if (!isException) { builder.statusCode(200); } return builder.build(); } /** * @param m Message frame. * @return True if frame is an event frame, false if not. */ private boolean isEvent(Message m) { return "event".equals(m.getHeaders().get(":message-type").getString()); } /** * @param m Message frame. * @return True if frame is an error frame, false if not. */ private boolean isError(Message m) { return "error".equals(m.getHeaders().get(":message-type").getString()); } /** * @param m Message frame. * @return True if frame is an exception frame, false if not. */ private boolean isException(Message m) { return "exception".equals(m.getHeaders().get(":message-type").getString()); } /** * Builder for {@link EventStreamAsyncResponseTransformer}. * * @param <ResponseT> Initial response type. * @param <EventT> Event type being delivered. */ public static final class Builder<ResponseT, EventT> { private EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler; private HttpResponseHandler<? extends ResponseT> initialResponseHandler; private HttpResponseHandler<? extends EventT> eventResponseHandler; private HttpResponseHandler<? extends Throwable> exceptionResponseHandler; private CompletableFuture<Void> future; private String serviceName; private Builder() { } /** * @param eventStreamResponseHandler Response handler provided by customer. * @return This object for method chaining. */ public Builder<ResponseT, EventT> eventStreamResponseHandler( EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) { this.eventStreamResponseHandler = eventStreamResponseHandler; return this; } /** * @param initialResponseHandler Response handler for the initial-response event stream message. * @return This object for method chaining. */ public Builder<ResponseT, EventT> initialResponseHandler( HttpResponseHandler<? extends ResponseT> initialResponseHandler) { this.initialResponseHandler = initialResponseHandler; return this; } /** * @param eventResponseHandler Response handler for the various event types. * @return This object for method chaining. */ public Builder<ResponseT, EventT> eventResponseHandler(HttpResponseHandler<? extends EventT> eventResponseHandler) { this.eventResponseHandler = eventResponseHandler; return this; } /** * @param exceptionResponseHandler Response handler for error and exception messages. * @return This object for method chaining. */ public Builder<ResponseT, EventT> exceptionResponseHandler( HttpResponseHandler<? extends Throwable> exceptionResponseHandler) { this.exceptionResponseHandler = exceptionResponseHandler; return this; } /** * This is no longer being used, but is left behind because this is a protected API. */ @Deprecated public Builder<ResponseT, EventT> executor(Executor executor) { return this; } /** * @param future Future to notify when the last event has been delivered. * @return This object for method chaining. */ public Builder<ResponseT, EventT> future(CompletableFuture<Void> future) { this.future = future; return this; } /** * @param serviceName Descriptive name for the service to be used in exception unmarshalling. * @return This object for method chaining. */ public Builder<ResponseT, EventT> serviceName(String serviceName) { this.serviceName = serviceName; return this; } public EventStreamAsyncResponseTransformer<ResponseT, EventT> build() { return new EventStreamAsyncResponseTransformer<>(eventStreamResponseHandler, initialResponseHandler, eventResponseHandler, exceptionResponseHandler, future, serviceName); } } }
1,238
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamInitialRequestInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT; import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.interceptor.Context.ModifyHttpRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.internal.async.AsyncStreamPrepender; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; /** * An interceptor for event stream requests sent over RPC. This interceptor will prepend the initial request (i.e. the * serialized request POJO) to the stream of events supplied by the caller. */ @SdkProtectedApi public class EventStreamInitialRequestInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest( ModifyHttpRequest context, ExecutionAttributes executionAttributes ) { if (!Boolean.TRUE.equals(executionAttributes.getAttribute(HAS_INITIAL_REQUEST_EVENT))) { return context.httpRequest(); } return context.httpRequest().toBuilder() .removeHeader(CONTENT_TYPE) .putHeader(CONTENT_TYPE, MIMETYPE_EVENT_STREAM) .build(); } @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent( ModifyHttpRequest context, ExecutionAttributes executionAttributes ) { if (!Boolean.TRUE.equals(executionAttributes.getAttribute(HAS_INITIAL_REQUEST_EVENT))) { return context.asyncRequestBody(); } /* * At this point in the request execution, the requestBody contains the serialized initial request, * and the asyncRequestBody contains the event stream proper. We will prepend the former to the * latter. */ byte[] payload = getInitialRequestPayload(context); String contentType = context.httpRequest() .firstMatchingHeader(CONTENT_TYPE) .orElseThrow(() -> new IllegalStateException(CONTENT_TYPE + " header not defined.")); Map<String, HeaderValue> initialRequestEventHeaders = new HashMap<>(); initialRequestEventHeaders.put(":message-type", HeaderValue.fromString("event")); initialRequestEventHeaders.put(":event-type", HeaderValue.fromString("initial-request")); initialRequestEventHeaders.put(":content-type", HeaderValue.fromString(contentType)); ByteBuffer initialRequest = new Message(initialRequestEventHeaders, payload).toByteBuffer(); Publisher<ByteBuffer> asyncRequestBody = context.asyncRequestBody() .orElseThrow(() -> new IllegalStateException("This request is an event streaming request and thus " + "should have an asyncRequestBody")); Publisher<ByteBuffer> withInitialRequest = new AsyncStreamPrepender<>(asyncRequestBody, initialRequest); return Optional.of(AsyncRequestBody.fromPublisher(withInitialRequest)); } private byte[] getInitialRequestPayload(ModifyHttpRequest context) { RequestBody requestBody = context.requestBody() .orElseThrow(() -> new IllegalStateException("This request should have a requestBody")); byte[] payload; try { try (InputStream inputStream = requestBody.contentStreamProvider().newStream()) { payload = new byte[inputStream.available()]; int bytesRead = inputStream.read(payload); if (bytesRead != payload.length) { throw new IllegalStateException("Expected " + payload.length + " bytes, but only got " + bytesRead + " bytes"); } } } catch (IOException ex) { throw new RuntimeException("Unable to read serialized request payload", ex); } return payload; } }
1,239
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamTaggedUnionJsonMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static java.util.stream.Collectors.toList; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullRequest; /** * Composite {@link Marshaller} that dispatches the given event to the * correct marshaller based on the event class type. * * @param <BaseEventT> Base type for all events. */ @SdkProtectedApi public final class EventStreamTaggedUnionJsonMarshaller<BaseEventT> implements Marshaller<BaseEventT> { private final Map<Class<? extends BaseEventT>, Marshaller<BaseEventT>> marshallers; private final Marshaller<BaseEventT> defaultMarshaller; private EventStreamTaggedUnionJsonMarshaller(Builder<BaseEventT> builder) { this.marshallers = new HashMap<>(builder.marshallers); this.defaultMarshaller = builder.defaultMarshaller; } @Override public SdkHttpFullRequest marshall(BaseEventT eventT) { return marshallers.getOrDefault(eventT.getClass(), defaultMarshaller).marshall(eventT); } public static Builder builder() { return new Builder(); } public static final class Builder<BaseEventT> { private final Map<Class<? extends BaseEventT>, Marshaller<BaseEventT>> marshallers = new HashMap<>(); private Marshaller<BaseEventT> defaultMarshaller; private Builder() { } /** * Registers a new {@link Marshaller} with given event class type. * * @param eventClass Class type of the event * @param marshaller Marshaller for the event * @return This object for method chaining */ public Builder putMarshaller(Class<? extends BaseEventT> eventClass, Marshaller<BaseEventT> marshaller) { marshallers.put(eventClass, marshaller); return this; } public EventStreamTaggedUnionJsonMarshaller<BaseEventT> build() { defaultMarshaller = e -> { String errorMsg = "Event type should be one of the following types: " + marshallers.keySet().stream().map(Class::getSimpleName).collect(toList()); throw new IllegalArgumentException(errorMsg); }; return new EventStreamTaggedUnionJsonMarshaller<>(this); } } }
1,240
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/DefaultEventStreamResponseHandlerBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.utils.async.SequentialSubscriber; /** * Base class for event stream response handler builders. * * @param <ResponseT> Type of POJO response. * @param <EventT> Type of event being published. * @param <SubBuilderT> Subtype of builder class for method chaining. */ @SdkProtectedApi public abstract class DefaultEventStreamResponseHandlerBuilder<ResponseT, EventT, SubBuilderT> implements EventStreamResponseHandler.Builder<ResponseT, EventT, SubBuilderT> { private Consumer<ResponseT> onResponse; private Consumer<Throwable> onError; private Runnable onComplete; private Supplier<Subscriber<EventT>> subscriber; private Consumer<SdkPublisher<EventT>> onSubscribe; private Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer; protected DefaultEventStreamResponseHandlerBuilder() { } @Override public SubBuilderT onResponse(Consumer<ResponseT> responseConsumer) { this.onResponse = responseConsumer; return subclass(); } Consumer<ResponseT> onResponse() { return onResponse; } @Override public SubBuilderT onError(Consumer<Throwable> consumer) { this.onError = consumer; return subclass(); } Consumer<Throwable> onError() { return onError; } @Override public SubBuilderT onComplete(Runnable onComplete) { this.onComplete = onComplete; return subclass(); } Runnable onComplete() { return onComplete; } @Override public SubBuilderT subscriber(Supplier<Subscriber<EventT>> eventSubscriber) { this.subscriber = eventSubscriber; return subclass(); } @Override public SubBuilderT subscriber(Consumer<EventT> eventConsumer) { this.subscriber = () -> new SequentialSubscriber<>(eventConsumer, new CompletableFuture<>()); return subclass(); } Supplier<Subscriber<EventT>> subscriber() { return subscriber; } @Override public SubBuilderT onEventStream(Consumer<SdkPublisher<EventT>> onSubscribe) { this.onSubscribe = onSubscribe; return subclass(); } Consumer<SdkPublisher<EventT>> onEventStream() { return onSubscribe; } @Override public SubBuilderT publisherTransformer(Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer) { this.publisherTransformer = publisherTransformer; return subclass(); } Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer() { return publisherTransformer; } private SubBuilderT subclass() { return (SubBuilderT) this; } }
1,241
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamResponseHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.async.SdkPublisher; /** * Response handler for event streaming operations. * * @param <ResponseT> the POJO response type * @param <EventT> the event type */ @SdkProtectedApi public interface EventStreamResponseHandler<ResponseT, EventT> { /** * Called when the initial response has been received and the POJO response has * been unmarshalled. This is guaranteed to be called before {@link #onEventStream(SdkPublisher)}. * * <p>In the event of a retryable error, this callback may be called multiple times. It * also may never be invoked if the request never succeeds.</p> * * @param response Unmarshalled POJO containing metadata about the streamed data. */ void responseReceived(ResponseT response); /** * Called when events are ready to be streamed. Implementations must subscribe to the {@link Publisher} and request data via * a {@link org.reactivestreams.Subscription} as they can handle it. * * <p> * If at any time the subscriber wishes to stop receiving data, it may call {@link Subscription#cancel()}. This * will <b>NOT</b> be treated as a failure of the response and the response will be completed normally. * </p> * * <p>This callback may never be called if the response has no content or if an error occurs.</p> * * <p> * In the event of a retryable error, this callback may be called multiple times with different Publishers. * If this method is called more than once, implementation must either reset any state to prepare for another * stream of data or must throw an exception indicating they cannot reset. If any exception is thrown then no * automatic retry is performed. * </p> */ void onEventStream(SdkPublisher<EventT> publisher); /** * Called when an exception occurs while establishing the connection or streaming the response. Implementations * should free up any resources in this method. This method may be called multiple times during the lifecycle * of a request if automatic retries are enabled. * * @param throwable Exception that occurred. */ void exceptionOccurred(Throwable throwable); /** * Called when all data has been successfully published to the {@link org.reactivestreams.Subscriber}. This will * only be called once during the lifecycle of the request. Implementors should free up any resources they have * opened. */ void complete(); /** * Base builder for sub-interfaces of {@link EventStreamResponseHandler}. */ interface Builder<ResponseT, EventT, SubBuilderT> { /** * Callback to invoke when the initial response is received. * * @param responseConsumer Callback that will process the initial response. * @return This builder for method chaining. */ SubBuilderT onResponse(Consumer<ResponseT> responseConsumer); /** * Callback to invoke in the event on an error. * * @param consumer Callback that will process any error that occurs. * @return This builder for method chaining. */ SubBuilderT onError(Consumer<Throwable> consumer); /** * Action to invoke when the event stream completes. This will only be invoked * when all events are being received. * * @param runnable Action to run on the completion of the event stream. * @return This builder for method chaining. */ SubBuilderT onComplete(Runnable runnable); /** * Subscriber that will subscribe to the {@link SdkPublisher} of events. Subscriber * must be provided. * * @param eventSubscriberSupplier Supplier for a subscriber that will be subscribed to the publisher of events. * @return This builder for method chaining. */ SubBuilderT subscriber(Supplier<Subscriber<EventT>> eventSubscriberSupplier); /** * Sets the subscriber to the {@link SdkPublisher} of events. The given consumer will be called for each event received * by the publisher. Events are requested sequentially after each event is processed. If you need more control over * the backpressure strategy consider using {@link #subscriber(Supplier)} instead. * * @param eventConsumer Consumer that will process incoming events. * @return This builder for method chaining. */ SubBuilderT subscriber(Consumer<EventT> eventConsumer); /** * Callback to invoke when the {@link SdkPublisher} is available. This callback must subscribe to the given publisher. * This method should not be used with {@link #subscriber(Supplier)} or any of it's overloads. * * @param onSubscribe Callback that will subscribe to the {@link SdkPublisher}. * @return This builder for method chaining. */ SubBuilderT onEventStream(Consumer<SdkPublisher<EventT>> onSubscribe); /** * Allows for optional transformation of the publisher of events before subscribing. This transformation must return * a {@link SdkPublisher} of the same type so methods like {@link SdkPublisher#map(Function)} and * {@link SdkPublisher#buffer(int)} that change the type cannot be used with this method. * * @param publisherTransformer Function that returns a new {@link SdkPublisher} with augmented behavior. * @return This builder for method chaining. */ SubBuilderT publisherTransformer(Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer); } }
1,242
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamTaggedUnionPojoSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.http.SdkHttpFullResponse; @SdkProtectedApi public final class EventStreamTaggedUnionPojoSupplier implements Function<SdkHttpFullResponse, SdkPojo> { private final Map<String, Supplier<SdkPojo>> pojoSuppliers; private final Supplier<SdkPojo> defaultPojoSupplier; private EventStreamTaggedUnionPojoSupplier(Builder builder) { this.pojoSuppliers = new HashMap<>(builder.pojoSuppliers); this.defaultPojoSupplier = builder.defaultPojoSupplier; } @Override public SdkPojo apply(SdkHttpFullResponse sdkHttpFullResponse) { String eventType = sdkHttpFullResponse.firstMatchingHeader(":event-type").orElse(null); return pojoSuppliers.getOrDefault(eventType, defaultPojoSupplier).get(); } public static Builder builder() { return new Builder(); } public static final class Builder { private final Map<String, Supplier<SdkPojo>> pojoSuppliers = new HashMap<>(); private Supplier<SdkPojo> defaultPojoSupplier; private Builder() { } /** * Registers a new {@link Supplier} of an {@link SdkPojo} associated with a given event type. * * @param type Value of ':event-type' header this unmarshaller handles. * @param pojoSupplier Supplier of {@link SdkPojo}. * @return This object for method chaining. */ public Builder putSdkPojoSupplier(String type, Supplier<SdkPojo> pojoSupplier) { pojoSuppliers.put(type, pojoSupplier); return this; } /** * Registers the default {@link SdkPojo} supplier. Used when the value in the ':event-type' header does not match * a registered event type (i.e. this is a new event that this version of the SDK doesn't know about). * * @param defaultPojoSupplier Default POJO supplier to use when event-type doesn't match a registered event type. * @return This object for method chaining. */ public Builder defaultSdkPojoSupplier(Supplier<SdkPojo> defaultPojoSupplier) { this.defaultPojoSupplier = defaultPojoSupplier; return this; } public EventStreamTaggedUnionPojoSupplier build() { return new EventStreamTaggedUnionPojoSupplier(this); } } }
1,243
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamResponseHandlerFromBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import static software.amazon.awssdk.utils.Validate.getOrDefault; import static software.amazon.awssdk.utils.Validate.mutuallyExclusive; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.reactivestreams.Subscriber; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.utils.FunctionalUtils; /** * Base class for creating implementations of an {@link EventStreamResponseHandler} from a builder. * See {@link EventStreamResponseHandler.Builder}. * * @param <ResponseT> Type of initial response object. * @param <EventT> Type of event being published. */ @SdkProtectedApi public abstract class EventStreamResponseHandlerFromBuilder<ResponseT, EventT> implements EventStreamResponseHandler<ResponseT, EventT> { private final Consumer<ResponseT> responseConsumer; private final Consumer<Throwable> errorConsumer; private final Runnable onComplete; private final Consumer<SdkPublisher<EventT>> onEventStream; private final Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer; protected EventStreamResponseHandlerFromBuilder(DefaultEventStreamResponseHandlerBuilder<ResponseT, EventT, ?> builder) { mutuallyExclusive("onEventStream and subscriber are mutually exclusive, set only one on the Builder", builder.onEventStream(), builder.subscriber()); Supplier<Subscriber<EventT>> subscriber = builder.subscriber(); this.onEventStream = subscriber != null ? p -> p.subscribe(subscriber.get()) : builder.onEventStream(); if (this.onEventStream == null) { throw new IllegalArgumentException("Must provide either a subscriber or set onEventStream " + "and subscribe to the publisher in the callback method"); } this.responseConsumer = getOrDefault(builder.onResponse(), FunctionalUtils::noOpConsumer); this.errorConsumer = getOrDefault(builder.onError(), FunctionalUtils::noOpConsumer); this.onComplete = getOrDefault(builder.onComplete(), FunctionalUtils::noOpRunnable); this.publisherTransformer = getOrDefault(builder.publisherTransformer(), Function::identity); } @Override public void responseReceived(ResponseT response) { responseConsumer.accept(response); } @Override public void onEventStream(SdkPublisher<EventT> p) { onEventStream.accept(publisherTransformer.apply(p)); } @Override public void exceptionOccurred(Throwable throwable) { errorConsumer.accept(throwable); } @Override public void complete() { this.onComplete.run(); } }
1,244
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/RestEventStreamAsyncResponseTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.eventstream; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.SdkPublisher; /** * Adapter transformer meant for eventstream responses from REST services (REST-XML, REST-JSON). These protocols don't have an * 'initial-response' event, unlike AWS-JSON. In these protocols "initial response" is treated as the HTTP response itself. * When this transformer's {@link #onResponse(SdkResponse)} method is invoked, it also invokes it on the eventstream * response handler, which the normal {@link EventStreamAsyncResponseTransformer} does not do. * * @param <ResponseT> Initial response type of event stream operation. * @param <EventT> Base type of event stream message frames. */ @SdkProtectedApi public class RestEventStreamAsyncResponseTransformer<ResponseT extends SdkResponse, EventT> implements AsyncResponseTransformer<ResponseT, Void> { private final EventStreamAsyncResponseTransformer<ResponseT, EventT> delegate; private final EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler; private RestEventStreamAsyncResponseTransformer( EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer, EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) { this.delegate = delegateAsyncResponseTransformer; this.eventStreamResponseHandler = eventStreamResponseHandler; } @Override public CompletableFuture<Void> prepare() { return delegate.prepare(); } @Override public void onResponse(ResponseT response) { delegate.onResponse(response); eventStreamResponseHandler.responseReceived(response); } @Override public void onStream(SdkPublisher<ByteBuffer> publisher) { delegate.onStream(publisher); } @Override public void exceptionOccurred(Throwable throwable) { delegate.exceptionOccurred(throwable); } public static <ResponseT extends SdkResponse, EventT> Builder<ResponseT, EventT> builder() { return new Builder<>(); } /** * Builder for {@link RestEventStreamAsyncResponseTransformer}. * * @param <ResponseT> Initial response type. * @param <EventT> Event type being delivered. */ public static final class Builder<ResponseT extends SdkResponse, EventT> { private EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer; private EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler; private Builder() { } /** * @param delegateAsyncResponseTransformer {@link EventStreamAsyncResponseTransformer} that can be delegated the work * common for RPC and REST services * @return This object for method chaining */ public Builder<ResponseT, EventT> eventStreamAsyncResponseTransformer( EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer) { this.delegateAsyncResponseTransformer = delegateAsyncResponseTransformer; return this; } /** * @param eventStreamResponseHandler Response handler provided by customer. * @return This object for method chaining. */ public Builder<ResponseT, EventT> eventStreamResponseHandler( EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) { this.eventStreamResponseHandler = eventStreamResponseHandler; return this; } public RestEventStreamAsyncResponseTransformer<ResponseT, EventT> build() { return new RestEventStreamAsyncResponseTransformer<>(delegateAsyncResponseTransformer, eventStreamResponseHandler); } } }
1,245
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/AwsEndpointAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoints; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme; import software.amazon.awssdk.endpoints.EndpointAttributeKey; /** * Known endpoint attributes added by endpoint rule sets for AWS services. */ @SdkProtectedApi public final class AwsEndpointAttribute { /** * The auth schemes supported by the endpoint. */ public static final EndpointAttributeKey<List<EndpointAuthScheme>> AUTH_SCHEMES = EndpointAttributeKey.forList("AuthSchemes"); private AwsEndpointAttribute() { } public static List<EndpointAttributeKey<?>> values() { return Collections.singletonList(AUTH_SCHEMES); } }
1,246
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/EndpointAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoints.authscheme; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.endpoints.Endpoint; /** * An authentication scheme for an {@link Endpoint} returned by an endpoint provider. */ @SdkProtectedApi public interface EndpointAuthScheme { String name(); default String schemeId() { throw new UnsupportedOperationException(); } }
1,247
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/SigV4AuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoints.authscheme; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A Signature Version 4 authentication scheme. */ @SdkProtectedApi public final class SigV4AuthScheme implements EndpointAuthScheme { private final String signingRegion; private final String signingName; private final Boolean disableDoubleEncoding; private SigV4AuthScheme(Builder b) { this.signingRegion = b.signingRegion; this.signingName = b.signingName; this.disableDoubleEncoding = b.disableDoubleEncoding; } @Override public String name() { return "sigv4"; } @Override public String schemeId() { return "aws.auth#sigv4"; } public String signingRegion() { return signingRegion; } public String signingName() { return signingName; } public boolean disableDoubleEncoding() { return disableDoubleEncoding == null ? false : disableDoubleEncoding; } public boolean isDisableDoubleEncodingSet() { return disableDoubleEncoding != null; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SigV4AuthScheme that = (SigV4AuthScheme) o; if (disableDoubleEncoding != null ? !disableDoubleEncoding.equals(that.disableDoubleEncoding) : that.disableDoubleEncoding != null) { return false; } if (signingRegion != null ? !signingRegion.equals(that.signingRegion) : that.signingRegion != null) { return false; } return signingName != null ? signingName.equals(that.signingName) : that.signingName == null; } @Override public int hashCode() { int result = signingRegion != null ? signingRegion.hashCode() : 0; result = 31 * result + (signingName != null ? signingName.hashCode() : 0); result = 31 * result + (disableDoubleEncoding != null ? disableDoubleEncoding.hashCode() : 0); return result; } public static Builder builder() { return new Builder(); } public static class Builder { private String signingRegion; private String signingName; private Boolean disableDoubleEncoding; public Builder signingRegion(String signingRegion) { this.signingRegion = signingRegion; return this; } public Builder signingName(String signingName) { this.signingName = signingName; return this; } public Builder disableDoubleEncoding(Boolean disableDoubleEncoding) { this.disableDoubleEncoding = disableDoubleEncoding; return this; } public SigV4AuthScheme build() { return new SigV4AuthScheme(this); } } }
1,248
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/SigV4aAuthScheme.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoints.authscheme; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A Signature Version 4A authentication scheme. */ @SdkProtectedApi public final class SigV4aAuthScheme implements EndpointAuthScheme { private final String signingName; private final List<String> signingRegionSet; private final Boolean disableDoubleEncoding; private SigV4aAuthScheme(Builder b) { this.signingName = b.signingName; this.signingRegionSet = b.signingRegionSet; this.disableDoubleEncoding = b.disableDoubleEncoding; } public String signingName() { return signingName; } public boolean disableDoubleEncoding() { return disableDoubleEncoding == null ? false : disableDoubleEncoding; } public boolean isDisableDoubleEncodingSet() { return disableDoubleEncoding != null; } public List<String> signingRegionSet() { return signingRegionSet; } @Override public String name() { return "sigv4a"; } @Override public String schemeId() { return "aws.auth#sigv4a"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SigV4aAuthScheme that = (SigV4aAuthScheme) o; if (disableDoubleEncoding != null ? !disableDoubleEncoding.equals(that.disableDoubleEncoding) : that.disableDoubleEncoding != null) { return false; } if (signingName != null ? !signingName.equals(that.signingName) : that.signingName != null) { return false; } return signingRegionSet != null ? signingRegionSet.equals(that.signingRegionSet) : that.signingRegionSet == null; } @Override public int hashCode() { int result = signingName != null ? signingName.hashCode() : 0; result = 31 * result + (signingRegionSet != null ? signingRegionSet.hashCode() : 0); result = 31 * result + (disableDoubleEncoding != null ? disableDoubleEncoding.hashCode() : 0); return result; } public static Builder builder() { return new Builder(); } public static class Builder { private final List<String> signingRegionSet = new ArrayList<>(); private String signingName; private Boolean disableDoubleEncoding; public Builder addSigningRegion(String signingRegion) { this.signingRegionSet.add(signingRegion); return this; } public Builder signingName(String signingName) { this.signingName = signingName; return this; } public Builder disableDoubleEncoding(Boolean disableDoubleEncoding) { this.disableDoubleEncoding = disableDoubleEncoding; return this; } public SigV4aAuthScheme build() { return new SigV4aAuthScheme(this); } } }
1,249
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry/AwsRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.internal.AwsErrorCode; import software.amazon.awssdk.awscore.retry.conditions.RetryOnErrorCodeCondition; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.conditions.OrRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; /** * Retry Policy used by clients when communicating with AWS services. */ @SdkPublicApi public final class AwsRetryPolicy { private AwsRetryPolicy() { } /** * Retrieve the {@link RetryCondition#defaultRetryCondition()} with AWS-specific conditions added. */ public static RetryCondition defaultRetryCondition() { return OrRetryCondition.create(RetryCondition.defaultRetryCondition(), awsRetryCondition()); } /** * Retrieve the {@link RetryPolicy#defaultRetryPolicy()} with AWS-specific conditions added. */ public static RetryPolicy defaultRetryPolicy() { return forRetryMode(RetryMode.defaultRetryMode()); } /** * Retrieve the {@link RetryPolicy#defaultRetryPolicy()} with AWS-specific conditions added. This uses the specified * {@link RetryMode} when constructing the {@link RetryPolicy}. */ public static RetryPolicy forRetryMode(RetryMode retryMode) { return addRetryConditions(RetryPolicy.forRetryMode(retryMode)); } /** * Update the provided {@link RetryPolicy} to add AWS-specific conditions. */ public static RetryPolicy addRetryConditions(RetryPolicy condition) { return condition.toBuilder() .retryCondition(OrRetryCondition.create(condition.retryCondition(), awsRetryCondition())) .build(); } private static RetryOnErrorCodeCondition awsRetryCondition() { return RetryOnErrorCodeCondition.create(AwsErrorCode.RETRYABLE_ERROR_CODES); } }
1,250
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry/conditions/RetryOnErrorCodeCondition.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.retry.conditions; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.core.retry.conditions.RetryCondition; /** * Retry condition implementation that retries if the exception or the cause of the exception matches the error codes defined. */ @SdkPublicApi public final class RetryOnErrorCodeCondition implements RetryCondition { private final Set<String> retryableErrorCodes; private RetryOnErrorCodeCondition(Set<String> retryableErrorCodes) { this.retryableErrorCodes = retryableErrorCodes; } @Override public boolean shouldRetry(RetryPolicyContext context) { Exception ex = context.exception(); if (ex instanceof AwsServiceException) { AwsServiceException exception = (AwsServiceException) ex; return retryableErrorCodes.contains(exception.awsErrorDetails().errorCode()); } return false; } public static RetryOnErrorCodeCondition create(String... retryableErrorCodes) { return new RetryOnErrorCodeCondition(Arrays.stream(retryableErrorCodes).collect(Collectors.toSet())); } public static RetryOnErrorCodeCondition create(Set<String> retryableErrorCodes) { return new RetryOnErrorCodeCondition(retryableErrorCodes); } }
1,251
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/AwsHostNameUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.regions.Region; @SdkProtectedApi //TODO This isn't used for as many services as it supports. Can we simplify or remove it? public final class AwsHostNameUtils { private static final Pattern S3_ENDPOINT_PATTERN = Pattern.compile("^(?:.+\\.)?s3[.-]([a-z0-9-]+)$"); private static final Pattern STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN = Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch$"); private static final Pattern EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN = Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch\\..+"); private AwsHostNameUtils() { } /** * Attempts to parse the region name from an endpoint based on conventions * about the endpoint format. * * @param host the hostname to parse * @param serviceHint an optional hint about the service for the endpoint * @return the region parsed from the hostname, or * null if no region information could be found. */ public static Optional<Region> parseSigningRegion(final String host, final String serviceHint) { if (host == null) { throw new IllegalArgumentException("hostname cannot be null"); } if (host.endsWith(".amazonaws.com")) { int index = host.length() - ".amazonaws.com".length(); return parseStandardRegionName(host.substring(0, index)); } if (serviceHint != null) { if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) { // CloudSearch domains use the nonstandard domain format // [domain].[region].cloudsearch.[suffix]. Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(host); if (matcher.matches()) { return Optional.of(Region.of(matcher.group(1))); } } // If we have a service hint, look for 'service.[region]' or // 'service-[region]' in the endpoint's hostname. Pattern pattern = Pattern.compile("^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\."); Matcher matcher = pattern.matcher(host); if (matcher.find()) { return Optional.of(Region.of(matcher.group(1))); } } // Endpoint is non-standard return Optional.empty(); } /** * Parses the region name from a standard (*.amazonaws.com) endpoint. * * @param fragment the portion of the endpoint excluding * &quot;.amazonaws.com&quot; * @return the parsed region name (or &quot;us-east-1&quot; as a * best guess if we can't tell for sure) */ private static Optional<Region> parseStandardRegionName(final String fragment) { Matcher matcher = S3_ENDPOINT_PATTERN.matcher(fragment); if (matcher.matches()) { // host was 'bucket.s3-[region].amazonaws.com'. return Optional.of(Region.of(matcher.group(1))); } matcher = STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(fragment); if (matcher.matches()) { // host was 'domain.[region].cloudsearch.amazonaws.com'. return Optional.of(Region.of(matcher.group(1))); } int index = fragment.lastIndexOf('.'); if (index == -1) { // host was 'service.amazonaws.com', assume they're talking about us-east-1. return Optional.of(Region.US_EAST_1); } // host was 'service.[region].amazonaws.com'. String region = fragment.substring(index + 1); // Special case for iam.us-gov.amazonaws.com, which is actually // us-gov-west-1. if ("us-gov".equals(region)) { region = "us-gov-west-1"; } if ("s3".equals(region)) { region = fragment.substring(index + 4); } return Optional.of(Region.of(region)); } }
1,252
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/AwsHeader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Constants for commonly used Aws headers. */ @SdkProtectedApi public final class AwsHeader { public static final String AWS_REQUEST_ID = "AWS_REQUEST_ID"; private AwsHeader() { } }
1,253
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/SignerOverrideUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.util; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.signer.Signer; /** * Utility to override a given {@link SdkRequest}'s {@link Signer}. Typically used by {@link ExecutionInterceptor}s that wish to * dynamically enable particular signing methods, like SigV4a for multi-region endpoints. */ @SdkProtectedApi public final class SignerOverrideUtils { private SignerOverrideUtils() { } /** * @deprecated No longer used by modern clients after migration to reference architecture */ @Deprecated public static SdkRequest overrideSignerIfNotOverridden(SdkRequest request, ExecutionAttributes executionAttributes, Signer signer) { return overrideSignerIfNotOverridden(request, executionAttributes, () -> signer); } /** * @deprecated No longer used by modern clients after migration to reference architecture */ @Deprecated public static SdkRequest overrideSignerIfNotOverridden(SdkRequest request, ExecutionAttributes executionAttributes, Supplier<Signer> signer) { if (isSignerOverridden(request, executionAttributes)) { return request; } return overrideSigner(request, signer.get()); } public static boolean isSignerOverridden(SdkRequest request, ExecutionAttributes executionAttributes) { boolean isClientSignerOverridden = Boolean.TRUE.equals(executionAttributes.getAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN)); Optional<Signer> requestSigner = request.overrideConfiguration() .flatMap(RequestOverrideConfiguration::signer); return isClientSignerOverridden || requestSigner.isPresent(); } /** * @deprecated No longer used by modern clients after migration to reference architecture */ @Deprecated private static SdkRequest overrideSigner(SdkRequest request, Signer signer) { return request.overrideConfiguration() .flatMap(config -> config.signer() .map(existingOverrideSigner -> request)) .orElseGet(() -> createNewRequest(request, signer)); } /** * @deprecated No longer used by modern clients after migration to reference architecture */ @Deprecated private static SdkRequest createNewRequest(SdkRequest request, Signer signer) { AwsRequest awsRequest = (AwsRequest) request; AwsRequestOverrideConfiguration modifiedOverride = awsRequest.overrideConfiguration() .map(AwsRequestOverrideConfiguration::toBuilder) .orElseGet(AwsRequestOverrideConfiguration::builder) .signer(signer) .build(); return awsRequest.toBuilder() .overrideConfiguration(modifiedOverride) .build(); } }
1,254
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsStatusCode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import static java.util.Collections.unmodifiableSet; import java.util.HashSet; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Contains AWS-specific meanings behind status codes. */ @SdkInternalApi public class AwsStatusCode { public static final Set<Integer> POSSIBLE_CLOCK_SKEW_STATUS_CODES; static { Set<Integer> clockSkewErrorCodes = new HashSet<>(2); clockSkewErrorCodes.add(401); clockSkewErrorCodes.add(403); POSSIBLE_CLOCK_SKEW_STATUS_CODES = unmodifiableSet(clockSkewErrorCodes); } private AwsStatusCode() { } public static boolean isPossibleClockSkewStatusCode(int statusCode) { return POSSIBLE_CLOCK_SKEW_STATUS_CODES.contains(statusCode); } }
1,255
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsExecutionContextBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import static software.amazon.awssdk.auth.signer.internal.util.SignerMethodResolver.resolveSigningMethodUsed; import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.internal.authcontext.AuthorizationStrategy; import software.amazon.awssdk.awscore.internal.authcontext.AuthorizationStrategyFactory; import software.amazon.awssdk.awscore.util.SignerOverrideUtils; import software.amazon.awssdk.core.HttpChecksumConstant; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.SelectedAuthScheme; 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.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.http.ExecutionContext; 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.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute; import software.amazon.awssdk.core.internal.util.HttpChecksumResolver; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.metrics.MetricCollector; @SdkInternalApi public final class AwsExecutionContextBuilder { private AwsExecutionContextBuilder() { } /** * Used by both sync and async clients to create the execution context, and run initial interceptors. */ public static <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams, SdkClientConfiguration clientConfig) { // Note: This is currently copied to DefaultS3Presigner and other presigners. // Don't edit this without considering those SdkRequest originalRequest = executionParams.getInput(); MetricCollector metricCollector = resolveMetricCollector(executionParams); ExecutionAttributes executionAttributes = mergeExecutionAttributeOverrides( executionParams.executionAttributes(), clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES), originalRequest.overrideConfiguration().map(c -> c.executionAttributes()).orElse(null)); executionAttributes.putAttributeIfAbsent(SdkExecutionAttribute.API_CALL_METRIC_COLLECTOR, metricCollector); executionAttributes .putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1) .putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG, clientConfig.option(SdkClientOption.SERVICE_CONFIGURATION)) .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, clientConfig.option(AwsClientOption.SERVICE_SIGNING_NAME)) .putAttribute(AwsExecutionAttribute.AWS_REGION, clientConfig.option(AwsClientOption.AWS_REGION)) .putAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX, clientConfig.option(AwsClientOption.ENDPOINT_PREFIX)) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, clientConfig.option(AwsClientOption.SIGNING_REGION)) .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, executionParams.isFullDuplex()) .putAttribute(SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT, executionParams.hasInitialRequestEvent()) .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, clientConfig.option(SdkClientOption.CLIENT_TYPE)) .putAttribute(SdkExecutionAttribute.SERVICE_NAME, clientConfig.option(SdkClientOption.SERVICE_NAME)) .putAttribute(SdkInternalExecutionAttribute.PROTOCOL_METADATA, executionParams.getProtocolMetadata()) .putAttribute(SdkExecutionAttribute.PROFILE_FILE, clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER) != null ? clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER).get() : null) .putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER, clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER)) .putAttribute(SdkExecutionAttribute.PROFILE_NAME, clientConfig.option(SdkClientOption.PROFILE_NAME)) .putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED, clientConfig.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED)) .putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED, clientConfig.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)) .putAttribute(SdkExecutionAttribute.OPERATION_NAME, executionParams.getOperationName()) .putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, clientConfig.option(SdkClientOption.ENDPOINT)) .putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, clientConfig.option(SdkClientOption.ENDPOINT_OVERRIDDEN)) .putAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER, resolveEndpointProvider(originalRequest, clientConfig)) .putAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS, clientConfig.option(SdkClientOption.CLIENT_CONTEXT_PARAMS)) .putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION, clientConfig.option(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION)) .putAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN, clientConfig.option(SdkClientOption.SIGNER_OVERRIDDEN)) .putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT, clientConfig.option(AwsClientOption.USE_GLOBAL_ENDPOINT)) .putAttribute(RESOLVED_CHECKSUM_SPECS, HttpChecksumResolver.resolveChecksumSpecs(executionAttributes)); // Auth Scheme resolution related attributes putAuthSchemeResolutionAttributes(executionAttributes, clientConfig, originalRequest); ExecutionInterceptorChain executionInterceptorChain = new ExecutionInterceptorChain(clientConfig.option(SdkClientOption.EXECUTION_INTERCEPTORS)); InterceptorContext interceptorContext = InterceptorContext.builder() .request(originalRequest) .asyncRequestBody(executionParams.getAsyncRequestBody()) .requestBody(executionParams.getRequestBody()) .build(); interceptorContext = runInitialInterceptors(interceptorContext, executionAttributes, executionInterceptorChain); Signer signer = null; if (loadOldSigner(executionAttributes, originalRequest)) { AuthorizationStrategyFactory authorizationStrategyFactory = new AuthorizationStrategyFactory(interceptorContext.request(), metricCollector, clientConfig); AuthorizationStrategy authorizationStrategy = authorizationStrategyFactory.strategyFor(executionParams.credentialType()); authorizationStrategy.addCredentialsToExecutionAttributes(executionAttributes); signer = authorizationStrategy.resolveSigner(); } executionAttributes.putAttribute(HttpChecksumConstant.SIGNING_METHOD, resolveSigningMethodUsed( signer, executionAttributes, executionAttributes.getOptionalAttribute( AwsSignerExecutionAttribute.AWS_CREDENTIALS).orElse(null))); return ExecutionContext.builder() .interceptorChain(executionInterceptorChain) .interceptorContext(interceptorContext) .executionAttributes(executionAttributes) .signer(signer) .metricCollector(metricCollector) .build(); } /** * We will load the old (non-SRA) signer if this client seems like an old version or the customer has provided a signer * override. We assume that if there's no auth schemes defined, we're on the old code path. * <p> * In addition, if authType=none, we don't need to use the old signer, even if overridden. */ private static boolean loadOldSigner(ExecutionAttributes attributes, SdkRequest request) { Map<String, AuthScheme<?>> authSchemes = attributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES); if (authSchemes == null) { // pre SRA case. // We used to set IS_NONE_AUTH_TYPE_REQUEST = false when authType=none. Yes, false. return attributes.getOptionalAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST).orElse(true); } // post SRA case. // By default, SRA uses new HttpSigner, so we shouldn't use old non-SRA Signer, unless the customer has provided a signer // override. // But, if the operation was modeled as authTpye=None, we don't want to use the provided overridden Signer either. In // post SRA, modeled authType=None would default to NoAuthAuthScheme. // Note, for authType=None operation, technically, customer could override the AuthSchemeProvider and select a different // AuthScheme (than NoAuthAuthScheme). In this case, we are choosing to use the customer's overridden Signer. SelectedAuthScheme<?> selectedAuthScheme = attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME); return SignerOverrideUtils.isSignerOverridden(request, attributes) && selectedAuthScheme != null && !NoAuthAuthScheme.SCHEME_ID.equals(selectedAuthScheme.authSchemeOption().schemeId()); } private static void putAuthSchemeResolutionAttributes(ExecutionAttributes executionAttributes, SdkClientConfiguration clientConfig, SdkRequest originalRequest) { // TODO(sra-identity-and-auth): When request-level auth scheme provider is added, use the request-level auth scheme // provider if the customer specified an override, otherwise fall back to the one on the client. AuthSchemeProvider authSchemeProvider = clientConfig.option(SdkClientOption.AUTH_SCHEME_PROVIDER); // Use auth schemes that the user specified at the request level with // preference over those on the client. // TODO(sra-identity-and-auth): The request level schemes should be "merged" with client level, with request preferred // over client. Map<String, AuthScheme<?>> authSchemes = clientConfig.option(SdkClientOption.AUTH_SCHEMES); IdentityProviders identityProviders = resolveIdentityProviders(originalRequest, clientConfig); executionAttributes .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER, authSchemeProvider) .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES, authSchemes) .putAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS, identityProviders); } // TODO(sra-identity-and-auth): This is hard coding the logic for the credentialsIdentityProvider from // AwsRequestOverrideConfiguration. Currently, AwsRequestOverrideConfiguration does not support overriding the // tokenIdentityProvider. When adding that support this method will need to be updated. private static IdentityProviders resolveIdentityProviders(SdkRequest originalRequest, SdkClientConfiguration clientConfig) { IdentityProviders identityProviders = clientConfig.option(SdkClientOption.IDENTITY_PROVIDERS); // identityProviders can be null, for new core with old client. In this case, even if AwsRequestOverrideConfiguration // has credentialsIdentityProvider set (because it is in new core), it is ok to not setup IDENTITY_PROVIDERS, as old // client won't have AUTH_SCHEME_PROVIDER/AUTH_SCHEMES set either, which are also needed for SRA logic. if (identityProviders == null) { return null; } return originalRequest.overrideConfiguration() .filter(c -> c instanceof AwsRequestOverrideConfiguration) .map(c -> (AwsRequestOverrideConfiguration) c) .flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider) .map(identityProvider -> identityProviders.copy(b -> b.putIdentityProvider(identityProvider))) .orElse(identityProviders); } /** * Finalize {@link SdkRequest} by running beforeExecution and modifyRequest interceptors. * * @param interceptorContext containing the immutable SdkRequest information the interceptor can act on * @param executionAttributes mutable container of attributes concerning the execution and request * @return the {@link InterceptorContext} returns a context with a new SdkRequest */ public static InterceptorContext runInitialInterceptors(InterceptorContext interceptorContext, ExecutionAttributes executionAttributes, ExecutionInterceptorChain executionInterceptorChain) { executionInterceptorChain.beforeExecution(interceptorContext, executionAttributes); return executionInterceptorChain.modifyRequest(interceptorContext, executionAttributes); } private static <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionAttributes mergeExecutionAttributeOverrides( ExecutionAttributes executionAttributes, ExecutionAttributes clientOverrideExecutionAttributes, ExecutionAttributes requestOverrideExecutionAttributes) { executionAttributes.putAbsentAttributes(requestOverrideExecutionAttributes); executionAttributes.putAbsentAttributes(clientOverrideExecutionAttributes); return executionAttributes; } private static MetricCollector resolveMetricCollector(ClientExecutionParams<?, ?> params) { MetricCollector metricCollector = params.getMetricCollector(); if (metricCollector == null) { metricCollector = MetricCollector.create("ApiCall"); } return metricCollector; } /** * Resolves the endpoint provider, with the request override configuration taking precedence over the * provided default client clientConfig. * @return The endpoint provider that will be used by the SDK to resolve endpoints. */ private static EndpointProvider resolveEndpointProvider(SdkRequest request, SdkClientConfiguration clientConfig) { return request.overrideConfiguration() .flatMap(RequestOverrideConfiguration::endpointProvider) .orElse(clientConfig.option(SdkClientOption.ENDPOINT_PROVIDER)); } }
1,256
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsServiceProtocol.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public enum AwsServiceProtocol { EC2("ec2"), AWS_JSON("json"), REST_JSON("rest-json"), CBOR("cbor"), QUERY("query"), REST_XML("rest-xml"); private String protocol; AwsServiceProtocol(String protocol) { this.protocol = protocol; } public static AwsServiceProtocol fromValue(String strProtocol) { if (strProtocol == null) { return null; } for (AwsServiceProtocol protocol : values()) { if (protocol.protocol.equals(strProtocol)) { return protocol; } } throw new IllegalArgumentException("Unknown enum value for Protocol : " + strProtocol); } @Override public String toString() { return protocol; } }
1,257
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsErrorCode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import static java.util.Collections.unmodifiableSet; import java.util.HashSet; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Contains AWS error codes. */ @SdkInternalApi public final class AwsErrorCode { public static final Set<String> RETRYABLE_ERROR_CODES; public static final Set<String> THROTTLING_ERROR_CODES; public static final Set<String> DEFINITE_CLOCK_SKEW_ERROR_CODES; public static final Set<String> POSSIBLE_CLOCK_SKEW_ERROR_CODES; static { Set<String> throttlingErrorCodes = new HashSet<>(9); throttlingErrorCodes.add("Throttling"); throttlingErrorCodes.add("ThrottlingException"); throttlingErrorCodes.add("ThrottledException"); throttlingErrorCodes.add("ProvisionedThroughputExceededException"); throttlingErrorCodes.add("SlowDown"); throttlingErrorCodes.add("TooManyRequestsException"); throttlingErrorCodes.add("RequestLimitExceeded"); throttlingErrorCodes.add("BandwidthLimitExceeded"); throttlingErrorCodes.add("RequestThrottled"); throttlingErrorCodes.add("RequestThrottledException"); throttlingErrorCodes.add("EC2ThrottledException"); throttlingErrorCodes.add("TransactionInProgressException"); THROTTLING_ERROR_CODES = unmodifiableSet(throttlingErrorCodes); Set<String> definiteClockSkewErrorCodes = new HashSet<>(3); definiteClockSkewErrorCodes.add("RequestTimeTooSkewed"); definiteClockSkewErrorCodes.add("RequestExpired"); definiteClockSkewErrorCodes.add("RequestInTheFuture"); DEFINITE_CLOCK_SKEW_ERROR_CODES = unmodifiableSet(definiteClockSkewErrorCodes); Set<String> possibleClockSkewErrorCodes = new HashSet<>(3); possibleClockSkewErrorCodes.add("InvalidSignatureException"); possibleClockSkewErrorCodes.add("SignatureDoesNotMatch"); possibleClockSkewErrorCodes.add("AuthFailure"); POSSIBLE_CLOCK_SKEW_ERROR_CODES = unmodifiableSet(possibleClockSkewErrorCodes); Set<String> retryableErrorCodes = new HashSet<>(1); retryableErrorCodes.add("PriorRequestNotComplete"); retryableErrorCodes.add("RequestTimeout"); retryableErrorCodes.add("RequestTimeoutException"); retryableErrorCodes.add("InternalError"); RETRYABLE_ERROR_CODES = unmodifiableSet(retryableErrorCodes); } private AwsErrorCode() { } public static boolean isThrottlingErrorCode(String errorCode) { return THROTTLING_ERROR_CODES.contains(errorCode); } public static boolean isDefiniteClockSkewErrorCode(String errorCode) { return DEFINITE_CLOCK_SKEW_ERROR_CODES.contains(errorCode); } public static boolean isPossibleClockSkewErrorCode(String errorCode) { return POSSIBLE_CLOCK_SKEW_ERROR_CODES.contains(errorCode); } public static boolean isRetryableErrorCode(String errorCode) { return RETRYABLE_ERROR_CODES.contains(errorCode); } }
1,258
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsProtocolMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkProtocolMetadata; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Contains AWS-specific protocol metadata. Implementation of {@link SdkProtocolMetadata}. */ @SdkInternalApi public final class AwsProtocolMetadata implements SdkProtocolMetadata, ToCopyableBuilder<AwsProtocolMetadata.Builder, AwsProtocolMetadata> { private final AwsServiceProtocol serviceProtocol; private AwsProtocolMetadata(Builder builder) { this.serviceProtocol = builder.serviceProtocol; } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } @Override public String serviceProtocol() { return serviceProtocol.toString(); } @Override public String toString() { return ToString.builder("AwsProtocolMetadata") .add("serviceProtocol", serviceProtocol) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsProtocolMetadata protocolMetadata = (AwsProtocolMetadata) o; return serviceProtocol == protocolMetadata.serviceProtocol; } @Override public int hashCode() { return serviceProtocol != null ? serviceProtocol.hashCode() : 0; } public static final class Builder implements CopyableBuilder<Builder, AwsProtocolMetadata> { private AwsServiceProtocol serviceProtocol; private Builder() { } private Builder(AwsProtocolMetadata protocolMetadata) { this.serviceProtocol = protocolMetadata.serviceProtocol; } public Builder serviceProtocol(AwsServiceProtocol serviceProtocol) { this.serviceProtocol = serviceProtocol; return this; } @Override public AwsProtocolMetadata build() { return new AwsProtocolMetadata(this); } } }
1,259
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenRefresher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Interface to refresh token. * @param <T> Class that is a AwsToken. */ @SdkInternalApi public interface TokenRefresher<T extends SdkToken> extends SdkAutoCloseable { /** * Gets the fresh token from the service or provided suppliers. * @return Fresh AwsToken as supplied by suppliers. */ T refreshIfStaleAndFetch(); }
1,260
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenTransformer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.awscore.AwsResponse; /** * Transformer to convert the response received from service to respective Token objects. * @param <T> AwsToken that needs to be transformed to. * @param <R> AwsResponse that needs to be transformed from. */ @SdkInternalApi public interface TokenTransformer<T extends SdkToken, R extends AwsResponse> { /** * API to convert the response received from the service to Token. * @param awsResponse Response received from service which will have token details. * @return */ T transform(R awsResponse); }
1,261
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenManager.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * An object that knows how to load and optionally, store, an SSO token. */ @SdkInternalApi public interface TokenManager<T extends SdkToken> extends SdkAutoCloseable { Optional<T> loadToken(); default void storeToken(T token) { throw new UnsupportedOperationException(); } }
1,262
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/CachedTokenRefresher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.token; import java.time.Duration; import java.time.Instant; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.cache.CachedSupplier; import software.amazon.awssdk.utils.cache.NonBlocking; import software.amazon.awssdk.utils.cache.RefreshResult; /** * Class to cache Tokens which are supplied by the Suppliers while constructing this class. Automatic refresh can be enabled by * setting autoRefreshDuration in builder methods. */ @ThreadSafe @SdkInternalApi public final class CachedTokenRefresher<TokenT extends SdkToken> implements TokenRefresher<TokenT> { private static final Duration DEFAULT_STALE_TIME = Duration.ofMinutes(1); private static final String THREAD_CLASS_NAME = "sdk-token-refresher"; private final Supplier<TokenT> tokenRetriever; private final Duration staleDuration; private final Duration prefetchDuration; private final Function<SdkException, TokenT> exceptionHandler; private final CachedSupplier<TokenT> tokenCacheSupplier; private CachedTokenRefresher(Builder builder) { Validate.paramNotNull(builder.tokenRetriever, "tokenRetriever"); this.staleDuration = builder.staleDuration == null ? DEFAULT_STALE_TIME : builder.staleDuration; this.prefetchDuration = builder.prefetchDuration == null ? this.staleDuration : builder.prefetchDuration; Function<SdkException, TokenT> defaultExceptionHandler = exp -> { throw exp; }; this.exceptionHandler = builder.exceptionHandler == null ? defaultExceptionHandler : builder.exceptionHandler; this.tokenRetriever = builder.tokenRetriever; CachedSupplier.Builder<TokenT> cachedBuilder = CachedSupplier.builder(this::refreshResult) .cachedValueName("SsoOidcTokenProvider()"); if (builder.asyncRefreshEnabled) { cachedBuilder.prefetchStrategy(new NonBlocking(THREAD_CLASS_NAME)); } this.tokenCacheSupplier = cachedBuilder.build(); } /** * Builder method to construct instance of CachedTokenRefresher. * * @return */ public static Builder builder() { return new Builder(); } @Override public TokenT refreshIfStaleAndFetch() { return tokenCacheSupplier.get(); } private TokenT refreshAndGetTokenFromSupplier() { try { TokenT freshToken = tokenRetriever.get(); return freshToken; } catch (SdkException exception) { return exceptionHandler.apply(exception); } } private RefreshResult<TokenT> refreshResult() { TokenT tokenT = refreshAndGetTokenFromSupplier(); Instant staleTime = tokenT.expirationTime().isPresent() ? tokenT.expirationTime().get().minus(staleDuration) : Instant.now(); Instant prefetchTime = tokenT.expirationTime().isPresent() ? tokenT.expirationTime().get().minus(prefetchDuration) : null; return RefreshResult.builder(tokenT).staleTime(staleTime).prefetchTime(prefetchTime).build(); } @Override public void close() { tokenCacheSupplier.close(); } public static class Builder<TokenT extends SdkToken> { private Function<SdkException, TokenT> exceptionHandler; private Duration staleDuration; private Duration prefetchDuration; private Supplier<TokenT> tokenRetriever; private Boolean asyncRefreshEnabled = false; /** * @param tokenRetriever Supplier to retrieve the token from its respective sources. * @return */ public Builder tokenRetriever(Supplier<TokenT> tokenRetriever) { this.tokenRetriever = tokenRetriever; return this; } /** * @param staleDuration The time before which the token is marked as stale to indicate it is time to fetch a fresh token. * @return */ public Builder staleDuration(Duration staleDuration) { this.staleDuration = staleDuration; return this; } /** * Configure the amount of time, relative to SSO session token expiration, that the cached credentials are considered * close to stale and should be updated. See {@link #asyncRefreshEnabled}. * * <p>By default, this is 5 minutes.</p> */ public Builder prefetchTime(Duration prefetchTime) { this.prefetchDuration = prefetchTime; return this; } /** * Configure whether this refresher should fetch tokens asynchronously in the background. If this is true, threads are * less likely to block when {@link #refreshIfStaleAndFetch()} ()} is called, but additional resources are used to * maintain the provider. * * <p>By default, this is disabled.</p> */ public Builder asyncRefreshEnabled(Boolean asyncRefreshEnabled) { this.asyncRefreshEnabled = asyncRefreshEnabled; return this; } /** * @param exceptionHandler Handler which takes action when a Runtime exception occurs while fetching a token. Handler can * return a previously stored token or throw back the exception. * @return */ public Builder exceptionHandler(Function<SdkException, TokenT> exceptionHandler) { this.exceptionHandler = exceptionHandler; return this; } public CachedTokenRefresher build() { CachedTokenRefresher cachedTokenRefresher = new CachedTokenRefresher(this); return cachedTokenRefresher; } } }
1,263
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import java.util.Locale; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.OptionalUtils; /** * Allows customizing the variables used during determination of a {@link DefaultsMode}. Created via {@link #create()}. */ @SdkInternalApi public final class DefaultsModeResolver { private static final DefaultsMode SDK_DEFAULT_DEFAULTS_MODE = DefaultsMode.LEGACY; private Supplier<ProfileFile> profileFile; private String profileName; private DefaultsMode mode; private DefaultsModeResolver() { } public static DefaultsModeResolver create() { return new DefaultsModeResolver(); } /** * Configure the profile file that should be used when determining the {@link RetryMode}. The supplier is only consulted * if a higher-priority determinant (e.g. environment variables) does not find the setting. */ public DefaultsModeResolver profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } /** * Configure the profile file name should be used when determining the {@link RetryMode}. */ public DefaultsModeResolver profileName(String profileName) { this.profileName = profileName; return this; } /** * Configure the {@link DefaultsMode} that should be used if the mode is not specified anywhere else. */ public DefaultsModeResolver defaultMode(DefaultsMode mode) { this.mode = mode; return this; } /** * Resolve which defaults mode should be used, based on the configured values. */ public DefaultsMode resolve() { return OptionalUtils.firstPresent(DefaultsModeResolver.fromSystemSettings(), () -> fromProfileFile(profileFile, profileName)) .orElseGet(this::fromDefaultMode); } private static Optional<DefaultsMode> fromSystemSettings() { return SdkSystemSetting.AWS_DEFAULTS_MODE.getStringValue() .map(value -> DefaultsMode.fromValue(value.toLowerCase(Locale.US))); } private static Optional<DefaultsMode> fromProfileFile(Supplier<ProfileFile> profileFile, String profileName) { profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile; profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); return profileFile.get() .profile(profileName) .flatMap(p -> p.property(ProfileProperty.DEFAULTS_MODE)) .map(value -> DefaultsMode.fromValue(value.toLowerCase(Locale.US))); } private DefaultsMode fromDefaultMode() { return mode != null ? mode : SDK_DEFAULT_DEFAULTS_MODE; } }
1,264
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/defaultsmode/AutoDefaultsModeDiscovery.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.defaultsmode; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; import software.amazon.awssdk.utils.JavaSystemSetting; import software.amazon.awssdk.utils.OptionalUtils; import software.amazon.awssdk.utils.SystemSetting; import software.amazon.awssdk.utils.internal.SystemSettingUtils; /** * This class attempts to discover the appropriate {@link DefaultsMode} by inspecting the environment. It falls * back to the {@link DefaultsMode#STANDARD} mode if the target mode cannot be determined. */ @SdkInternalApi public class AutoDefaultsModeDiscovery { private static final String EC2_METADATA_REGION_PATH = "/latest/meta-data/placement/region"; private static final DefaultsMode FALLBACK_DEFAULTS_MODE = DefaultsMode.STANDARD; private static final String ANDROID_JAVA_VENDOR = "The Android Project"; private static final String AWS_DEFAULT_REGION_ENV_VAR = "AWS_DEFAULT_REGION"; /** * Discovers the defaultMode using the following workflow: * * 1. Check if it's on mobile * 2. If it's not on mobile (best we can tell), see if we can determine whether we're an in-region or cross-region client. * 3. If we couldn't figure out the region from environment variables. Check IMDSv2. This step might take up to 1 second * (default connect timeout) * 4. Finally, use fallback mode */ public DefaultsMode discover(Region regionResolvedFromSdkClient) { if (isMobile()) { return DefaultsMode.MOBILE; } if (isAwsExecutionEnvironment()) { Optional<String> regionStr = regionFromAwsExecutionEnvironment(); if (regionStr.isPresent()) { return compareRegion(regionStr.get(), regionResolvedFromSdkClient); } } Optional<String> regionFromEc2 = queryImdsV2(); if (regionFromEc2.isPresent()) { return compareRegion(regionFromEc2.get(), regionResolvedFromSdkClient); } return FALLBACK_DEFAULTS_MODE; } private static DefaultsMode compareRegion(String region, Region clientRegion) { if (region.equalsIgnoreCase(clientRegion.id())) { return DefaultsMode.IN_REGION; } return DefaultsMode.CROSS_REGION; } private static Optional<String> queryImdsV2() { try { String ec2InstanceRegion = EC2MetadataUtils.fetchData(EC2_METADATA_REGION_PATH, false, 1); // ec2InstanceRegion could be null return Optional.ofNullable(ec2InstanceRegion); } catch (Exception exception) { return Optional.empty(); } } /** * Check to see if the application is running on a mobile device by verifying the Java * vendor system property. Currently only checks for Android. While it's technically possible to * use Java with iOS, it's not a common use-case. * <p> * https://developer.android.com/reference/java/lang/System#getProperties() */ private static boolean isMobile() { return JavaSystemSetting.JAVA_VENDOR.getStringValue() .filter(o -> o.equals(ANDROID_JAVA_VENDOR)) .isPresent(); } private static boolean isAwsExecutionEnvironment() { return SdkSystemSetting.AWS_EXECUTION_ENV.getStringValue().isPresent(); } private static Optional<String> regionFromAwsExecutionEnvironment() { Optional<String> regionFromRegionEnvVar = SdkSystemSetting.AWS_REGION.getStringValue(); return OptionalUtils.firstPresent(regionFromRegionEnvVar, () -> SystemSettingUtils.resolveEnvironmentVariable(new DefaultRegionEnvVar())); } private static final class DefaultRegionEnvVar implements SystemSetting { @Override public String property() { return null; } @Override public String environmentVariable() { return AWS_DEFAULT_REGION_ENV_VAR; } @Override public String defaultValue() { return null; } } }
1,265
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AwsCredentialsAuthorizationStrategy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.Validate; /** * An authorization strategy for AWS Credentials that can resolve a compatible signer as * well as provide resolved AWS credentials as an execution attribute. * * @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code * paths are working, we should migrate old clients to the new code paths (where possible) and delete this code. */ @Deprecated @SdkInternalApi public final class AwsCredentialsAuthorizationStrategy implements AuthorizationStrategy { private final SdkRequest request; private final Signer defaultSigner; private final IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider; private final MetricCollector metricCollector; public AwsCredentialsAuthorizationStrategy(Builder builder) { this.request = builder.request(); this.defaultSigner = builder.defaultSigner(); this.defaultCredentialsProvider = builder.defaultCredentialsProvider(); this.metricCollector = builder.metricCollector(); } public static Builder builder() { return new Builder(); } /** * Request override signers take precedence over the default alternative, for instance what is specified in the * client. Request override signers can also be modified by modifyRequest interceptors. * * @return The signer that will be used by the SDK to sign the request * */ @Override public Signer resolveSigner() { return request.overrideConfiguration() .flatMap(RequestOverrideConfiguration::signer) .orElse(defaultSigner); } /** * Add credentials to be used by the signer in later stages. */ @Override public void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes) { IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider = resolveCredentialsProvider(request, defaultCredentialsProvider); AwsCredentials credentials = CredentialUtils.toCredentials(resolveCredentials(credentialsProvider, metricCollector)); executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials); } /** * Resolves the credentials provider, with the request override configuration taking precedence over the * provided default. * * @return The credentials provider that will be used by the SDK to resolve credentials */ private static IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsProvider( SdkRequest originalRequest, IdentityProvider<? extends AwsCredentialsIdentity> defaultProvider) { return originalRequest.overrideConfiguration() .filter(c -> c instanceof AwsRequestOverrideConfiguration) .map(c -> (AwsRequestOverrideConfiguration) c) .flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider) .orElse(defaultProvider); } private static AwsCredentialsIdentity resolveCredentials( IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider, MetricCollector metricCollector) { Validate.notNull(credentialsProvider, "No credentials provider exists to resolve credentials from."); // TODO(sra-identity-and-auth): internal issue SMITHY-1677. avoid join for async clients. Pair<? extends AwsCredentialsIdentity, Duration> measured = MetricUtils.measureDuration(() -> CompletableFutureUtils.joinLikeSync(credentialsProvider.resolveIdentity())); metricCollector.reportMetric(CoreMetric.CREDENTIALS_FETCH_DURATION, measured.right()); AwsCredentialsIdentity credentials = measured.left(); Validate.validState(credentials != null, "Credential providers must never return null."); return credentials; } public static final class Builder { private SdkRequest request; private Signer defaultSigner; private IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider; private MetricCollector metricCollector; private Builder() { } public SdkRequest request() { return this.request; } public Builder request(SdkRequest request) { this.request = request; return this; } public Signer defaultSigner() { return this.defaultSigner; } public Builder defaultSigner(Signer defaultSigner) { this.defaultSigner = defaultSigner; return this; } public IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider() { return this.defaultCredentialsProvider; } public Builder defaultCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider) { this.defaultCredentialsProvider = defaultCredentialsProvider; return this; } public MetricCollector metricCollector() { return this.metricCollector; } public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } public AwsCredentialsAuthorizationStrategy build() { return new AwsCredentialsAuthorizationStrategy(this); } } }
1,266
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/TokenAuthorizationStrategy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.TokenUtils; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.util.MetricUtils; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.metrics.MetricCollector; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.Validate; /** * An authorization strategy for tokens that can resolve a compatible signer as * well as provide a resolved token as an execution attribute. * * @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code * paths are working, we should migrate old clients to the new code paths (where possible) and delete this code. */ @Deprecated @SdkInternalApi public final class TokenAuthorizationStrategy implements AuthorizationStrategy { private final SdkRequest request; private final Signer defaultSigner; private final IdentityProvider<? extends TokenIdentity> defaultTokenProvider; private final MetricCollector metricCollector; public TokenAuthorizationStrategy(Builder builder) { this.request = builder.request(); this.defaultSigner = builder.defaultSigner(); this.defaultTokenProvider = builder.defaultTokenProvider(); this.metricCollector = builder.metricCollector(); } public static Builder builder() { return new Builder(); } /** * Request override signers take precedence over the default alternative, for instance what is specified in the * client. Request override signers can also be modified by modifyRequest interceptors. * * @return The signer that will be used by the SDK to sign the request */ @Override public Signer resolveSigner() { return request.overrideConfiguration() .flatMap(RequestOverrideConfiguration::signer) .orElse(defaultSigner); } /** * Add credentials to be used by the signer in later stages. */ @Override public void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes) { TokenIdentity tokenIdentity = resolveToken(defaultTokenProvider, metricCollector); SdkToken token = TokenUtils.toSdkToken(tokenIdentity); executionAttributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); } private static TokenIdentity resolveToken(IdentityProvider<? extends TokenIdentity> tokenProvider, MetricCollector metricCollector) { Validate.notNull(tokenProvider, "No token provider exists to resolve a token from."); // TODO(sra-identity-and-auth): internal issue SMITHY-1677. avoid join for async clients. Pair<TokenIdentity, Duration> measured = MetricUtils.measureDuration(() -> CompletableFutureUtils.joinLikeSync(tokenProvider.resolveIdentity())); metricCollector.reportMetric(CoreMetric.TOKEN_FETCH_DURATION, measured.right()); TokenIdentity token = measured.left(); Validate.validState(token != null, "Token providers must never return null."); return token; } public static final class Builder { private SdkRequest request; private Signer defaultSigner; private IdentityProvider<? extends TokenIdentity> defaultTokenProvider; private MetricCollector metricCollector; private Builder() { } public SdkRequest request() { return this.request; } public Builder request(SdkRequest request) { this.request = request; return this; } public Signer defaultSigner() { return this.defaultSigner; } public Builder defaultSigner(Signer defaultSigner) { this.defaultSigner = defaultSigner; return this; } public IdentityProvider<? extends TokenIdentity> defaultTokenProvider() { return this.defaultTokenProvider; } public Builder defaultTokenProvider(IdentityProvider<? extends TokenIdentity> defaultTokenProvider) { this.defaultTokenProvider = defaultTokenProvider; return this; } public MetricCollector metricCollector() { return this.metricCollector; } public Builder metricCollector(MetricCollector metricCollector) { this.metricCollector = metricCollector; return this; } public TokenAuthorizationStrategy build() { return new TokenAuthorizationStrategy(this); } } }
1,267
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategyFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.CredentialType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.metrics.MetricCollector; /** * Will create the correct authorization strategy based on provided credential type. * * @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code * paths are working, we should migrate old clients to the new code paths (where possible) and delete this code. */ @Deprecated @SdkInternalApi public final class AuthorizationStrategyFactory { private final SdkRequest request; private final MetricCollector metricCollector; private final SdkClientConfiguration clientConfiguration; public AuthorizationStrategyFactory(SdkRequest request, MetricCollector metricCollector, SdkClientConfiguration clientConfiguration) { this.request = request; this.metricCollector = metricCollector; this.clientConfiguration = clientConfiguration; } public AuthorizationStrategy strategyFor(CredentialType credentialType) { if (credentialType == CredentialType.TOKEN) { return tokenAuthorizationStrategy(); } return awsCredentialsAuthorizationStrategy(); } private TokenAuthorizationStrategy tokenAuthorizationStrategy() { Signer defaultSigner = clientConfiguration.option(SdkAdvancedClientOption.TOKEN_SIGNER); // Older generated clients may be setting TOKEN_PROVIDER, hence fallback. IdentityProvider<? extends TokenIdentity> defaultTokenProvider = clientConfiguration.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER) == null ? clientConfiguration.option(AwsClientOption.TOKEN_PROVIDER) : clientConfiguration.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER); return TokenAuthorizationStrategy.builder() .request(request) .defaultSigner(defaultSigner) .defaultTokenProvider(defaultTokenProvider) .metricCollector(metricCollector) .build(); } private AwsCredentialsAuthorizationStrategy awsCredentialsAuthorizationStrategy() { Signer defaultSigner = clientConfiguration.option(SdkAdvancedClientOption.SIGNER); IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider = clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER); return AwsCredentialsAuthorizationStrategy.builder() .request(request) .defaultSigner(defaultSigner) .defaultCredentialsProvider(defaultCredentialsProvider) .metricCollector(metricCollector) .build(); } }
1,268
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.authcontext; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Signer; /** * Represents a logical unit for providing instructions on how to authorize a request, * including which signer and which credentials to use. * * @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code * paths are working, we should migrate old clients to the new code paths (where possible) and delete this code. */ @Deprecated @SdkInternalApi public interface AuthorizationStrategy { Signer resolveSigner(); void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes); }
1,269
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/client/config/AwsClientOptionValidation.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.client.config; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOptionValidation; /** * A set of static methods used to validate that a {@link SdkClientConfiguration} contains all of * the values required for the AWS client handlers to function. */ @SdkInternalApi public final class AwsClientOptionValidation extends SdkClientOptionValidation { private AwsClientOptionValidation() { } public static void validateAsyncClientOptions(SdkClientConfiguration c) { validateClientOptions(c); } public static void validateSyncClientOptions(SdkClientConfiguration c) { validateClientOptions(c); } private static void validateClientOptions(SdkClientConfiguration c) { require("credentialsProvider", c.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER)); require("overrideConfiguration.advancedOption[AWS_REGION]", c.option(AwsClientOption.AWS_REGION)); require("overrideConfiguration.advancedOption[SIGNING_REGION]", c.option(AwsClientOption.SIGNING_REGION)); require("overrideConfiguration.advancedOption[SERVICE_SIGNING_NAME]", c.option(AwsClientOption.SERVICE_SIGNING_NAME)); require("overrideConfiguration.advancedOption[ENABLE_DEFAULT_REGION_DETECTION]", c.option(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION)); } }
1,270
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/interceptor/TracingSystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.internal.interceptor; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.SystemSetting; /** * Tracing specific System Setting. */ @SdkInternalApi public enum TracingSystemSetting implements SystemSetting { // See: https://github.com/aws/aws-xray-sdk-java/issues/251 _X_AMZN_TRACE_ID("com.amazonaws.xray.traceHeader", null); private final String systemProperty; private final String defaultValue; TracingSystemSetting(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,271
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/SdkPresigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.presigner; import java.net.URI; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * The base interface for all SDK presigners. */ @SdkPublicApi public interface SdkPresigner extends SdkAutoCloseable { /** * Close this presigner, releasing any resources it might have acquired. It is recommended to invoke this method whenever * the presigner is done being used, to prevent resource leaks. * <p/> * For example, some {@link AwsCredentialsProvider} implementations hold resources that could be released by this method. */ @Override void close(); /** * The base interface for all SDK presigner builders. */ @SdkPublicApi interface Builder { /** * Configure the region for which the requests should be signed. * * <p>If this is not specified, the SDK will attempt to identify the endpoint automatically using the following logic: * <ol> * <li>Check the 'aws.region' system property for the region.</li> * <li>Check the 'AWS_REGION' environment variable for the region.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li> * <li>If running in EC2, check the EC2 metadata service for the region.</li> * </ol> * * <p>If the region is not found in any of the locations above, an exception will be thrown at {@link #build()} * time. */ Builder region(Region region); /** * Configure the credentials that should be used for request signing. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li> * <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI * environment variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} * time. * </p> * * <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)} * wins.</p> */ default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } /** * Configure the credentials that should be used to authenticate with AWS. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li> * <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI * environment variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} * time. * </p> * * <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)} * wins.</p> */ default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } /** * Configure whether the SDK should use the AWS dualstack endpoint. * * <p>If this is not specified, the SDK will attempt to determine whether the dualstack endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useDualstackEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_DUALSTACK_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_dualstack_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ Builder dualstackEnabled(Boolean dualstackEnabled); /** * Configure whether the SDK should use the AWS fips endpoint. * * <p>If this is not specified, the SDK will attempt to determine whether the fips endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useFipsEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_FIPS_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_fips_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ Builder fipsEnabled(Boolean fipsEnabled); /** * Configure an endpoint that should be used in the pre-signed requests. This will override the endpoint that is usually * determined by the {@link #region(Region)} and {@link #dualstackEnabled(Boolean)} settings. */ Builder endpointOverride(URI endpointOverride); /** * Build the presigner using the configuration on this builder. */ SdkPresigner build(); } }
1,272
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/PresignedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.presigner; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.net.URL; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.Validate; /** * The base class for all presigned requests. * <p/> * The {@link #isBrowserExecutable} method can be used to determine whether this request can be executed by a web browser. */ @SdkPublicApi public abstract class PresignedRequest { private final URL url; private final Instant expiration; private final boolean isBrowserExecutable; private final Map<String, List<String>> signedHeaders; private final SdkBytes signedPayload; private final SdkHttpRequest httpRequest; protected PresignedRequest(DefaultBuilder<?> builder) { this.expiration = Validate.notNull(builder.expiration, "expiration"); this.isBrowserExecutable = Validate.notNull(builder.isBrowserExecutable, "isBrowserExecutable"); this.signedHeaders = Validate.notEmpty(builder.signedHeaders, "signedHeaders"); this.signedPayload = builder.signedPayload; this.httpRequest = Validate.notNull(builder.httpRequest, "httpRequest"); this.url = invokeSafely(httpRequest.getUri()::toURL); } /** * The URL that the presigned request will execute against. The {@link #isBrowserExecutable} method can be used to * determine whether this request will work in a browser. */ public URL url() { return url; } /** * The exact SERVICE time that the request will expire. After this time, attempting to execute the request * will fail. * <p/> * This may differ from the local clock, based on the skew between the local and AWS service clocks. */ public Instant expiration() { return expiration; } /** * Whether the url returned by the url method can be executed in a browser. * <p/> * This is true when the HTTP request method is GET and all data included in the signature will be sent by a standard web * browser. */ public boolean isBrowserExecutable() { return isBrowserExecutable; } /** * Returns the subset of headers that were signed, and MUST be included in the presigned request to prevent * the request from failing. */ public Map<String, List<String>> signedHeaders() { return signedHeaders; } /** * Returns the payload that was signed, or Optional.empty() if there is no signed payload with this request. */ public Optional<SdkBytes> signedPayload() { return Optional.ofNullable(signedPayload); } /** * The entire SigV4 query-parameter signed request (minus the payload), that can be transmitted as-is to a * service using any HTTP client that implement the SDK's HTTP client SPI. * <p> * This request includes signed AND unsigned headers. */ public SdkHttpRequest httpRequest() { return httpRequest; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PresignedRequest that = (PresignedRequest) o; if (isBrowserExecutable != that.isBrowserExecutable) { return false; } if (!expiration.equals(that.expiration)) { return false; } if (!signedHeaders.equals(that.signedHeaders)) { return false; } if (signedPayload != null ? !signedPayload.equals(that.signedPayload) : that.signedPayload != null) { return false; } return httpRequest.equals(that.httpRequest); } @Override public int hashCode() { int result = expiration.hashCode(); result = 31 * result + (isBrowserExecutable ? 1 : 0); result = 31 * result + signedHeaders.hashCode(); result = 31 * result + (signedPayload != null ? signedPayload.hashCode() : 0); result = 31 * result + httpRequest.hashCode(); return result; } @SdkPublicApi public interface Builder { /** * Configure the exact SERVICE time that the request will expire. After this time, attempting to execute the request * will fail. */ Builder expiration(Instant expiration); /** * Configure whether the url returned by the url method can be executed in a browser. */ Builder isBrowserExecutable(Boolean isBrowserExecutable); /** * Configure the subset of headers that were signed, and MUST be included in the presigned request to prevent * the request from failing. */ Builder signedHeaders(Map<String, List<String>> signedHeaders); /** * Configure the payload that was signed. */ Builder signedPayload(SdkBytes signedPayload); /** * Configure the entire SigV4 query-parameter signed request (minus the payload), that can be transmitted as-is to a * service using any HTTP client that implement the SDK's HTTP client SPI. */ Builder httpRequest(SdkHttpRequest httpRequest); PresignedRequest build(); } @SdkProtectedApi protected abstract static class DefaultBuilder<B extends DefaultBuilder<B>> implements Builder { private Instant expiration; private Boolean isBrowserExecutable; private Map<String, List<String>> signedHeaders; private SdkBytes signedPayload; private SdkHttpRequest httpRequest; protected DefaultBuilder() { } protected DefaultBuilder(PresignedRequest request) { this.expiration = request.expiration; this.isBrowserExecutable = request.isBrowserExecutable; this.signedHeaders = request.signedHeaders; this.signedPayload = request.signedPayload; this.httpRequest = request.httpRequest; } @Override public B expiration(Instant expiration) { this.expiration = expiration; return thisBuilder(); } @Override public B isBrowserExecutable(Boolean isBrowserExecutable) { this.isBrowserExecutable = isBrowserExecutable; return thisBuilder(); } @Override public B signedHeaders(Map<String, List<String>> signedHeaders) { this.signedHeaders = signedHeaders; return thisBuilder(); } @Override public B signedPayload(SdkBytes signedPayload) { this.signedPayload = signedPayload; return thisBuilder(); } @Override public B httpRequest(SdkHttpRequest httpRequest) { this.httpRequest = httpRequest; return thisBuilder(); } @SuppressWarnings("unchecked") private B thisBuilder() { return (B) this; } } }
1,273
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/PresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.presigner; import java.time.Duration; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * The base class for all presign requests. */ @SdkPublicApi public abstract class PresignRequest { private final Duration signatureDuration; protected PresignRequest(DefaultBuilder<?> builder) { this.signatureDuration = Validate.paramNotNull(builder.signatureDuration, "signatureDuration"); } /** * Retrieves the duration for which this presigned request should be valid. After this time has * expired, attempting to use the presigned request will fail.  */ public Duration signatureDuration() { return this.signatureDuration; } /** * The base interface for all presign request builders. */ @SdkPublicApi public interface Builder { /** * Specifies the duration for which this presigned request should be valid. After this time has * expired, attempting to use the presigned request will fail.  */ Builder signatureDuration(Duration signatureDuration); /** * Build the presigned request, based on the configuration on this builder. */ PresignRequest build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PresignRequest that = (PresignRequest) o; return signatureDuration.equals(that.signatureDuration); } @Override public int hashCode() { return signatureDuration.hashCode(); } @SdkProtectedApi protected abstract static class DefaultBuilder<B extends DefaultBuilder<B>> implements Builder { private Duration signatureDuration; protected DefaultBuilder() { } protected DefaultBuilder(PresignRequest request) { this.signatureDuration = request.signatureDuration; } @Override public B signatureDuration(Duration signatureDuration) { this.signatureDuration = signatureDuration; return thisBuilder(); } @SuppressWarnings("unchecked") private B thisBuilder() { return (B) this; } } }
1,274
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/FipsEnabledProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoint; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.Validate; /** * A resolver for the default value of whether the SDK should use fips endpoints. This checks environment variables, * system properties and the profile file for the relevant configuration options when {@link #isFipsEnabled()} is invoked. */ @SdkProtectedApi public class FipsEnabledProvider { private final Supplier<ProfileFile> profileFile; private final String profileName; private FipsEnabledProvider(Builder builder) { this.profileFile = Validate.paramNotNull(builder.profileFile, "profileFile"); this.profileName = builder.profileName; } public static Builder builder() { return new Builder(); } /** * Returns true when dualstack should be used, false when dualstack should not be used, and empty when there is no global * dualstack configuration. */ public Optional<Boolean> isFipsEnabled() { Optional<Boolean> setting = SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.getBooleanValue(); if (setting.isPresent()) { return setting; } return profileFile.get() .profile(profileName()) .flatMap(p -> p.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT)); } private String profileName() { return profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } public static final class Builder { private Supplier<ProfileFile> profileFile = ProfileFile::defaultProfileFile; private String profileName; private Builder() { } public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public FipsEnabledProvider build() { return new FipsEnabledProvider(this); } } }
1,275
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/DualstackEnabledProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoint; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.Validate; /** * A resolver for the default value of whether the SDK should use dualstack endpoints. This checks environment variables, * system properties and the profile file for the relevant configuration options when {@link #isDualstackEnabled()} is invoked. */ @SdkProtectedApi public class DualstackEnabledProvider { private final Supplier<ProfileFile> profileFile; private final String profileName; private DualstackEnabledProvider(Builder builder) { this.profileFile = Validate.paramNotNull(builder.profileFile, "profileFile"); this.profileName = builder.profileName; } public static Builder builder() { return new Builder(); } /** * Returns true when dualstack should be used, false when dualstack should not be used, and empty when there is no global * dualstack configuration. */ public Optional<Boolean> isDualstackEnabled() { Optional<Boolean> setting = SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.getBooleanValue(); if (setting.isPresent()) { return setting; } ProfileFile profileFile = this.profileFile.get(); Optional<Profile> profile = profileFile .profile(profileName()); return profile .flatMap(p -> p.booleanProperty(ProfileProperty.USE_DUALSTACK_ENDPOINT)); } private String profileName() { return profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } public static final class Builder { private Supplier<ProfileFile> profileFile = ProfileFile::defaultProfileFile; private String profileName; private Builder() { } public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public DualstackEnabledProvider build() { return new DualstackEnabledProvider(this); } } }
1,276
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/DefaultServiceEndpointBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.endpoint; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.regions.EndpointTag; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Validate; /** * Uses service metadata and the request region to construct an endpoint for a specific service */ @NotThreadSafe @SdkProtectedApi // TODO We may not need this anymore, we should default to AWS partition when resolving // a region we don't know about yet. public final class DefaultServiceEndpointBuilder { private final String serviceName; private final String protocol; private Region region; private Supplier<ProfileFile> profileFile; private String profileName; private final Map<ServiceMetadataAdvancedOption<?>, Object> advancedOptions = new HashMap<>(); private Boolean dualstackEnabled; private Boolean fipsEnabled; public DefaultServiceEndpointBuilder(String serviceName, String protocol) { this.serviceName = Validate.paramNotNull(serviceName, "serviceName"); this.protocol = Validate.paramNotNull(protocol, "protocol"); } public DefaultServiceEndpointBuilder withRegion(Region region) { if (region == null) { throw new IllegalArgumentException("Region cannot be null"); } this.region = region; return this; } public DefaultServiceEndpointBuilder withProfileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public DefaultServiceEndpointBuilder withProfileFile(ProfileFile profileFile) { this.profileFile = () -> profileFile; return this; } public DefaultServiceEndpointBuilder withProfileName(String profileName) { this.profileName = profileName; return this; } public <T> DefaultServiceEndpointBuilder putAdvancedOption(ServiceMetadataAdvancedOption<T> option, T value) { advancedOptions.put(option, value); return this; } public DefaultServiceEndpointBuilder withDualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } public DefaultServiceEndpointBuilder withFipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } public URI getServiceEndpoint() { if (profileFile == null) { profileFile = new Lazy<>(ProfileFile::defaultProfileFile)::getValue; } if (profileName == null) { profileName = ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } if (dualstackEnabled == null) { dualstackEnabled = DualstackEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isDualstackEnabled() .orElse(false); } if (fipsEnabled == null) { fipsEnabled = FipsEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isFipsEnabled() .orElse(false); } List<EndpointTag> endpointTags = new ArrayList<>(); if (dualstackEnabled) { endpointTags.add(EndpointTag.DUALSTACK); } if (fipsEnabled) { endpointTags.add(EndpointTag.FIPS); } ServiceMetadata serviceMetadata = ServiceMetadata.of(serviceName) .reconfigure(c -> c.profileFile(profileFile) .profileName(profileName) .advancedOptions(advancedOptions)); URI endpoint = addProtocolToServiceEndpoint(serviceMetadata.endpointFor(ServiceEndpointKey.builder() .region(region) .tags(endpointTags) .build())); if (endpoint.getHost() == null) { String error = "Configured region (" + region + ") and tags (" + endpointTags + ") resulted in an invalid URI: " + endpoint + ". This is usually caused by an invalid region configuration."; List<Region> exampleRegions = serviceMetadata.regions(); if (!exampleRegions.isEmpty()) { error += " Valid regions: " + exampleRegions; } throw SdkClientException.create(error); } return endpoint; } private URI addProtocolToServiceEndpoint(URI endpointWithoutProtocol) throws IllegalArgumentException { try { return new URI(protocol + "://" + endpointWithoutProtocol); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } public Region getRegion() { return region; } }
1,277
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/exception/AwsServiceException.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.StringJoiner; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.internal.AwsErrorCode; import software.amazon.awssdk.awscore.internal.AwsStatusCode; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.retry.ClockSkew; import software.amazon.awssdk.http.SdkHttpResponse; /** * Extension of {@link SdkServiceException} that represents an error response returned * by an Amazon web service. * <p> * <p> * AmazonServiceException provides callers several pieces of * information that can be used to obtain more information about the error and * why it occurred. In particular, the errorType field can be used to determine * if the caller's request was invalid, or the service encountered an error on * the server side while processing it. * * @see SdkServiceException */ @SdkPublicApi public class AwsServiceException extends SdkServiceException { private AwsErrorDetails awsErrorDetails; private Duration clockSkew; protected AwsServiceException(Builder b) { super(b); this.awsErrorDetails = b.awsErrorDetails(); this.clockSkew = b.clockSkew(); } /** * Additional details pertaining to an exception thrown by an AWS service. * * @return {@link AwsErrorDetails}. */ public AwsErrorDetails awsErrorDetails() { return awsErrorDetails; } @Override public String getMessage() { if (awsErrorDetails != null) { StringJoiner details = new StringJoiner(", ", "(", ")"); details.add("Service: " + awsErrorDetails().serviceName()); details.add("Status Code: " + statusCode()); details.add("Request ID: " + requestId()); if (extendedRequestId() != null) { details.add("Extended Request ID: " + extendedRequestId()); } String message = super.getMessage(); if (message == null) { message = awsErrorDetails().errorMessage(); } return message + " " + details; } return super.getMessage(); } @Override public boolean isClockSkewException() { if (super.isClockSkewException()) { return true; } if (awsErrorDetails == null) { return false; } if (AwsErrorCode.isDefiniteClockSkewErrorCode(awsErrorDetails.errorCode())) { return true; } SdkHttpResponse sdkHttpResponse = awsErrorDetails.sdkHttpResponse(); if (clockSkew == null || sdkHttpResponse == null) { return false; } boolean isPossibleClockSkewError = AwsErrorCode.isPossibleClockSkewErrorCode(awsErrorDetails.errorCode()) || AwsStatusCode.isPossibleClockSkewStatusCode(statusCode()); return isPossibleClockSkewError && ClockSkew.isClockSkewed(Instant.now().minus(clockSkew), ClockSkew.getServerTime(sdkHttpResponse).orElse(null)); } @Override public boolean isThrottlingException() { return super.isThrottlingException() || Optional.ofNullable(awsErrorDetails) .map(a -> AwsErrorCode.isThrottlingErrorCode(a.errorCode())) .orElse(false); } /** * @return {@link Builder} instance to construct a new {@link AwsServiceException}. */ public static Builder builder() { return new BuilderImpl(); } /** * Create a {@link AwsServiceException.Builder} initialized with the properties of this {@code AwsServiceException}. * * @return A new builder initialized with this config's properties. */ @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Class<? extends Builder> serializableBuilderClass() { return BuilderImpl.class; } public interface Builder extends SdkServiceException.Builder { /** * Specifies the additional awsErrorDetails from the service response. * @param awsErrorDetails Object containing additional details from the response. * @return This object for method chaining. */ Builder awsErrorDetails(AwsErrorDetails awsErrorDetails); /** * The {@link AwsErrorDetails} from the service response. * * @return {@link AwsErrorDetails}. */ AwsErrorDetails awsErrorDetails(); /** * The request-level time skew between the client and server date for the request that generated this exception. Positive * values imply the client clock is "fast" and negative values imply the client clock is "slow". */ Builder clockSkew(Duration timeOffSet); /** * The request-level time skew between the client and server date for the request that generated this exception. Positive * values imply the client clock is "fast" and negative values imply the client clock is "slow". */ Duration clockSkew(); @Override Builder message(String message); @Override Builder cause(Throwable t); @Override Builder requestId(String requestId); @Override Builder extendedRequestId(String extendedRequestId); @Override Builder statusCode(int statusCode); @Override AwsServiceException build(); } protected static class BuilderImpl extends SdkServiceException.BuilderImpl implements Builder { protected AwsErrorDetails awsErrorDetails; private Duration clockSkew; protected BuilderImpl() { } protected BuilderImpl(AwsServiceException ex) { super(ex); this.awsErrorDetails = ex.awsErrorDetails(); } @Override public Builder awsErrorDetails(AwsErrorDetails awsErrorDetails) { this.awsErrorDetails = awsErrorDetails; return this; } @Override public AwsErrorDetails awsErrorDetails() { return awsErrorDetails; } public AwsErrorDetails getAwsErrorDetails() { return awsErrorDetails; } public void setAwsErrorDetails(AwsErrorDetails awsErrorDetails) { this.awsErrorDetails = awsErrorDetails; } @Override public Builder clockSkew(Duration clockSkew) { this.clockSkew = clockSkew; return this; } @Override public Duration clockSkew() { return clockSkew; } @Override public Builder message(String message) { this.message = message; return this; } @Override public Builder cause(Throwable cause) { this.cause = cause; return this; } @Override public Builder writableStackTrace(Boolean writableStackTrace) { this.writableStackTrace = writableStackTrace; return this; } @Override public Builder requestId(String requestId) { this.requestId = requestId; return this; } @Override public Builder extendedRequestId(String extendedRequestId) { this.extendedRequestId = extendedRequestId; return this; } @Override public Builder statusCode(int statusCode) { this.statusCode = statusCode; return this; } @Override public AwsServiceException build() { return new AwsServiceException(this); } } }
1,278
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/exception/AwsErrorDetails.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.exception; import java.io.Serializable; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.ToString; @SdkPublicApi public class AwsErrorDetails implements Serializable { private static final long serialVersionUID = 1L; private final String errorMessage; private final String errorCode; private final String serviceName; private final SdkHttpResponse sdkHttpResponse; private final SdkBytes rawResponse; protected AwsErrorDetails(Builder b) { this.errorMessage = b.errorMessage(); this.errorCode = b.errorCode(); this.serviceName = b.serviceName(); this.sdkHttpResponse = b.sdkHttpResponse(); this.rawResponse = b.rawResponse(); } /** * Returns the name of the service as defined in the static constant * SERVICE_NAME variable of each service's interface. * * @return The name of the service that sent this error response. */ public String serviceName() { return serviceName; } /** * @return the human-readable error message provided by the service. */ public String errorMessage() { return errorMessage; } /** * Returns the error code associated with the response. */ public String errorCode() { return errorCode; } /** * Returns the response payload as bytes. */ public SdkBytes rawResponse() { return rawResponse; } /** * Returns a map of HTTP headers associated with the error response. */ public SdkHttpResponse sdkHttpResponse() { return sdkHttpResponse; } /** * @return {@link AwsErrorDetails.Builder} instance to construct a new {@link AwsErrorDetails}. */ public static Builder builder() { return new BuilderImpl(); } /** * Create a {@link AwsErrorDetails.Builder} initialized with the properties of this {@code AwsErrorDetails}. * * @return A new builder initialized with this config's properties. */ public Builder toBuilder() { return new BuilderImpl(this); } public static Class<? extends Builder> serializableBuilderClass() { return BuilderImpl.class; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AwsErrorDetails that = (AwsErrorDetails) o; return Objects.equals(errorMessage, that.errorMessage) && Objects.equals(errorCode, that.errorCode) && Objects.equals(serviceName, that.serviceName) && Objects.equals(sdkHttpResponse, that.sdkHttpResponse) && Objects.equals(rawResponse, that.rawResponse); } @Override public int hashCode() { int result = Objects.hashCode(errorMessage); result = 31 * result + Objects.hashCode(errorCode); result = 31 * result + Objects.hashCode(serviceName); result = 31 * result + Objects.hashCode(sdkHttpResponse); result = 31 * result + Objects.hashCode(rawResponse); return result; } @Override public String toString() { return ToString.builder("AwsErrorDetails") .add("errorMessage", errorMessage) .add("errorCode", errorCode) .add("serviceName", serviceName) .build(); } public interface Builder { /** * Specifies the error message returned by the service. * * @param errorMessage The error message returned by the service. * @return This object for method chaining. */ Builder errorMessage(String errorMessage); /** * The error message specified by the service. * * @return The error message specified by the service. */ String errorMessage(); /** * Specifies the error code returned by the service. * * @param errorCode The error code returned by the service. * @return This object for method chaining. */ Builder errorCode(String errorCode); /** * The error code specified by the service. * * @return The error code specified by the service. */ String errorCode(); /** * Specifies the name of the service that returned this error. * * @param serviceName The name of the service. * @return This object for method chaining. */ Builder serviceName(String serviceName); /** * Returns the name of the service as defined in the static constant * SERVICE_NAME variable of each service's interface. * * @return The name of the service that returned this error. */ String serviceName(); /** * Specifies the {@link SdkHttpResponse} returned on the error response from the service. * * @param sdkHttpResponse The HTTP response from the service. * @return This object for method chaining. */ Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse); /** * The HTTP response returned from the service. * * @return {@link SdkHttpResponse}. */ SdkHttpResponse sdkHttpResponse(); /** * Specifies raw http response from the service. * * @param rawResponse raw byte response from the service. * @return The object for method chaining. */ Builder rawResponse(SdkBytes rawResponse); /** * The raw response from the service. * * @return The raw response from the service in a byte array. */ SdkBytes rawResponse(); /** * Creates a new {@link AwsErrorDetails} with the properties set on this builder. * * @return The new {@link AwsErrorDetails}. */ AwsErrorDetails build(); } protected static final class BuilderImpl implements Builder { private String errorMessage; private String errorCode; private String serviceName; private SdkHttpResponse sdkHttpResponse; private SdkBytes rawResponse; private BuilderImpl() { } private BuilderImpl(AwsErrorDetails awsErrorDetails) { this.errorMessage = awsErrorDetails.errorMessage(); this.errorCode = awsErrorDetails.errorCode(); this.serviceName = awsErrorDetails.serviceName(); this.sdkHttpResponse = awsErrorDetails.sdkHttpResponse(); this.rawResponse = awsErrorDetails.rawResponse(); } @Override public Builder errorMessage(String errorMessage) { this.errorMessage = errorMessage; return this; } @Override public String errorMessage() { return errorMessage; } @Override public Builder errorCode(String errorCode) { this.errorCode = errorCode; return this; } @Override public String errorCode() { return errorCode; } @Override public Builder serviceName(String serviceName) { this.serviceName = serviceName; return this; } @Override public String serviceName() { return serviceName; } @Override public Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse) { this.sdkHttpResponse = sdkHttpResponse; return this; } @Override public SdkHttpResponse sdkHttpResponse() { return sdkHttpResponse; } @Override public Builder rawResponse(SdkBytes rawResponse) { this.rawResponse = rawResponse; return this; } @Override public SdkBytes rawResponse() { return rawResponse; } @Override public AwsErrorDetails build() { return new AwsErrorDetails(this); } } }
1,279
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsClientHandlerUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.handler; import static software.amazon.awssdk.utils.CollectionUtils.firstIfPresent; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.LinkedHashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.utils.IoUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; @SdkProtectedApi public final class AwsClientHandlerUtils { private AwsClientHandlerUtils() { } /** * Encodes the request into a flow message and then returns bytebuffer from the message. * * @param request The request to encode * @return A bytebuffer representing the given request */ public static ByteBuffer encodeEventStreamRequestToByteBuffer(SdkHttpFullRequest request) { Map<String, HeaderValue> headers = new LinkedHashMap<>(); request.forEachHeader((name, value) -> headers.put(name, HeaderValue.fromString(firstIfPresent(value)))); byte[] payload = null; if (request.contentStreamProvider().isPresent()) { try { payload = IoUtils.toByteArray(request.contentStreamProvider().get().newStream()); } catch (IOException e) { throw new UncheckedIOException(e); } } return new Message(headers, payload).toByteBuffer(); } }
1,280
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsAsyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.handler; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.internal.AwsExecutionContextBuilder; import software.amazon.awssdk.awscore.internal.client.config.AwsClientOptionValidation; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.handler.AsyncClientHandler; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler; import software.amazon.awssdk.core.http.ExecutionContext; /** * Async client handler for AWS SDK clients. */ @ThreadSafe @Immutable @SdkProtectedApi public final class AwsAsyncClientHandler extends SdkAsyncClientHandler implements AsyncClientHandler { public AwsAsyncClientHandler(SdkClientConfiguration clientConfiguration) { super(clientConfiguration); AwsClientOptionValidation.validateAsyncClientOptions(clientConfiguration); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse> CompletableFuture<OutputT> execute( ClientExecutionParams<InputT, OutputT> executionParams) { return super.execute(executionParams); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CompletableFuture<ReturnT> execute( ClientExecutionParams<InputT, OutputT> executionParams, AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer) { return super.execute(executionParams, asyncResponseTransformer); } @Override protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams) { SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams); return AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfiguration); } }
1,281
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsSyncClientHandler.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.handler; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.internal.AwsExecutionContextBuilder; import software.amazon.awssdk.awscore.internal.client.config.AwsClientOptionValidation; 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.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkSyncClientHandler; import software.amazon.awssdk.core.client.handler.SyncClientHandler; import software.amazon.awssdk.core.http.Crc32Validation; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.http.SdkHttpFullResponse; /** * Client handler for AWS SDK clients. */ @ThreadSafe @Immutable @SdkProtectedApi public final class AwsSyncClientHandler extends SdkSyncClientHandler implements SyncClientHandler { public AwsSyncClientHandler(SdkClientConfiguration clientConfiguration) { super(clientConfiguration); AwsClientOptionValidation.validateSyncClientOptions(clientConfiguration); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse> OutputT execute( ClientExecutionParams<InputT, OutputT> executionParams) { ClientExecutionParams<InputT, OutputT> clientExecutionParams = addCrc32Validation(executionParams); return super.execute(clientExecutionParams); } @Override public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> ReturnT execute( ClientExecutionParams<InputT, OutputT> executionParams, ResponseTransformer<OutputT, ReturnT> responseTransformer) { return super.execute(executionParams, responseTransformer); } @Override protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams) { SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams); return AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfiguration); } private <InputT extends SdkRequest, OutputT> ClientExecutionParams<InputT, OutputT> addCrc32Validation( ClientExecutionParams<InputT, OutputT> executionParams) { if (executionParams.getCombinedResponseHandler() != null) { return executionParams.withCombinedResponseHandler( new Crc32ValidationResponseHandler<>(executionParams.getCombinedResponseHandler())); } else { return executionParams.withResponseHandler( new Crc32ValidationResponseHandler<>(executionParams.getResponseHandler())); } } /** * Decorate {@link HttpResponseHandler} to validate CRC32 if needed. */ private class Crc32ValidationResponseHandler<T> implements HttpResponseHandler<T> { private final HttpResponseHandler<T> delegate; private Crc32ValidationResponseHandler(HttpResponseHandler<T> delegate) { this.delegate = delegate; } @Override public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception { return delegate.handle(Crc32Validation.validate(isCalculateCrc32FromCompressedData(), response), executionAttributes); } } }
1,282
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/config/AwsAdvancedClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.config; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration.Builder; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.regions.Region; /** * A collection of advanced options that can be configured on an AWS client via * {@link Builder#putAdvancedOption(SdkAdvancedClientOption, Object)}. * * <p>These options are usually not required outside of testing or advanced libraries, so most users should not need to configure * them.</p> * * @param <T> The type of value associated with the option. */ @SdkPublicApi public final class AwsAdvancedClientOption<T> extends SdkAdvancedClientOption<T> { /** * Whether region detection should be enabled. Region detection is used when the {@link AwsClientBuilder#region(Region)} is * not specified. This is enabled by default. */ public static final AwsAdvancedClientOption<Boolean> ENABLE_DEFAULT_REGION_DETECTION = new AwsAdvancedClientOption<>(Boolean.class); private AwsAdvancedClientOption(Class<T> valueClass) { super(valueClass); } }
1,283
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/config/AwsClientOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.config; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.client.config.ClientOption; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; import software.amazon.awssdk.regions.Region; @SdkProtectedApi public final class AwsClientOption<T> extends ClientOption<T> { /** * This option is deprecated in favor of {@link #CREDENTIALS_IDENTITY_PROVIDER}. * @see AwsClientBuilder#credentialsProvider(AwsCredentialsProvider) */ @Deprecated // smithy codegen TODO: This could be removed when doing a minor version bump where we told customers we'll be breaking // protected APIs. Postpone this to when we do Smithy code generator migration, where we'll likely have to start // breaking a lot of protected things. public static final AwsClientOption<AwsCredentialsProvider> CREDENTIALS_PROVIDER = new AwsClientOption<>(AwsCredentialsProvider.class); /** * @see AwsClientBuilder#credentialsProvider(IdentityProvider) */ public static final AwsClientOption<IdentityProvider<? extends AwsCredentialsIdentity>> CREDENTIALS_IDENTITY_PROVIDER = new AwsClientOption<>(new UnsafeValueType(IdentityProvider.class)); /** * AWS Region the client was configured with. Note that this is not always the signing region in the case of global * services like IAM. */ public static final AwsClientOption<Region> AWS_REGION = new AwsClientOption<>(Region.class); /** * AWS Region to be used for signing the request. This is not always same as {@link #AWS_REGION} in case of global services. */ public static final AwsClientOption<Region> SIGNING_REGION = new AwsClientOption<>(Region.class); /** * Whether the SDK should resolve dualstack endpoints instead of default endpoints. See * {@link AwsClientBuilder#dualstackEnabled(Boolean)}. */ public static final AwsClientOption<Boolean> DUALSTACK_ENDPOINT_ENABLED = new AwsClientOption<>(Boolean.class); /** * Whether the SDK should resolve fips endpoints instead of default endpoints. See * {@link AwsClientBuilder#fipsEnabled(Boolean)}. */ public static final ClientOption<Boolean> FIPS_ENDPOINT_ENABLED = new AwsClientOption<>(Boolean.class); /** * Scope name to use during signing of a request. */ public static final AwsClientOption<String> SERVICE_SIGNING_NAME = new AwsClientOption<>(String.class); /** * The first part of the URL in the DNS name for the service. Eg. in the endpoint "dynamodb.amazonaws.com", this is the * "dynamodb". * * For standard services, this should match the "endpointPrefix" field in the AWS model. */ public static final AwsClientOption<String> ENDPOINT_PREFIX = new AwsClientOption<>(String.class); /** * Configuration of the DEFAULTS_MODE. Unlike {@link #DEFAULTS_MODE}, this may be {@link DefaultsMode#AUTO}. */ public static final AwsClientOption<DefaultsMode> CONFIGURED_DEFAULTS_MODE = new AwsClientOption<>(DefaultsMode.class); /** * Option used by the rest of the SDK to read the {@link DefaultsMode}. This will never be {@link DefaultsMode#AUTO}. */ public static final AwsClientOption<DefaultsMode> DEFAULTS_MODE = new AwsClientOption<>(DefaultsMode.class); /** * Option to specify whether global endpoint should be used. */ public static final AwsClientOption<Boolean> USE_GLOBAL_ENDPOINT = new AwsClientOption<>(Boolean.class); /** * Option to specific the {@link SdkTokenProvider} to use for bearer token authorization. * This option is deprecated in favor or {@link #TOKEN_IDENTITY_PROVIDER} */ @Deprecated public static final AwsClientOption<SdkTokenProvider> TOKEN_PROVIDER = new AwsClientOption<>(SdkTokenProvider.class); /** * Option to specific the {@link SdkTokenProvider} to use for bearer token authorization. */ public static final AwsClientOption<IdentityProvider<? extends TokenIdentity>> TOKEN_IDENTITY_PROVIDER = new AwsClientOption<>(new UnsafeValueType(IdentityProvider.class)); private AwsClientOption(Class<T> valueClass) { super(valueClass); } private AwsClientOption(UnsafeValueType valueType) { super(valueType); } }
1,284
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsAsyncClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.builder.SdkAsyncClientBuilder; /** * This includes required and optional override configuration required by every AWS async client builder. An instance can be * acquired by calling the static "builder" method on the type of async client you wish to create. * * <p>Implementations of this interface are mutable and not thread-safe.</p> * * @param <B> The type of builder that should be returned by the fluent builder methods in this interface. * @param <C> The type of client generated by this builder. */ @SdkPublicApi public interface AwsAsyncClientBuilder<B extends AwsAsyncClientBuilder<B, C>, C> extends SdkAsyncClientBuilder<B, C> { }
1,285
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsSyncClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.client.builder.SdkSyncClientBuilder; /** * This includes required and optional override configuration required by every sync client builder. An instance can be acquired * by calling the static "builder" method on the type of sync client you wish to create. * * <p>Implementations of this interface are mutable and not thread-safe.</p> * * @param <B> The type of builder that should be returned by the fluent builder methods in this interface. * @param <C> The type of client generated by this builder. */ @SdkPublicApi public interface AwsSyncClientBuilder<B extends AwsSyncClientBuilder<B, C>, C> extends SdkSyncClientBuilder<B, C> { }
1,286
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.core.client.builder.SdkClientBuilder; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; /** * This includes required and optional override configuration required by every client builder. An instance can be acquired by * calling the static "builder" method on the type of client you wish to create. * * <p>Implementations of this interface are mutable and not thread-safe.</p> * * @param <BuilderT> The type of builder that should be returned by the fluent builder methods in this interface. * @param <ClientT> The type of client generated by this builder. */ @SdkPublicApi public interface AwsClientBuilder<BuilderT extends AwsClientBuilder<BuilderT, ClientT>, ClientT> extends SdkClientBuilder<BuilderT, ClientT> { /** * Configure the credentials that should be used to authenticate with AWS. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li> * <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment * variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} time. * </p> * * <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)} * wins.</p> */ default BuilderT credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider); } /** * Configure the credentials that should be used to authenticate with AWS. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li> * <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment * variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} time. * </p> * * <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)} * wins.</p> */ default BuilderT credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } /** * Configure the region with which the SDK should communicate. * * <p>If this is not specified, the SDK will attempt to identify the endpoint automatically using the following logic: * <ol> * <li>Check the 'aws.region' system property for the region.</li> * <li>Check the 'AWS_REGION' environment variable for the region.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li> * <li>If running in EC2, check the EC2 metadata service for the region.</li> * </ol> * * <p>If the region is not found in any of the locations above, an exception will be thrown at {@link #build()} time. */ BuilderT region(Region region); /** * Sets the {@link DefaultsMode} that will be used to determine how certain default configuration options are resolved in * the SDK. * * <p> * If this is not specified, the SDK will attempt to identify the defaults mode automatically using the following logic: * <ol> * <li>Check the "defaults_mode" profile file property.</li> * <li>Check "aws.defaultsMode" system property.</li> * <li>Check the "AWS_DEFAULTS_MODE" environment variable.</li> * </ol> * * @param defaultsMode the defaultsMode to use * @return This object for method chaining. * @see DefaultsMode */ default BuilderT defaultsMode(DefaultsMode defaultsMode) { throw new UnsupportedOperationException(); } /** * Configure whether the SDK should use the AWS dualstack endpoint. * * <p>If this is not specified, the SDK will attempt to determine whether the dualstack endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useDualstackEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_DUALSTACK_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_dualstack_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ BuilderT dualstackEnabled(Boolean dualstackEndpointEnabled); /** * Configure whether the SDK should use the AWS fips endpoints. * * <p>If this is not specified, the SDK will attempt to determine whether the fips endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useFipsEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_FIPS_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_fips_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ BuilderT fipsEnabled(Boolean fipsEndpointEnabled); }
1,287
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsDefaultClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.client.builder; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.awscore.endpoint.DualstackEnabledProvider; import software.amazon.awssdk.awscore.endpoint.FipsEnabledProvider; import software.amazon.awssdk.awscore.eventstream.EventStreamInitialRequestInterceptor; import software.amazon.awssdk.awscore.interceptor.HelpfulUnknownHostExceptionInterceptor; import software.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor; import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeResolver; import software.amazon.awssdk.awscore.retry.AwsRetryPolicy; import software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder; 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.ExecutionInterceptor; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.AttributeMap.LazyValueSource; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; /** * An SDK-internal implementation of the methods in {@link AwsClientBuilder}, {@link AwsAsyncClientBuilder} and * {@link AwsSyncClientBuilder}. This implements all methods required by those interfaces, allowing service-specific builders to * just * implement the configuration they wish to add. * * <p>By implementing both the sync and async interface's methods, service-specific builders can share code between their sync * and * async variants without needing one to extend the other. Note: This only defines the methods in the sync and async builder * interfaces. It does not implement the interfaces themselves. This is because the sync and async client builder interfaces both * require a type-constrained parameter for use in fluent chaining, and a generic type parameter conflict is introduced into the * class hierarchy by this interface extending the builder interfaces themselves.</p> * * <p>Like all {@link AwsClientBuilder}s, this class is not thread safe.</p> * * @param <BuilderT> The type of builder, for chaining. * @param <ClientT> The type of client generated by this builder. */ @SdkProtectedApi public abstract class AwsDefaultClientBuilder<BuilderT extends AwsClientBuilder<BuilderT, ClientT>, ClientT> extends SdkDefaultClientBuilder<BuilderT, ClientT> implements AwsClientBuilder<BuilderT, ClientT> { private static final Logger log = Logger.loggerFor(AwsClientBuilder.class); private static final String DEFAULT_ENDPOINT_PROTOCOL = "https"; private static final String[] FIPS_SEARCH = {"fips-", "-fips"}; private static final String[] FIPS_REPLACE = {"", ""}; private final AutoDefaultsModeDiscovery autoDefaultsModeDiscovery; protected AwsDefaultClientBuilder() { super(); autoDefaultsModeDiscovery = new AutoDefaultsModeDiscovery(); } @SdkTestInternalApi AwsDefaultClientBuilder(SdkHttpClient.Builder defaultHttpClientBuilder, SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory, AutoDefaultsModeDiscovery autoDefaultsModeDiscovery) { super(defaultHttpClientBuilder, defaultAsyncHttpClientFactory); this.autoDefaultsModeDiscovery = autoDefaultsModeDiscovery; } /** * Implemented by child classes to define the endpoint prefix used when communicating with AWS. This constitutes the first * part of the URL in the DNS name for the service. Eg. in the endpoint "dynamodb.amazonaws.com", this is the "dynamodb". * * <p>For standard services, this should match the "endpointPrefix" field in the AWS model.</p> */ protected abstract String serviceEndpointPrefix(); /** * Implemented by child classes to define the signing-name that should be used when signing requests when communicating with * AWS. */ protected abstract String signingName(); /** * Implemented by child classes to define the service name used to identify the request in things like metrics. */ protected abstract String serviceName(); @Override protected final SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) { SdkClientConfiguration config = mergeServiceDefaults(configuration); config = config.merge(c -> c.option(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION, true) .option(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, false) .option(AwsClientOption.SERVICE_SIGNING_NAME, signingName()) .option(SdkClientOption.SERVICE_NAME, serviceName()) .option(AwsClientOption.ENDPOINT_PREFIX, serviceEndpointPrefix())); return mergeInternalDefaults(config); } /** * Optionally overridden by child classes to define service-specific default configuration. */ protected SdkClientConfiguration mergeServiceDefaults(SdkClientConfiguration configuration) { return configuration; } /** * Optionally overridden by child classes to define internal default configuration. */ protected SdkClientConfiguration mergeInternalDefaults(SdkClientConfiguration configuration) { return configuration; } /** * Return a client configuration object, populated with the following chain of priorities. * <ol> * <li>Defaults vended from {@link DefaultsMode} </li> * <li>AWS Global Defaults</li> * </ol> */ @Override protected final SdkClientConfiguration finalizeChildConfiguration(SdkClientConfiguration configuration) { configuration = finalizeServiceConfiguration(configuration); configuration = finalizeAwsConfiguration(configuration); return configuration; } private SdkClientConfiguration finalizeAwsConfiguration(SdkClientConfiguration configuration) { return configuration.toBuilder() .option(SdkClientOption.EXECUTION_INTERCEPTORS, addAwsInterceptors(configuration)) .lazyOptionIfAbsent(AwsClientOption.AWS_REGION, this::resolveRegion) .lazyOptionIfAbsent(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED, this::resolveDualstackEndpointEnabled) .lazyOptionIfAbsent(AwsClientOption.FIPS_ENDPOINT_ENABLED, this::resolveFipsEndpointEnabled) .lazyOption(AwsClientOption.DEFAULTS_MODE, this::resolveDefaultsMode) .lazyOption(SdkClientOption.DEFAULT_RETRY_MODE, this::resolveDefaultRetryMode) .lazyOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, this::resolveDefaultS3UsEast1RegionalEndpoint) .lazyOptionIfAbsent(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, this::resolveCredentialsIdentityProvider) // CREDENTIALS_PROVIDER is also set, since older clients may be relying on it .lazyOptionIfAbsent(AwsClientOption.CREDENTIALS_PROVIDER, this::resolveCredentialsProvider) .lazyOptionIfAbsent(SdkClientOption.ENDPOINT, this::resolveEndpoint) .lazyOption(AwsClientOption.SIGNING_REGION, this::resolveSigningRegion) .lazyOption(SdkClientOption.HTTP_CLIENT_CONFIG, this::resolveHttpClientConfig) .applyMutation(this::configureRetryPolicy) .lazyOptionIfAbsent(SdkClientOption.IDENTITY_PROVIDERS, this::resolveIdentityProviders) .build(); } /** * Return HTTP related defaults with the following chain of priorities. * <ol> * <li>Service-Specific Defaults</li> * <li>Defaults vended by {@link DefaultsMode}</li> * </ol> */ private AttributeMap resolveHttpClientConfig(LazyValueSource config) { AttributeMap attributeMap = serviceHttpConfig(); return mergeSmartHttpDefaults(config, attributeMap); } /** * Optionally overridden by child classes to define service-specific HTTP configuration defaults. */ protected AttributeMap serviceHttpConfig() { return AttributeMap.empty(); } private IdentityProviders resolveIdentityProviders(LazyValueSource config) { // By default, all AWS clients get an identity provider for AWS credentials. Child classes may override this to specify // AWS credentials and another identity type like Bearer credentials. return IdentityProviders.builder() .putIdentityProvider(config.get(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER)) .build(); } private DefaultsMode resolveDefaultsMode(LazyValueSource config) { DefaultsMode configuredMode = config.get(AwsClientOption.CONFIGURED_DEFAULTS_MODE); if (configuredMode == null) { configuredMode = DefaultsModeResolver.create() .profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(config.get(SdkClientOption.PROFILE_NAME)) .resolve(); } if (configuredMode != DefaultsMode.AUTO) { return configuredMode; } return autoDefaultsModeDiscovery.discover(config.get(AwsClientOption.AWS_REGION)); } private RetryMode resolveDefaultRetryMode(LazyValueSource config) { return DefaultsModeConfiguration.defaultConfig(config.get(AwsClientOption.DEFAULTS_MODE)) .get(SdkClientOption.DEFAULT_RETRY_MODE); } private String resolveDefaultS3UsEast1RegionalEndpoint(LazyValueSource config) { return DefaultsModeConfiguration.defaultConfig(config.get(AwsClientOption.DEFAULTS_MODE)) .get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT); } /** * Optionally overridden by child classes to derive service-specific configuration from the default-applied configuration. */ protected SdkClientConfiguration finalizeServiceConfiguration(SdkClientConfiguration configuration) { return configuration; } /** * Merged the HTTP defaults specified for each {@link DefaultsMode} */ private AttributeMap mergeSmartHttpDefaults(LazyValueSource config, AttributeMap attributeMap) { DefaultsMode defaultsMode = config.get(AwsClientOption.DEFAULTS_MODE); return attributeMap.merge(DefaultsModeConfiguration.defaultHttpConfig(defaultsMode)); } /** * Resolve the signing region from the default-applied configuration. */ private Region resolveSigningRegion(LazyValueSource config) { return ServiceMetadata.of(serviceEndpointPrefix()) .signingRegion(config.get(AwsClientOption.AWS_REGION)); } /** * Resolve the endpoint from the default-applied configuration. */ private URI resolveEndpoint(LazyValueSource config) { return new DefaultServiceEndpointBuilder(serviceEndpointPrefix(), DEFAULT_ENDPOINT_PROTOCOL) .withRegion(config.get(AwsClientOption.AWS_REGION)) .withProfileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER)) .withProfileName(config.get(SdkClientOption.PROFILE_NAME)) .putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, config.get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)) .withDualstackEnabled(config.get(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED)) .withFipsEnabled(config.get(AwsClientOption.FIPS_ENDPOINT_ENABLED)) .getServiceEndpoint(); } /** * Resolve the region that should be used based on the customer's configuration. */ private Region resolveRegion(LazyValueSource config) { Boolean defaultRegionDetectionEnabled = config.get(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION); if (defaultRegionDetectionEnabled != null && !defaultRegionDetectionEnabled) { throw new IllegalStateException("No region was configured, and use-region-provider-chain was disabled."); } Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER); String profileName = config.get(SdkClientOption.PROFILE_NAME); return DefaultAwsRegionProviderChain.builder() .profileFile(profileFile) .profileName(profileName) .build() .getRegion(); } /** * Resolve whether a dualstack endpoint should be used for this client. */ private Boolean resolveDualstackEndpointEnabled(LazyValueSource config) { Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER); String profileName = config.get(SdkClientOption.PROFILE_NAME); return DualstackEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isDualstackEnabled() .orElse(null); } /** * Resolve whether a fips endpoint should be used for this client. */ private Boolean resolveFipsEndpointEnabled(LazyValueSource config) { Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER); String profileName = config.get(SdkClientOption.PROFILE_NAME); return FipsEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isFipsEnabled() .orElse(null); } /** * Resolve the credentials that should be used based on the customer's configuration. */ private IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsIdentityProvider(LazyValueSource config) { return DefaultCredentialsProvider.builder() .profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(config.get(SdkClientOption.PROFILE_NAME)) .build(); } private AwsCredentialsProvider resolveCredentialsProvider(LazyValueSource config) { return CredentialUtils.toCredentialsProvider(config.get(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER)); } private void configureRetryPolicy(SdkClientConfiguration.Builder config) { RetryPolicy policy = config.option(SdkClientOption.RETRY_POLICY); if (policy != null) { if (policy.additionalRetryConditionsAllowed()) { config.option(SdkClientOption.RETRY_POLICY, AwsRetryPolicy.addRetryConditions(policy)); } return; } config.lazyOption(SdkClientOption.RETRY_POLICY, this::resolveAwsRetryPolicy); } private RetryPolicy resolveAwsRetryPolicy(LazyValueSource config) { RetryMode retryMode = RetryMode.resolver() .profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(config.get(SdkClientOption.PROFILE_NAME)) .defaultRetryMode(config.get(SdkClientOption.DEFAULT_RETRY_MODE)) .resolve(); return AwsRetryPolicy.forRetryMode(retryMode); } @Override public final BuilderT region(Region region) { Region regionToSet = region; Boolean fipsEnabled = null; if (region != null) { Pair<Region, Optional<Boolean>> transformedRegion = transformFipsPseudoRegionIfNecessary(region); regionToSet = transformedRegion.left(); fipsEnabled = transformedRegion.right().orElse(null); } clientConfiguration.option(AwsClientOption.AWS_REGION, regionToSet); if (fipsEnabled != null) { clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED, fipsEnabled); } return thisBuilder(); } public final void setRegion(Region region) { region(region); } @Override public BuilderT dualstackEnabled(Boolean dualstackEndpointEnabled) { clientConfiguration.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED, dualstackEndpointEnabled); return thisBuilder(); } public final void setDualstackEnabled(Boolean dualstackEndpointEnabled) { dualstackEnabled(dualstackEndpointEnabled); } @Override public BuilderT fipsEnabled(Boolean dualstackEndpointEnabled) { clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED, dualstackEndpointEnabled); return thisBuilder(); } public final void setFipsEnabled(Boolean fipsEndpointEnabled) { fipsEnabled(fipsEndpointEnabled); } public final void setCredentialsProvider(AwsCredentialsProvider credentialsProvider) { credentialsProvider(credentialsProvider); } @Override public final BuilderT credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) { clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, identityProvider); return thisBuilder(); } public final void setCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) { credentialsProvider(identityProvider); } private List<ExecutionInterceptor> addAwsInterceptors(SdkClientConfiguration config) { List<ExecutionInterceptor> interceptors = awsInterceptors(); interceptors = CollectionUtils.mergeLists(interceptors, config.option(SdkClientOption.EXECUTION_INTERCEPTORS)); return interceptors; } private List<ExecutionInterceptor> awsInterceptors() { return Arrays.asList(new HelpfulUnknownHostExceptionInterceptor(), new EventStreamInitialRequestInterceptor(), new TraceIdExecutionInterceptor()); } @Override public final BuilderT defaultsMode(DefaultsMode defaultsMode) { clientConfiguration.option(AwsClientOption.CONFIGURED_DEFAULTS_MODE, defaultsMode); return thisBuilder(); } public final void setDefaultsMode(DefaultsMode defaultsMode) { defaultsMode(defaultsMode); } /** * If the region is a FIPS pseudo region (contains "fips"), this method returns a pair of values, the left side being the * region with the "fips" string removed, and the right being {@code true}. Otherwise, the region is returned * unchanged, and the right will be empty. */ private static Pair<Region, Optional<Boolean>> transformFipsPseudoRegionIfNecessary(Region region) { String id = region.id(); String newId = StringUtils.replaceEach(id, FIPS_SEARCH, FIPS_REPLACE); if (!newId.equals(id)) { log.info(() -> String.format("Replacing input region %s with %s and setting fipsEnabled to true", id, newId)); return Pair.of(Region.of(newId), Optional.of(true)); } return Pair.of(region, Optional.empty()); } }
1,288
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/HelpfulUnknownHostExceptionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.interceptor; import java.net.UnknownHostException; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.core.exception.SdkClientException; 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.regions.PartitionMetadata; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionMetadata; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServicePartitionMetadata; /** * This interceptor will monitor for {@link UnknownHostException}s and provide the customer with additional information they can * use to debug or fix the problem. */ @SdkInternalApi public final class HelpfulUnknownHostExceptionInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!hasCause(context.exception(), UnknownHostException.class)) { return context.exception(); } StringBuilder error = new StringBuilder(); error.append("Received an UnknownHostException when attempting to interact with a service. See cause for the " + "exact endpoint that is failing to resolve. "); Optional<String> globalRegionErrorDetails = getGlobalRegionErrorDetails(executionAttributes); if (globalRegionErrorDetails.isPresent()) { error.append(globalRegionErrorDetails.get()); } else { error.append("If this is happening on an endpoint that previously worked, there may be a network connectivity " + "issue or your DNS cache could be storing endpoints for too long."); } return SdkClientException.builder().message(error.toString()).cause(context.exception()).build(); } /** * If the customer is interacting with a global service (one with a single endpoint/region for an entire partition), this * will return error details that can instruct the customer on how to configure their client for success. */ private Optional<String> getGlobalRegionErrorDetails(ExecutionAttributes executionAttributes) { Region clientRegion = clientRegion(executionAttributes); if (clientRegion.isGlobalRegion()) { return Optional.empty(); } List<ServicePartitionMetadata> globalPartitionsForService = globalPartitionsForService(executionAttributes); if (globalPartitionsForService.isEmpty()) { return Optional.empty(); } String clientPartition = Optional.ofNullable(clientRegion.metadata()) .map(RegionMetadata::partition) .map(PartitionMetadata::id) .orElse(null); Optional<Region> globalRegionForClientRegion = globalPartitionsForService.stream() .filter(p -> p.partition().id().equals(clientPartition)) .findAny() .flatMap(ServicePartitionMetadata::globalRegion); if (!globalRegionForClientRegion.isPresent()) { String globalRegionsForThisService = globalPartitionsForService.stream() .map(ServicePartitionMetadata::globalRegion) .filter(Optional::isPresent) .map(Optional::get) .filter(Region::isGlobalRegion) .map(Region::id) .collect(Collectors.joining("/")); return Optional.of("This specific service may be a global service, in which case you should configure a global " + "region like " + globalRegionsForThisService + " on the client."); } Region globalRegion = globalRegionForClientRegion.get(); return Optional.of("This specific service is global in the same partition as the region configured on this client (" + clientRegion + "). If this is the first time you're trying to talk to this service in this region, " + "you should try configuring the global region on your client, instead: " + globalRegion); } /** * Retrieve the region configured on the client. */ private Region clientRegion(ExecutionAttributes executionAttributes) { return executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION); } /** * Retrieve all global partitions for the AWS service that we're interacting with. */ private List<ServicePartitionMetadata> globalPartitionsForService(ExecutionAttributes executionAttributes) { return ServiceMetadata.of(executionAttributes.getAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX)) .servicePartitions() .stream() .filter(sp -> sp.globalRegion().isPresent()) .collect(Collectors.toList()); } private boolean hasCause(Throwable thrown, Class<? extends Throwable> cause) { if (thrown == null) { return false; } if (cause.isAssignableFrom(thrown.getClass())) { return true; } return hasCause(thrown.getCause(), cause); } }
1,289
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/TraceIdExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.interceptor; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.internal.interceptor.TracingSystemSetting; 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.http.SdkHttpRequest; import software.amazon.awssdk.utils.SystemSetting; /** * The {@code TraceIdExecutionInterceptor} copies the trace details to the {@link #TRACE_ID_HEADER} header, assuming we seem to * be running in a lambda environment. */ @SdkInternalApi public class TraceIdExecutionInterceptor implements ExecutionInterceptor { private static final String TRACE_ID_HEADER = "X-Amzn-Trace-Id"; private static final String LAMBDA_FUNCTION_NAME_ENVIRONMENT_VARIABLE = "AWS_LAMBDA_FUNCTION_NAME"; @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { Optional<String> traceIdHeader = traceIdHeader(context); if (!traceIdHeader.isPresent()) { Optional<String> lambdafunctionName = lambdaFunctionNameEnvironmentVariable(); Optional<String> traceId = traceId(); if (lambdafunctionName.isPresent() && traceId.isPresent()) { return context.httpRequest().copy(r -> r.putHeader(TRACE_ID_HEADER, traceId.get())); } } return context.httpRequest(); } private Optional<String> traceIdHeader(Context.ModifyHttpRequest context) { return context.httpRequest().firstMatchingHeader(TRACE_ID_HEADER); } private Optional<String> traceId() { return TracingSystemSetting._X_AMZN_TRACE_ID.getStringValue(); } private Optional<String> lambdaFunctionNameEnvironmentVariable() { // CHECKSTYLE:OFF - This is not configured by the customer, so it should not be configurable by system property return SystemSetting.getStringValueFromEnvironmentVariable(LAMBDA_FUNCTION_NAME_ENVIRONMENT_VARIABLE); // CHECKSTYLE:ON } }
1,290
0
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore
Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/GlobalServiceExecutionInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.awscore.interceptor; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * A more specific version of {@link HelpfulUnknownHostExceptionInterceptor} that was used for older IAM clients. This can be * removed if we ever drop backwards-compatibility with older IAM client versions, because newer IAM client versions do not * depend on this interceptor. */ @SdkProtectedApi public class GlobalServiceExecutionInterceptor implements ExecutionInterceptor { private static final HelpfulUnknownHostExceptionInterceptor DELEGATE = new HelpfulUnknownHostExceptionInterceptor(); @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { return DELEGATE.modifyException(context, executionAttributes); } }
1,291
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/RegionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertSame; import java.util.HashMap; import java.util.Map; import org.junit.Test; public class RegionTest { @Test(expected = NullPointerException.class) public void of_ThrowsNullPointerException_WhenNullValue() { Region.of(null); } @Test(expected = IllegalArgumentException.class) public void of_ThrowsIllegalArgumentException_WhenEmptyString() { Region.of(""); } @Test(expected = IllegalArgumentException.class) public void of_ThrowsIllegalArgumentException_WhenBlankString() { Region.of(" "); } @Test public void of_ReturnsRegion_WhenValidString() { Region region = Region.of("us-east-1"); assertThat(region.id()).isEqualTo("us-east-1"); assertSame(Region.US_EAST_1, region); } @Test public void sameValueSameClassAreSameInstance() { Region first = Region.of("first"); Region alsoFirst = Region.of("first"); assertThat(first).isSameAs(alsoFirst); } @Test public void canBeUsedAsKeysInMap() { Map<Region, String> someMap = new HashMap<>(); someMap.put(Region.of("key"), "A Value"); assertThat(someMap.get(Region.of("key"))).isEqualTo("A Value"); } @Test public void idIsUrlEncoded() { Region region = Region.of("http://my-host.com/?"); assertThat(region.id()).isEqualTo("http%3A%2F%2Fmy-host.com%2F%3F"); } }
1,292
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/ServiceEndpointKeyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class ServiceEndpointKeyTest { @Test public void equalsHashCodeTest() { EqualsVerifier.forClass(ServiceEndpointKey.class) .withNonnullFields("region", "tags") .verify(); } }
1,293
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/PartitionEndpointKeyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class PartitionEndpointKeyTest { @Test public void equalsHashCodeTest() { EqualsVerifier.forClass(PartitionEndpointKey.class) .withNonnullFields("tags") .verify(); } }
1,294
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/PartitionServiceMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; public class PartitionServiceMetadataTest { private static final List<String> AWS_PARTITION_GLOBAL_SERVICES = Arrays.asList( "budgets", "cloudfront", "iam", "route53", "shield", "waf"); private static final List<String> AWS_PARTITION_REGIONALIZED_SERVICES = Arrays.asList( "acm", "apigateway", "application-autoscaling", "appstream2", "autoscaling", "batch", "cloudformation", "cloudhsm", "cloudsearch", "cloudtrail", "codebuild", "codecommit", "codedeploy", "codepipeline", "cognito-identity", "cognito-idp", "cognito-sync", "config", "cur", "data.iot", "datapipeline", "directconnect", "dms", "ds", "dynamodb", "ec2", "ecs", "elasticache", "elasticbeanstalk", "elasticfilesystem", "elasticloadbalancing", "elasticmapreduce", "elastictranscoder", "email", "es", "events", "firehose", "gamelift", "glacier", "inspector", "iot", "kinesis", "kinesisanalytics", "kms", "lambda", "lightsail", "logs", "machinelearning", "marketplacecommerceanalytics", "metering.marketplace", "mobileanalytics", "monitoring", "opsworks", "opsworks-cm", "pinpoint", "polly", "rds", "redshift", "rekognition", "route53domains", "s3", "sdb", "servicecatalog", "sms", "snowball", "sns", "sqs", "ssm", "states", "storagegateway", "streams.dynamodb", "sts", "support", "swf", "waf-regional", "workspaces", "xray"); private static final List<String> AWS_CN_PARTITION_GLOBAL_SERVICES = Arrays.asList("iam"); private static final List<String> AWS_CN_PARTITION_REGIONALIZED_SERVICES = Arrays.asList( "autoscaling", "cloudformation", "cloudtrail", "config", "directconnect", "dynamodb", "ec2", "elasticache", "elasticbeanstalk", "elasticloadbalancing", "elasticmapreduce", "events", "glacier", "kinesis", "logs", "monitoring", "rds", "redshift", "s3", "sns", "sqs", "storagegateway", "streams.dynamodb", "sts", "swf"); private static final List<String> AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES = Arrays.asList( "autoscaling", "cloudformation", "cloudhsm", "cloudtrail", "config", "directconnect", "dynamodb", "ec2", "elasticache", "elasticloadbalancing", "elasticmapreduce", "glacier", "kms", "logs", "monitoring", "rds", "redshift", "s3", "snowball", "sns", "sqs", "streams.dynamodb", "sts", "swf"); private static final List<String> AWS_US_GOV_PARTITION_GLOBAL_SERVICES = Arrays.asList("iam"); @Test public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsPartition() { AWS_PARTITION_REGIONALIZED_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.US_EAST_1)).isNotNull()); } @Test public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsGlobalRegion() { AWS_PARTITION_GLOBAL_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_GLOBAL)).isNotNull()); } @Test public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsCnPartition() { AWS_CN_PARTITION_REGIONALIZED_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.CN_NORTH_1)).isNotNull()); } @Test public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsCnGlobalRegion() { AWS_CN_PARTITION_GLOBAL_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_CN_GLOBAL)).isNotNull()); } @Test public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsUsGovPartition() { AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.US_GOV_WEST_1)).isNotNull()); } @Test public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsUsGovGlobalRegion() { AWS_US_GOV_PARTITION_GLOBAL_SERVICES.forEach( s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_US_GOV_GLOBAL)).isNotNull()); } @Test public void regions_ReturnsGreaterThan15Regions_ForS3() { assertThat(ServiceMetadata.of("s3").regions().size()).isGreaterThan(15); } @Test public void servicePartitions_ReturnsAllValidPartitions() { validateServicesAreInPartition(AWS_PARTITION_GLOBAL_SERVICES, "aws"); validateServicesAreInPartition(AWS_PARTITION_REGIONALIZED_SERVICES, "aws"); validateServicesAreInPartition(AWS_CN_PARTITION_GLOBAL_SERVICES, "aws-cn"); validateServicesAreInPartition(AWS_CN_PARTITION_REGIONALIZED_SERVICES, "aws-cn"); validateServicesAreInPartition(AWS_US_GOV_PARTITION_GLOBAL_SERVICES, "aws-us-gov"); validateServicesAreInPartition(AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES, "aws-us-gov"); } @Test public void servicePartitions_HasGlobalEndpoint_ForGlobalServices() { validateHasGlobalEndpointInPartition(AWS_PARTITION_GLOBAL_SERVICES, "aws", true); validateHasGlobalEndpointInPartition(AWS_CN_PARTITION_GLOBAL_SERVICES, "aws-cn", true); validateHasGlobalEndpointInPartition(AWS_US_GOV_PARTITION_GLOBAL_SERVICES, "aws-us-gov", true); } @Test public void servicePartitions_HasNoGlobalEndpoint_ForRegionalServices() { validateHasGlobalEndpointInPartition(AWS_PARTITION_REGIONALIZED_SERVICES, "aws", false); validateHasGlobalEndpointInPartition(AWS_CN_PARTITION_REGIONALIZED_SERVICES, "aws-cn", false); validateHasGlobalEndpointInPartition(AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES, "aws-us-gov", false); } private void validateHasGlobalEndpointInPartition(List<String> services, String partition, boolean hasGlobalEndpoint) { services.forEach(s -> assertThat(ServiceMetadata.of(s) .servicePartitions() .stream() .filter(sp -> sp.partition().id().equals(partition)) .anyMatch(sp -> sp.globalRegion().isPresent())) .as(s + " is global in " + partition) .isEqualTo(hasGlobalEndpoint)); } private void validateServicesAreInPartition(List<String> services, String partition) { services.forEach(s -> assertThat(ServiceMetadata.of(s) .servicePartitions() .stream() .map(p -> p.partition().id()) .collect(Collectors.toList())) .as(s + " is in " + partition) .contains(partition)); } }
1,295
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/servicemetadata/GeneratedServiceMetadataProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.servicemetadata; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.GeneratedServiceMetadataProvider; public class GeneratedServiceMetadataProviderTest { private static final GeneratedServiceMetadataProvider PROVIDER = new GeneratedServiceMetadataProvider(); @Test public void s3Metadata_isEnhanced() { assertThat(PROVIDER.serviceMetadata("s3")).isInstanceOf(EnhancedS3ServiceMetadata.class); } }
1,296
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/servicemetadata/EnhancedS3ServiceMetadataTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.servicemetadata; import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.Validate; @RunWith(Parameterized.class) public class EnhancedS3ServiceMetadataTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); private static final URI S3_GLOBAL_ENDPOINT = URI.create("s3.amazonaws.com"); private static final URI S3_IAD_REGIONAL_ENDPOINT = URI.create("s3.us-east-1.amazonaws.com"); private ServiceMetadata enhancedMetadata = new EnhancedS3ServiceMetadata(); @Parameterized.Parameter public TestData testData; @Parameterized.Parameters public static Collection<Object> data() { return Arrays.asList(new Object[] { // Test defaults new TestData(null, null, null, null, S3_GLOBAL_ENDPOINT), // Test precedence new TestData("regional", null, null, null, S3_IAD_REGIONAL_ENDPOINT), new TestData("test", "regional", "/profileconfig/s3_regional_config_profile.tst", "regional", S3_GLOBAL_ENDPOINT), new TestData(null, "regional", "/profileconfig/s3_regional_config_profile.tst", "non-regional", S3_IAD_REGIONAL_ENDPOINT), new TestData(null, null, "/profileconfig/s3_regional_config_profile.tst", "non-regional", S3_IAD_REGIONAL_ENDPOINT), new TestData(null, null, null, "regional", S3_IAD_REGIONAL_ENDPOINT), // Test capitalization standardization new TestData("rEgIONal", null, null, null, S3_IAD_REGIONAL_ENDPOINT), new TestData(null, "rEgIONal", null, null, S3_IAD_REGIONAL_ENDPOINT), new TestData(null, null, "/profileconfig/s3_regional_config_profile_mixed_case.tst", null, S3_IAD_REGIONAL_ENDPOINT), new TestData(null, null, null, "rEgIONal", S3_IAD_REGIONAL_ENDPOINT), // Test other value new TestData("othervalue", null, null, null, S3_GLOBAL_ENDPOINT), new TestData(null, "dafsad", null, null, S3_GLOBAL_ENDPOINT), new TestData(null, null, "/profileconfig/s3_regional_config_profile_non_regional.tst", null, S3_GLOBAL_ENDPOINT), new TestData(null, null, null, "somehtingelse", S3_GLOBAL_ENDPOINT), }); } @After public void methodSetup() { ENVIRONMENT_VARIABLE_HELPER.reset(); System.clearProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()); } @Test public void differentCombinationOfConfigs_shouldResolveCorrectly() { enhancedMetadata = new EnhancedS3ServiceMetadata().reconfigure(c -> c.putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, testData.advancedOption)); if (testData.envVarValue != null) { ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(), testData.envVarValue); } if (testData.systemProperty != null) { System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), testData.systemProperty); } if (testData.configFile != null) { String diskLocationForFile = diskLocationForConfig(testData.configFile); Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable."); ProfileFile file = ProfileFile.builder() .content(Paths.get(diskLocationForFile)) .type(ProfileFile.Type.CONFIGURATION) .build(); enhancedMetadata = enhancedMetadata.reconfigure(c -> c.profileFile(() -> file) .profileName("regional_s3_endpoint") .putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, testData.advancedOption)); } URI result = enhancedMetadata.endpointFor(Region.US_EAST_1); assertThat(result).isEqualTo(testData.expected); } private String diskLocationForConfig(String configFileName) { return getClass().getResource(configFileName).getFile(); } private static class TestData { private final String envVarValue; private final String systemProperty; private final String configFile; private final String advancedOption; private final URI expected; TestData(String systemProperty, String envVarValue, String configFile, String advancedOption, URI expected) { this.envVarValue = envVarValue; this.systemProperty = systemProperty; this.configFile = configFile; this.advancedOption = advancedOption; this.expected = expected; } } }
1,297
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/util/HttpCredentialsUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.junit.BeforeClass; import org.junit.ClassRule; 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.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.regions.internal.util.ConnectionUtils; import software.amazon.awssdk.regions.internal.util.SocketUtils; @RunWith(MockitoJUnitRunner.class) public class HttpCredentialsUtilsTest { @ClassRule public static WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false); private static final String CREDENTIALS_PATH = "/dummy/credentials/path"; private static final String SUCCESS_BODY = "{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\"," + "\"Token\":\"TOKEN_TOKEN_TOKEN\",\"Expiration\":\"3000-05-03T04:55:54Z\"}"; private static URI endpoint; private static Map<String, String> headers = new HashMap<String, String>() { { put("User-Agent", SdkUserAgent.create().userAgent()); put("Accept", "*/*"); put("Connection", "keep-alive"); } }; private static CustomRetryPolicy customRetryPolicy; private static HttpResourcesUtils httpCredentialsUtils; @Mock private ConnectionUtils mockConnection; @BeforeClass public static void setup() throws URISyntaxException { endpoint = new URI("http://localhost:" + mockServer.port() + CREDENTIALS_PATH); customRetryPolicy = new CustomRetryPolicy(); httpCredentialsUtils = HttpResourcesUtils.instance(); } /** * When a connection to end host cannot be opened, throws {@link IOException}. */ @Test(expected = IOException.class) public void readResourceThrowsIOExceptionWhenNoConnection() throws IOException, URISyntaxException { int port = 0; try { port = SocketUtils.getUnusedPort(); } catch (IOException ioexception) { fail("Unable to find an unused port"); } httpCredentialsUtils.readResource(new URI("http://localhost:" + port)); } /** * When server returns with status code 200, * the test successfully returns the body from the response. */ @Test public void readResouceReturnsResponseBodyFor200Response() throws IOException { generateStub(200, SUCCESS_BODY); assertEquals(SUCCESS_BODY, httpCredentialsUtils.readResource(endpoint)); } /** * When server returns with 404 status code, * the test should throw SdkClientException. */ @Test public void readResouceReturnsAceFor404ErrorResponse() throws Exception { try { httpCredentialsUtils.readResource(new URI("http://localhost:" + mockServer.port() + "/dummyPath")); fail("Expected SdkClientException"); } catch (SdkClientException ace) { assertTrue(ace.getMessage().contains("The requested metadata is not found at")); } } /** * When server returns a status code other than 200 and 404, * the test should throw SdkServiceException. The request * is not retried. */ @Test public void readResouceReturnsServiceExceptionFor5xxResponse() throws IOException { generateStub(500, "{\"code\":\"500 Internal Server Error\",\"message\":\"ERROR_MESSAGE\"}"); try { httpCredentialsUtils.readResource(endpoint); fail("Expected SdkServiceException"); } catch (SdkServiceException exception) { assertEquals(500, exception.statusCode()); } } /** * When server returns a status code other than 200 and 404 * and error body message is not in Json format, * the test throws SdkServiceException. */ @Test public void readResouceNonJsonErrorBody() throws IOException { generateStub(500, "Non Json error body"); try { httpCredentialsUtils.readResource(endpoint); fail("Expected SdkServiceException"); } catch (SdkServiceException exception) { assertEquals(500, exception.statusCode()); } } /** * When readResource is called with default retry policy and IOException occurs, * the request is not retried. */ @Test public void readResouceWithDefaultRetryPolicy_DoesNotRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenThrow(new IOException()); try { new HttpResourcesUtils(mockConnection).readResource(endpoint); fail("Expected an IOexception"); } catch (IOException exception) { Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(endpoint, headers, "GET"); } } /** * When readResource is called with custom retry policy and IOException occurs, * the request is retried and the number of retries is equal to the value * returned by getMaxRetries method of the custom retry policy. */ @Test public void readResouceWithCustomRetryPolicy_DoesRetry_ForIoException() throws IOException { Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenThrow(new IOException()); try { new HttpResourcesUtils(mockConnection).readResource(endpointProvider(endpoint, customRetryPolicy)); fail("Expected an IOexception"); } catch (IOException exception) { Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(endpoint, headers, "GET"); } } /** * When readResource is called with custom retry policy * and the exception is not an IOException, * then the request is not retried. */ @Test public void readResouceWithCustomRetryPolicy_DoesNotRetry_ForNonIoException() throws IOException { generateStub(500, "Non Json error body"); Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenCallRealMethod(); try { new HttpResourcesUtils(mockConnection).readResource(endpointProvider(endpoint, customRetryPolicy)); fail("Expected an SdkServiceException"); } catch (SdkServiceException exception) { Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(endpoint, headers, "GET"); } } private void generateStub(int statusCode, String message) { WireMock.stubFor( WireMock.get(WireMock.urlPathEqualTo(CREDENTIALS_PATH)) .willReturn(WireMock.aResponse() .withStatus(statusCode) .withHeader("Content-Type", "application/json") .withHeader("charset", "utf-8") .withBody(message))); } /** * Retry policy that retries only if a request fails with an IOException. */ private static class CustomRetryPolicy implements ResourcesEndpointRetryPolicy { private static final int MAX_RETRIES = 3; @Override public boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams) { if (retriesAttempted >= MAX_RETRIES) { return false; } if (retryParams.getException() != null && retryParams.getException() instanceof IOException) { return true; } return false; } } private static ResourcesEndpointProvider endpointProvider(URI endpoint, ResourcesEndpointRetryPolicy retryPolicy) { return new ResourcesEndpointProvider() { @Override public URI endpoint() throws IOException { return endpoint; } @Override public ResourcesEndpointRetryPolicy retryPolicy() { return retryPolicy; } }; } }
1,298
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/AwsRegionProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import static org.junit.Assert.assertEquals; 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 org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; public class AwsRegionProviderChainTest { @Test public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() { AwsRegionProvider providerOne = mock(AwsRegionProvider.class); AwsRegionProvider providerTwo = mock(AwsRegionProvider.class); AwsRegionProvider providerThree = mock(AwsRegionProvider.class); AwsRegionProviderChain chain = new AwsRegionProviderChain(providerOne, providerTwo, providerThree); final Region expectedRegion = Region.of("some-region-string"); when(providerOne.getRegion()).thenReturn(expectedRegion); assertEquals(expectedRegion, chain.getRegion()); verify(providerTwo, never()).getRegion(); verify(providerThree, never()).getRegion(); } @Test public void lastProviderInChainGivesRegionInformation() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } @Test public void providerThrowsException_ContinuesToNextInChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FaultyAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } /** * Only Exceptions should be caught and continued, Errors should propagate to caller and short * circuit the chain. */ @Test(expected = Error.class) public void providerThrowsError_DoesNotContinueChain() { final Region expectedRegion = Region.of("some-region-string"); AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new FatalAwsRegionProvider(), new StaticAwsRegionProvider( expectedRegion)); assertEquals(expectedRegion, chain.getRegion()); } @Test (expected = SdkClientException.class) public void noProviderGivesRegion_ThrowsException() { AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(), new NeverAwsRegionProvider(), new NeverAwsRegionProvider()); chain.getRegion(); } private static class NeverAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { return null; } } private static class StaticAwsRegionProvider implements AwsRegionProvider { private final Region region; public StaticAwsRegionProvider(Region region) { this.region = region; } @Override public Region getRegion() { return region; } } private static class FaultyAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { throw SdkClientException.builder().message("Unable to fetch region info").build(); } } private static class FatalAwsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { throw new Error("Something really bad happened"); } } }
1,299